es6.js 4.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers.slice();
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers ? samplers.slice() : [];
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. var vertexSource;
  197. var fragmentSource;
  198. if (baseName.vertexElement) {
  199. vertexSource = document.getElementById(baseName.vertexElement);
  200. if (!vertexSource) {
  201. vertexSource = baseName.vertexElement;
  202. }
  203. }
  204. else {
  205. vertexSource = baseName.vertex || baseName;
  206. }
  207. if (baseName.fragmentElement) {
  208. fragmentSource = document.getElementById(baseName.fragmentElement);
  209. if (!fragmentSource) {
  210. fragmentSource = baseName.fragmentElement;
  211. }
  212. }
  213. else {
  214. fragmentSource = baseName.fragment || baseName;
  215. }
  216. this._loadVertexShader(vertexSource, function (vertexCode) {
  217. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  218. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  219. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  220. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  221. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  222. if (baseName) {
  223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  227. }
  228. else {
  229. _this._vertexSourceCode = migratedVertexCode;
  230. _this._fragmentSourceCode = migratedFragmentCode;
  231. }
  232. _this._prepareEffect();
  233. });
  234. });
  235. });
  236. });
  237. });
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShader = function (vertex, callback) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. callback(vertexCode);
  352. return;
  353. }
  354. }
  355. // Base64 encoded ?
  356. if (vertex.substr(0, 7) === "base64:") {
  357. var vertexBinary = window.atob(vertex.substr(7));
  358. callback(vertexBinary);
  359. return;
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  364. return;
  365. }
  366. var vertexShaderUrl;
  367. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  368. vertexShaderUrl = vertex;
  369. }
  370. else {
  371. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  372. }
  373. // Vertex shader
  374. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  375. };
  376. /** @ignore */
  377. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  378. if (BABYLON.Tools.IsWindowObjectExist()) {
  379. // DOM element ?
  380. if (fragment instanceof HTMLElement) {
  381. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  382. callback(fragmentCode);
  383. return;
  384. }
  385. }
  386. // Base64 encoded ?
  387. if (fragment.substr(0, 7) === "base64:") {
  388. var fragmentBinary = window.atob(fragment.substr(7));
  389. callback(fragmentBinary);
  390. return;
  391. }
  392. // Is in local store ?
  393. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  394. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  395. return;
  396. }
  397. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  398. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  399. return;
  400. }
  401. var fragmentShaderUrl;
  402. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  403. fragmentShaderUrl = fragment;
  404. }
  405. else {
  406. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  407. }
  408. // Fragment shader
  409. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  410. };
  411. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  412. // Rebuild shaders source code
  413. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  414. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  415. vertexCode = prefix + vertexCode;
  416. fragmentCode = prefix + fragmentCode;
  417. // Number lines of shaders source code
  418. var i = 2;
  419. var regex = /\n/gm;
  420. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  421. i = 2;
  422. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. // Dump shaders name and formatted source code
  424. if (this.name.vertexElement) {
  425. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  426. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  427. }
  428. else if (this.name.vertex) {
  429. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  430. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  431. }
  432. else {
  433. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  434. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  435. }
  436. };
  437. ;
  438. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  439. var preparedSourceCode = this._processPrecision(sourceCode);
  440. if (this._engine.webGLVersion == 1) {
  441. callback(preparedSourceCode);
  442. return;
  443. }
  444. // Already converted
  445. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  446. callback(preparedSourceCode.replace("#version 300 es", ""));
  447. return;
  448. }
  449. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  450. // Remove extensions
  451. // #extension GL_OES_standard_derivatives : enable
  452. // #extension GL_EXT_shader_texture_lod : enable
  453. // #extension GL_EXT_frag_depth : enable
  454. // #extension GL_EXT_draw_buffers : require
  455. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  456. var result = preparedSourceCode.replace(regex, "");
  457. // Migrate to GLSL v300
  458. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  459. result = result.replace(/attribute[ \t]/g, "in ");
  460. result = result.replace(/[ \t]attribute/g, " in");
  461. if (isFragment) {
  462. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  464. result = result.replace(/texture2D\s*\(/g, "texture(");
  465. result = result.replace(/textureCube\s*\(/g, "texture(");
  466. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  467. result = result.replace(/gl_FragColor/g, "glFragColor");
  468. result = result.replace(/gl_FragData/g, "glFragData");
  469. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  470. }
  471. callback(result);
  472. };
  473. Effect.prototype._processIncludes = function (sourceCode, callback) {
  474. var _this = this;
  475. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  476. var match = regex.exec(sourceCode);
  477. var returnValue = new String(sourceCode);
  478. while (match != null) {
  479. var includeFile = match[1];
  480. // Uniform declaration
  481. if (includeFile.indexOf("__decl__") !== -1) {
  482. includeFile = includeFile.replace(/__decl__/, "");
  483. if (this._engine.supportsUniformBuffers) {
  484. includeFile = includeFile.replace(/Vertex/, "Ubo");
  485. includeFile = includeFile.replace(/Fragment/, "Ubo");
  486. }
  487. includeFile = includeFile + "Declaration";
  488. }
  489. if (Effect.IncludesShadersStore[includeFile]) {
  490. // Substitution
  491. var includeContent = Effect.IncludesShadersStore[includeFile];
  492. if (match[2]) {
  493. var splits = match[3].split(",");
  494. for (var index = 0; index < splits.length; index += 2) {
  495. var source = new RegExp(splits[index], "g");
  496. var dest = splits[index + 1];
  497. includeContent = includeContent.replace(source, dest);
  498. }
  499. }
  500. if (match[4]) {
  501. var indexString = match[5];
  502. if (indexString.indexOf("..") !== -1) {
  503. var indexSplits = indexString.split("..");
  504. var minIndex = parseInt(indexSplits[0]);
  505. var maxIndex = parseInt(indexSplits[1]);
  506. var sourceIncludeContent = includeContent.slice(0);
  507. includeContent = "";
  508. if (isNaN(maxIndex)) {
  509. maxIndex = this._indexParameters[indexSplits[1]];
  510. }
  511. for (var i = minIndex; i < maxIndex; i++) {
  512. if (!this._engine.supportsUniformBuffers) {
  513. // Ubo replacement
  514. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  515. return p1 + "{X}";
  516. });
  517. }
  518. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  519. }
  520. }
  521. else {
  522. if (!this._engine.supportsUniformBuffers) {
  523. // Ubo replacement
  524. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  525. return p1 + "{X}";
  526. });
  527. }
  528. includeContent = includeContent.replace(/\{X\}/g, indexString);
  529. }
  530. }
  531. // Replace
  532. returnValue = returnValue.replace(match[0], includeContent);
  533. }
  534. else {
  535. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  536. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  537. Effect.IncludesShadersStore[includeFile] = fileContent;
  538. _this._processIncludes(returnValue, callback);
  539. });
  540. return;
  541. }
  542. match = regex.exec(sourceCode);
  543. }
  544. callback(returnValue);
  545. };
  546. Effect.prototype._processPrecision = function (source) {
  547. if (source.indexOf("precision highp float") === -1) {
  548. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  549. source = "precision mediump float;\n" + source;
  550. }
  551. else {
  552. source = "precision highp float;\n" + source;
  553. }
  554. }
  555. else {
  556. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  557. source = source.replace("precision highp float", "precision mediump float");
  558. }
  559. }
  560. return source;
  561. };
  562. /**
  563. * Recompiles the webGL program
  564. * @param vertexSourceCode The source code for the vertex shader.
  565. * @param fragmentSourceCode The source code for the fragment shader.
  566. * @param onCompiled Callback called when completed.
  567. * @param onError Callback called on error.
  568. */
  569. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  570. var _this = this;
  571. this._isReady = false;
  572. this._vertexSourceCodeOverride = vertexSourceCode;
  573. this._fragmentSourceCodeOverride = fragmentSourceCode;
  574. this.onError = function (effect, error) {
  575. if (onError) {
  576. onError(error);
  577. }
  578. };
  579. this.onCompiled = function () {
  580. var scenes = _this.getEngine().scenes;
  581. for (var i = 0; i < scenes.length; i++) {
  582. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  583. }
  584. if (onCompiled) {
  585. onCompiled(_this._program);
  586. }
  587. };
  588. this._fallbacks = null;
  589. this._prepareEffect();
  590. };
  591. /**
  592. * Gets the uniform locations of the the specified variable names
  593. * @param names THe names of the variables to lookup.
  594. * @returns Array of locations in the same order as variable names.
  595. */
  596. Effect.prototype.getSpecificUniformLocations = function (names) {
  597. var engine = this._engine;
  598. return engine.getUniforms(this._program, names);
  599. };
  600. /**
  601. * Prepares the effect
  602. */
  603. Effect.prototype._prepareEffect = function () {
  604. var attributesNames = this._attributesNames;
  605. var defines = this.defines;
  606. var fallbacks = this._fallbacks;
  607. this._valueCache = {};
  608. var previousProgram = this._program;
  609. try {
  610. var engine = this._engine;
  611. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  612. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  613. }
  614. else {
  615. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  616. }
  617. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  618. if (engine.supportsUniformBuffers) {
  619. for (var name in this._uniformBuffersNames) {
  620. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  621. }
  622. }
  623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  624. this._attributes = engine.getAttributes(this._program, attributesNames);
  625. var index;
  626. for (index = 0; index < this._samplers.length; index++) {
  627. var sampler = this.getUniform(this._samplers[index]);
  628. if (sampler == null) {
  629. this._samplers.splice(index, 1);
  630. index--;
  631. }
  632. }
  633. engine.bindSamplers(this);
  634. this._compilationError = "";
  635. this._isReady = true;
  636. if (this.onCompiled) {
  637. this.onCompiled(this);
  638. }
  639. this.onCompileObservable.notifyObservers(this);
  640. this.onCompileObservable.clear();
  641. // Unbind mesh reference in fallbacks
  642. if (this._fallbacks) {
  643. this._fallbacks.unBindMesh();
  644. }
  645. if (previousProgram) {
  646. this.getEngine()._deleteProgram(previousProgram);
  647. }
  648. }
  649. catch (e) {
  650. this._compilationError = e.message;
  651. // Let's go through fallbacks then
  652. BABYLON.Tools.Error("Unable to compile effect:");
  653. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  654. return " " + uniform;
  655. }));
  656. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  657. return " " + attribute;
  658. }));
  659. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  660. BABYLON.Tools.Error("Error: " + this._compilationError);
  661. if (previousProgram) {
  662. this._program = previousProgram;
  663. this._isReady = true;
  664. if (this.onError) {
  665. this.onError(this, this._compilationError);
  666. }
  667. this.onErrorObservable.notifyObservers(this);
  668. }
  669. if (fallbacks && fallbacks.isMoreFallbacks) {
  670. BABYLON.Tools.Error("Trying next fallback.");
  671. this.defines = fallbacks.reduce(this.defines, this);
  672. this._prepareEffect();
  673. }
  674. else {
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. this.onErrorObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. }
  685. }
  686. };
  687. Object.defineProperty(Effect.prototype, "isSupported", {
  688. /**
  689. * Checks if the effect is supported. (Must be called after compilation)
  690. */
  691. get: function () {
  692. return this._compilationError === "";
  693. },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. /**
  698. * Binds a texture to the engine to be used as output of the shader.
  699. * @param channel Name of the output variable.
  700. * @param texture Texture to bind.
  701. */
  702. Effect.prototype._bindTexture = function (channel, texture) {
  703. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  704. };
  705. /**
  706. * Sets a texture on the engine to be used in the shader.
  707. * @param channel Name of the sampler variable.
  708. * @param texture Texture to set.
  709. */
  710. Effect.prototype.setTexture = function (channel, texture) {
  711. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  712. };
  713. /**
  714. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  715. * @param channel Name of the sampler variable.
  716. * @param texture Texture to set.
  717. */
  718. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  719. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  720. };
  721. /**
  722. * Sets an array of textures on the engine to be used in the shader.
  723. * @param channel Name of the variable.
  724. * @param textures Textures to set.
  725. */
  726. Effect.prototype.setTextureArray = function (channel, textures) {
  727. if (this._samplers.indexOf(channel + "Ex") === -1) {
  728. var initialPos = this._samplers.indexOf(channel);
  729. for (var index = 1; index < textures.length; index++) {
  730. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  731. }
  732. }
  733. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  734. };
  735. /**
  736. * 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)
  737. * @param channel Name of the sampler variable.
  738. * @param postProcess Post process to get the input texture from.
  739. */
  740. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  741. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  742. };
  743. /**
  744. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  745. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  746. * @param channel Name of the sampler variable.
  747. * @param postProcess Post process to get the output texture from.
  748. */
  749. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  750. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  751. };
  752. /** @ignore */
  753. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  754. var cache = this._valueCache[uniformName];
  755. var flag = matrix.updateFlag;
  756. if (cache !== undefined && cache === flag) {
  757. return false;
  758. }
  759. this._valueCache[uniformName] = flag;
  760. return true;
  761. };
  762. /** @ignore */
  763. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  764. var cache = this._valueCache[uniformName];
  765. if (!cache) {
  766. cache = [x, y];
  767. this._valueCache[uniformName] = cache;
  768. return true;
  769. }
  770. var changed = false;
  771. if (cache[0] !== x) {
  772. cache[0] = x;
  773. changed = true;
  774. }
  775. if (cache[1] !== y) {
  776. cache[1] = y;
  777. changed = true;
  778. }
  779. return changed;
  780. };
  781. /** @ignore */
  782. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  783. var cache = this._valueCache[uniformName];
  784. if (!cache) {
  785. cache = [x, y, z];
  786. this._valueCache[uniformName] = cache;
  787. return true;
  788. }
  789. var changed = false;
  790. if (cache[0] !== x) {
  791. cache[0] = x;
  792. changed = true;
  793. }
  794. if (cache[1] !== y) {
  795. cache[1] = y;
  796. changed = true;
  797. }
  798. if (cache[2] !== z) {
  799. cache[2] = z;
  800. changed = true;
  801. }
  802. return changed;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y, z, w];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. if (cache[2] !== z) {
  822. cache[2] = z;
  823. changed = true;
  824. }
  825. if (cache[3] !== w) {
  826. cache[3] = w;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /**
  832. * Binds a buffer to a uniform.
  833. * @param buffer Buffer to bind.
  834. * @param name Name of the uniform variable to bind to.
  835. */
  836. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  837. var bufferName = this._uniformBuffersNames[name];
  838. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  839. return;
  840. }
  841. Effect._baseCache[bufferName] = buffer;
  842. this._engine.bindUniformBufferBase(buffer, bufferName);
  843. };
  844. /**
  845. * Binds block to a uniform.
  846. * @param blockName Name of the block to bind.
  847. * @param index Index to bind.
  848. */
  849. Effect.prototype.bindUniformBlock = function (blockName, index) {
  850. this._engine.bindUniformBlock(this._program, blockName, index);
  851. };
  852. /**
  853. * Sets an interger value on a uniform variable.
  854. * @param uniformName Name of the variable.
  855. * @param value Value to be set.
  856. * @returns this effect.
  857. */
  858. Effect.prototype.setInt = function (uniformName, value) {
  859. var cache = this._valueCache[uniformName];
  860. if (cache !== undefined && cache === value)
  861. return this;
  862. this._valueCache[uniformName] = value;
  863. this._engine.setInt(this.getUniform(uniformName), value);
  864. return this;
  865. };
  866. /**
  867. * Sets an int array on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param array array to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setIntArray = function (uniformName, array) {
  873. this._valueCache[uniformName] = null;
  874. this._engine.setIntArray(this.getUniform(uniformName), array);
  875. return this;
  876. };
  877. /**
  878. * 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)
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * 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)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray3 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray3(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * 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)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray4 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray4(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * Sets an float array on a uniform variable.
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setFloatArray = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setFloatArray(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * 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)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * 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)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * 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)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an array on a uniform variable.
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setArray = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setArray(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * 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)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray2 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray2(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * 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)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray3 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray3(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * 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)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray4 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray4(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets matrices on a uniform variable.
  1000. * @param uniformName Name of the variable.
  1001. * @param matrices matrices to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1005. if (!matrices) {
  1006. return this;
  1007. }
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrix on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrix matrix to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1019. if (this._cacheMatrix(uniformName, matrix)) {
  1020. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1021. }
  1022. return this;
  1023. };
  1024. /**
  1025. * 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)
  1026. * @param uniformName Name of the variable.
  1027. * @param matrix matrix to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1033. return this;
  1034. };
  1035. /**
  1036. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a float on a uniform variable.
  1048. * @param uniformName Name of the variable.
  1049. * @param value value to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloat = function (uniformName, value) {
  1053. var cache = this._valueCache[uniformName];
  1054. if (cache !== undefined && cache === value)
  1055. return this;
  1056. this._valueCache[uniformName] = value;
  1057. this._engine.setFloat(this.getUniform(uniformName), value);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a boolean on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param bool value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setBool = function (uniformName, bool) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === bool)
  1069. return this;
  1070. this._valueCache[uniformName] = bool;
  1071. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a Vector2 on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param vector2 vector2 to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1081. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1082. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1083. }
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a float2 on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param x First float in float2.
  1090. * @param y Second float in float2.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1094. if (this._cacheFloat2(uniformName, x, y)) {
  1095. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1096. }
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets a Vector3 on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param vector3 Value to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1106. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1107. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float3 on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param x First float in float3.
  1115. * @param y Second float in float3.
  1116. * @param z Third float in float3.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1120. if (this._cacheFloat3(uniformName, x, y, z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector4 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector4 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1132. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1133. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float4 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float4.
  1141. * @param y Second float in float4.
  1142. * @param z Third float in float4.
  1143. * @param w Fourth float in float4.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1147. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1148. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Color3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param color3 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setColor3 = function (uniformName, color3) {
  1159. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1160. this._engine.setColor3(this.getUniform(uniformName), color3);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Color4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param color3 Value to be set.
  1168. * @param alpha Alpha value to be set.
  1169. * @returns this effect.
  1170. */
  1171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1174. }
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Color4 on a uniform variable
  1179. * @param uniformName defines the name of the variable
  1180. * @param color4 defines the value to be set
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1184. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1185. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Resets the cache of effects.
  1191. */
  1192. Effect.ResetCache = function () {
  1193. Effect._baseCache = {};
  1194. };
  1195. Effect._uniqueIdSeed = 0;
  1196. Effect._baseCache = {};
  1197. /**
  1198. * Store of each shader (The can be looked up using effect.key)
  1199. */
  1200. Effect.ShadersStore = {};
  1201. /**
  1202. * Store of each included file for a shader (The can be looked up using effect.key)
  1203. */
  1204. Effect.IncludesShadersStore = {};
  1205. return Effect;
  1206. }());
  1207. BABYLON.Effect = Effect;
  1208. })(BABYLON || (BABYLON = {}));
  1209. //# sourceMappingURL=babylon.effect.js.map
  1210. "use strict";
  1211. //# sourceMappingURL=babylon.types.js.map
  1212. "use strict";
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. "use strict";
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var PointerEventTypes = /** @class */ (function () {
  1265. function PointerEventTypes() {
  1266. }
  1267. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1268. get: function () {
  1269. return PointerEventTypes._POINTERDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1275. get: function () {
  1276. return PointerEventTypes._POINTERUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1282. get: function () {
  1283. return PointerEventTypes._POINTERMOVE;
  1284. },
  1285. enumerable: true,
  1286. configurable: true
  1287. });
  1288. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1289. get: function () {
  1290. return PointerEventTypes._POINTERWHEEL;
  1291. },
  1292. enumerable: true,
  1293. configurable: true
  1294. });
  1295. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1296. get: function () {
  1297. return PointerEventTypes._POINTERPICK;
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1303. get: function () {
  1304. return PointerEventTypes._POINTERTAP;
  1305. },
  1306. enumerable: true,
  1307. configurable: true
  1308. });
  1309. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1310. get: function () {
  1311. return PointerEventTypes._POINTERDOUBLETAP;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. PointerEventTypes._POINTERDOWN = 0x01;
  1317. PointerEventTypes._POINTERUP = 0x02;
  1318. PointerEventTypes._POINTERMOVE = 0x04;
  1319. PointerEventTypes._POINTERWHEEL = 0x08;
  1320. PointerEventTypes._POINTERPICK = 0x10;
  1321. PointerEventTypes._POINTERTAP = 0x20;
  1322. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1323. return PointerEventTypes;
  1324. }());
  1325. BABYLON.PointerEventTypes = PointerEventTypes;
  1326. var PointerInfoBase = /** @class */ (function () {
  1327. function PointerInfoBase(type, event) {
  1328. this.type = type;
  1329. this.event = event;
  1330. }
  1331. return PointerInfoBase;
  1332. }());
  1333. BABYLON.PointerInfoBase = PointerInfoBase;
  1334. /**
  1335. * This class is used to store pointer related info for the onPrePointerObservable event.
  1336. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1337. */
  1338. var PointerInfoPre = /** @class */ (function (_super) {
  1339. __extends(PointerInfoPre, _super);
  1340. function PointerInfoPre(type, event, localX, localY) {
  1341. var _this = _super.call(this, type, event) || this;
  1342. _this.skipOnPointerObservable = false;
  1343. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1344. return _this;
  1345. }
  1346. return PointerInfoPre;
  1347. }(PointerInfoBase));
  1348. BABYLON.PointerInfoPre = PointerInfoPre;
  1349. /**
  1350. * This type contains all the data related to a pointer event in Babylon.js.
  1351. * 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.
  1352. */
  1353. var PointerInfo = /** @class */ (function (_super) {
  1354. __extends(PointerInfo, _super);
  1355. function PointerInfo(type, event, pickInfo) {
  1356. var _this = _super.call(this, type, event) || this;
  1357. _this.pickInfo = pickInfo;
  1358. return _this;
  1359. }
  1360. return PointerInfo;
  1361. }(PointerInfoBase));
  1362. BABYLON.PointerInfo = PointerInfo;
  1363. })(BABYLON || (BABYLON = {}));
  1364. //# sourceMappingURL=babylon.pointerEvents.js.map
  1365. "use strict";
  1366. var BABYLON;
  1367. (function (BABYLON) {
  1368. BABYLON.ToGammaSpace = 1 / 2.2;
  1369. BABYLON.ToLinearSpace = 2.2;
  1370. BABYLON.Epsilon = 0.001;
  1371. /**
  1372. * Class used to hold a RBG color
  1373. */
  1374. var Color3 = /** @class */ (function () {
  1375. /**
  1376. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1377. * @param r defines the red component (between 0 and 1, default is 0)
  1378. * @param g defines the green component (between 0 and 1, default is 0)
  1379. * @param b defines the blue component (between 0 and 1, default is 0)
  1380. */
  1381. function Color3(
  1382. /**
  1383. * Defines the red component (between 0 and 1, default is 0)
  1384. */
  1385. r,
  1386. /**
  1387. * Defines the green component (between 0 and 1, default is 0)
  1388. */
  1389. g,
  1390. /**
  1391. * Defines the blue component (between 0 and 1, default is 0)
  1392. */
  1393. b) {
  1394. if (r === void 0) { r = 0; }
  1395. if (g === void 0) { g = 0; }
  1396. if (b === void 0) { b = 0; }
  1397. this.r = r;
  1398. this.g = g;
  1399. this.b = b;
  1400. }
  1401. /**
  1402. * Creates a string with the Color3 current values
  1403. * @returns the string representation of the Color3 object
  1404. */
  1405. Color3.prototype.toString = function () {
  1406. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1407. };
  1408. /**
  1409. * Returns the string "Color3"
  1410. * @returns "Color3"
  1411. */
  1412. Color3.prototype.getClassName = function () {
  1413. return "Color3";
  1414. };
  1415. /**
  1416. * Compute the Color3 hash code
  1417. * @returns an unique number that can be used to hash Color3 objects
  1418. */
  1419. Color3.prototype.getHashCode = function () {
  1420. var hash = this.r || 0;
  1421. hash = (hash * 397) ^ (this.g || 0);
  1422. hash = (hash * 397) ^ (this.b || 0);
  1423. return hash;
  1424. };
  1425. // Operators
  1426. /**
  1427. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1428. * @param array defines the array where to store the r,g,b components
  1429. * @param index defines an optional index in the target array to define where to start storing values
  1430. * @returns the current Color3 object
  1431. */
  1432. Color3.prototype.toArray = function (array, index) {
  1433. if (index === undefined) {
  1434. index = 0;
  1435. }
  1436. array[index] = this.r;
  1437. array[index + 1] = this.g;
  1438. array[index + 2] = this.b;
  1439. return this;
  1440. };
  1441. /**
  1442. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1443. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1444. * @returns a new {BABYLON.Color4} object
  1445. */
  1446. Color3.prototype.toColor4 = function (alpha) {
  1447. if (alpha === void 0) { alpha = 1; }
  1448. return new Color4(this.r, this.g, this.b, alpha);
  1449. };
  1450. /**
  1451. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1452. * @returns the new array
  1453. */
  1454. Color3.prototype.asArray = function () {
  1455. var result = new Array();
  1456. this.toArray(result, 0);
  1457. return result;
  1458. };
  1459. /**
  1460. * Returns the luminance value
  1461. * @returns a float value
  1462. */
  1463. Color3.prototype.toLuminance = function () {
  1464. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1465. };
  1466. /**
  1467. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1468. * @param otherColor defines the second operand
  1469. * @returns the new Color3 object
  1470. */
  1471. Color3.prototype.multiply = function (otherColor) {
  1472. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1473. };
  1474. /**
  1475. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1476. * @param otherColor defines the second operand
  1477. * @param result defines the Color3 object where to store the result
  1478. * @returns the current Color3
  1479. */
  1480. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1481. result.r = this.r * otherColor.r;
  1482. result.g = this.g * otherColor.g;
  1483. result.b = this.b * otherColor.b;
  1484. return this;
  1485. };
  1486. /**
  1487. * Determines equality between Color3 objects
  1488. * @param otherColor defines the second operand
  1489. * @returns true if the rgb values are equal to the passed ones
  1490. */
  1491. Color3.prototype.equals = function (otherColor) {
  1492. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1493. };
  1494. /**
  1495. * Determines equality between the current Color3 object and a set of r,b,g values
  1496. * @param r defines the red component to check
  1497. * @param g defines the green component to check
  1498. * @param b defines the blue component to check
  1499. * @returns true if the rgb values are equal to the passed ones
  1500. */
  1501. Color3.prototype.equalsFloats = function (r, g, b) {
  1502. return this.r === r && this.g === g && this.b === b;
  1503. };
  1504. /**
  1505. * Multiplies in place each rgb value by scale
  1506. * @param scale defines the scaling factor
  1507. * @returns the updated Color3
  1508. */
  1509. Color3.prototype.scale = function (scale) {
  1510. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1511. };
  1512. /**
  1513. * Multiplies the rgb values by scale and stores the result into "result"
  1514. * @param scale defines the scaling factor
  1515. * @param result defines the Color3 object where to store the result
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.scaleToRef = function (scale, result) {
  1519. result.r = this.r * scale;
  1520. result.g = this.g * scale;
  1521. result.b = this.b * scale;
  1522. return this;
  1523. };
  1524. /**
  1525. * Scale the current Color3 values by a factor and add the result to a given Color3
  1526. * @param scale defines the scale factor
  1527. * @param result defines color to store the result into
  1528. * @returns the unmodified current Color3
  1529. */
  1530. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1531. result.r += this.r * scale;
  1532. result.g += this.g * scale;
  1533. result.b += this.b * scale;
  1534. return this;
  1535. };
  1536. /**
  1537. * Clamps the rgb values by the min and max values and stores the result into "result"
  1538. * @param min defines minimum clamping value (default is 0)
  1539. * @param max defines maximum clamping value (default is 1)
  1540. * @param result defines color to store the result into
  1541. * @returns the original Color3
  1542. */
  1543. Color3.prototype.clampToRef = function (min, max, result) {
  1544. if (min === void 0) { min = 0; }
  1545. if (max === void 0) { max = 1; }
  1546. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1547. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1548. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1549. return this;
  1550. };
  1551. /**
  1552. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1553. * @param otherColor defines the second operand
  1554. * @returns the new Color3
  1555. */
  1556. Color3.prototype.add = function (otherColor) {
  1557. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1558. };
  1559. /**
  1560. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1561. * @param otherColor defines the second operand
  1562. * @param result defines Color3 object to store the result into
  1563. * @returns the unmodified current Color3
  1564. */
  1565. Color3.prototype.addToRef = function (otherColor, result) {
  1566. result.r = this.r + otherColor.r;
  1567. result.g = this.g + otherColor.g;
  1568. result.b = this.b + otherColor.b;
  1569. return this;
  1570. };
  1571. /**
  1572. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3
  1575. */
  1576. Color3.prototype.subtract = function (otherColor) {
  1577. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1578. };
  1579. /**
  1580. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines Color3 object to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.subtractToRef = function (otherColor, result) {
  1586. result.r = this.r - otherColor.r;
  1587. result.g = this.g - otherColor.g;
  1588. result.b = this.b - otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Copy the current object
  1593. * @returns a new Color3 copied the current one
  1594. */
  1595. Color3.prototype.clone = function () {
  1596. return new Color3(this.r, this.g, this.b);
  1597. };
  1598. /**
  1599. * Copies the rgb values from the source in the current Color3
  1600. * @param source defines the source Color3 object
  1601. * @returns the updated Color3 object
  1602. */
  1603. Color3.prototype.copyFrom = function (source) {
  1604. this.r = source.r;
  1605. this.g = source.g;
  1606. this.b = source.b;
  1607. return this;
  1608. };
  1609. /**
  1610. * Updates the Color3 rgb values from the passed floats
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @returns the current Color3 object
  1615. */
  1616. Color3.prototype.copyFromFloats = function (r, g, b) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. return this;
  1621. };
  1622. /**
  1623. * Updates the Color3 rgb values from the passed floats
  1624. * @param r defines the red component to read from
  1625. * @param g defines the green component to read from
  1626. * @param b defines the blue component to read from
  1627. * @returns the current Color3 object
  1628. */
  1629. Color3.prototype.set = function (r, g, b) {
  1630. return this.copyFromFloats(r, g, b);
  1631. };
  1632. /**
  1633. * Compute the Color3 hexadecimal code as a string
  1634. * @returns a string containing the hexadecimal representation of the Color3 object
  1635. */
  1636. Color3.prototype.toHexString = function () {
  1637. var intR = (this.r * 255) | 0;
  1638. var intG = (this.g * 255) | 0;
  1639. var intB = (this.b * 255) | 0;
  1640. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1641. };
  1642. /**
  1643. * Computes a new Color3 converted from the current one to linear space
  1644. * @returns a new Color3 object
  1645. */
  1646. Color3.prototype.toLinearSpace = function () {
  1647. var convertedColor = new Color3();
  1648. this.toLinearSpaceToRef(convertedColor);
  1649. return convertedColor;
  1650. };
  1651. /**
  1652. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1653. * @param convertedColor defines the Color3 object where to store the linear space version
  1654. * @returns the unmodified Color3
  1655. */
  1656. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1657. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1658. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1659. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1660. return this;
  1661. };
  1662. /**
  1663. * Computes a new Color3 converted from the current one to gamma space
  1664. * @returns a new Color3 object
  1665. */
  1666. Color3.prototype.toGammaSpace = function () {
  1667. var convertedColor = new Color3();
  1668. this.toGammaSpaceToRef(convertedColor);
  1669. return convertedColor;
  1670. };
  1671. /**
  1672. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1673. * @param convertedColor defines the Color3 object where to store the gamma space version
  1674. * @returns the unmodified Color3
  1675. */
  1676. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1677. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1678. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1679. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1680. return this;
  1681. };
  1682. // Statics
  1683. /**
  1684. * Creates a new Color3 from the string containing valid hexadecimal values
  1685. * @param hex defines a string containing valid hexadecimal values
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.FromHexString = function (hex) {
  1689. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1690. return new Color3(0, 0, 0);
  1691. }
  1692. var r = parseInt(hex.substring(1, 3), 16);
  1693. var g = parseInt(hex.substring(3, 5), 16);
  1694. var b = parseInt(hex.substring(5, 7), 16);
  1695. return Color3.FromInts(r, g, b);
  1696. };
  1697. /**
  1698. * Creates a new Vector3 from the starting index of the passed array
  1699. * @param array defines the source array
  1700. * @param offset defines an offset in the source array
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.FromArray = function (array, offset) {
  1704. if (offset === void 0) { offset = 0; }
  1705. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1706. };
  1707. /**
  1708. * Creates a new Color3 from integer values (< 256)
  1709. * @param r defines the red component to read from (value between 0 and 255)
  1710. * @param g defines the green component to read from (value between 0 and 255)
  1711. * @param b defines the blue component to read from (value between 0 and 255)
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.FromInts = function (r, g, b) {
  1715. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1716. };
  1717. /**
  1718. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1719. * @param start defines the start Color3 value
  1720. * @param end defines the end Color3 value
  1721. * @param amount defines the gradient value between start and end
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Lerp = function (start, end, amount) {
  1725. var r = start.r + ((end.r - start.r) * amount);
  1726. var g = start.g + ((end.g - start.g) * amount);
  1727. var b = start.b + ((end.b - start.b) * amount);
  1728. return new Color3(r, g, b);
  1729. };
  1730. /**
  1731. * Returns a Color3 value containing a red color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Red = function () { return new Color3(1, 0, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a green color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Green = function () { return new Color3(0, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a blue color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1745. /**
  1746. * Returns a Color3 value containing a black color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Black = function () { return new Color3(0, 0, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a white color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.White = function () { return new Color3(1, 1, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a purple color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1760. /**
  1761. * Returns a Color3 value containing a magenta color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a yellow color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a gray color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1775. /**
  1776. * Returns a Color3 value containing a teal color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1780. /**
  1781. * Returns a Color3 value containing a random color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1785. return Color3;
  1786. }());
  1787. BABYLON.Color3 = Color3;
  1788. /**
  1789. * Class used to hold a RBGA color
  1790. */
  1791. var Color4 = /** @class */ (function () {
  1792. /**
  1793. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1794. * @param r defines the red component (between 0 and 1, default is 0)
  1795. * @param g defines the green component (between 0 and 1, default is 0)
  1796. * @param b defines the blue component (between 0 and 1, default is 0)
  1797. * @param a defines the alpha component (between 0 and 1, default is 1)
  1798. */
  1799. function Color4(
  1800. /**
  1801. * Defines the red component (between 0 and 1, default is 0)
  1802. */
  1803. r,
  1804. /**
  1805. * Defines the green component (between 0 and 1, default is 0)
  1806. */
  1807. g,
  1808. /**
  1809. * Defines the blue component (between 0 and 1, default is 0)
  1810. */
  1811. b,
  1812. /**
  1813. * Defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. a) {
  1816. if (r === void 0) { r = 0; }
  1817. if (g === void 0) { g = 0; }
  1818. if (b === void 0) { b = 0; }
  1819. if (a === void 0) { a = 1; }
  1820. this.r = r;
  1821. this.g = g;
  1822. this.b = b;
  1823. this.a = a;
  1824. }
  1825. // Operators
  1826. /**
  1827. * Adds in place the passed Color4 values to the current Color4 object
  1828. * @param right defines the second operand
  1829. * @returns the current updated Color4 object
  1830. */
  1831. Color4.prototype.addInPlace = function (right) {
  1832. this.r += right.r;
  1833. this.g += right.g;
  1834. this.b += right.b;
  1835. this.a += right.a;
  1836. return this;
  1837. };
  1838. /**
  1839. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1840. * @returns the new array
  1841. */
  1842. Color4.prototype.asArray = function () {
  1843. var result = new Array();
  1844. this.toArray(result, 0);
  1845. return result;
  1846. };
  1847. /**
  1848. * Stores from the starting index in the passed array the Color4 successive values
  1849. * @param array defines the array where to store the r,g,b components
  1850. * @param index defines an optional index in the target array to define where to start storing values
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.toArray = function (array, index) {
  1854. if (index === undefined) {
  1855. index = 0;
  1856. }
  1857. array[index] = this.r;
  1858. array[index + 1] = this.g;
  1859. array[index + 2] = this.b;
  1860. array[index + 3] = this.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.add = function (right) {
  1869. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1870. };
  1871. /**
  1872. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1873. * @param right defines the second operand
  1874. * @returns a new Color4 object
  1875. */
  1876. Color4.prototype.subtract = function (right) {
  1877. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1878. };
  1879. /**
  1880. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1881. * @param right defines the second operand
  1882. * @param result defines the Color4 object where to store the result
  1883. * @returns the current Color4 object
  1884. */
  1885. Color4.prototype.subtractToRef = function (right, result) {
  1886. result.r = this.r - right.r;
  1887. result.g = this.g - right.g;
  1888. result.b = this.b - right.b;
  1889. result.a = this.a - right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 with the current Color4 values multiplied by scale
  1894. * @param scale defines the scaling factor to apply
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.scale = function (scale) {
  1898. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1899. };
  1900. /**
  1901. * Multiplies the current Color4 values by scale and stores the result in "result"
  1902. * @param scale defines the scaling factor to apply
  1903. * @param result defines the Color4 object where to store the result
  1904. * @returns the current unmodified Color4
  1905. */
  1906. Color4.prototype.scaleToRef = function (scale, result) {
  1907. result.r = this.r * scale;
  1908. result.g = this.g * scale;
  1909. result.b = this.b * scale;
  1910. result.a = this.a * scale;
  1911. return this;
  1912. };
  1913. /**
  1914. * Scale the current Color4 values by a factor and add the result to a given Color4
  1915. * @param scale defines the scale factor
  1916. * @param result defines the Color4 object where to store the result
  1917. * @returns the unmodified current Color4
  1918. */
  1919. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1920. result.r += this.r * scale;
  1921. result.g += this.g * scale;
  1922. result.b += this.b * scale;
  1923. result.a += this.a * scale;
  1924. return this;
  1925. };
  1926. /**
  1927. * Clamps the rgb values by the min and max values and stores the result into "result"
  1928. * @param min defines minimum clamping value (default is 0)
  1929. * @param max defines maximum clamping value (default is 1)
  1930. * @param result defines color to store the result into.
  1931. * @returns the cuurent Color4
  1932. */
  1933. Color4.prototype.clampToRef = function (min, max, result) {
  1934. if (min === void 0) { min = 0; }
  1935. if (max === void 0) { max = 1; }
  1936. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1937. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1938. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1939. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1940. return this;
  1941. };
  1942. /**
  1943. * Multipy an Color4 value by another and return a new Color4 object
  1944. * @param color defines the Color4 value to multiply by
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.multiply = function (color) {
  1948. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1949. };
  1950. /**
  1951. * Multipy a Color4 value by another and push the result in a reference value
  1952. * @param color defines the Color4 value to multiply by
  1953. * @param result defines the Color4 to fill the result in
  1954. * @returns the result Color4
  1955. */
  1956. Color4.prototype.multiplyToRef = function (color, result) {
  1957. result.r = this.r * color.r;
  1958. result.g = this.g * color.g;
  1959. result.b = this.b * color.b;
  1960. result.a = this.a * color.a;
  1961. return result;
  1962. };
  1963. /**
  1964. * Creates a string with the Color4 current values
  1965. * @returns the string representation of the Color4 object
  1966. */
  1967. Color4.prototype.toString = function () {
  1968. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1969. };
  1970. /**
  1971. * Returns the string "Color4"
  1972. * @returns "Color4"
  1973. */
  1974. Color4.prototype.getClassName = function () {
  1975. return "Color4";
  1976. };
  1977. /**
  1978. * Compute the Color4 hash code
  1979. * @returns an unique number that can be used to hash Color4 objects
  1980. */
  1981. Color4.prototype.getHashCode = function () {
  1982. var hash = this.r || 0;
  1983. hash = (hash * 397) ^ (this.g || 0);
  1984. hash = (hash * 397) ^ (this.b || 0);
  1985. hash = (hash * 397) ^ (this.a || 0);
  1986. return hash;
  1987. };
  1988. /**
  1989. * Creates a new Color4 copied from the current one
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.clone = function () {
  1993. return new Color4(this.r, this.g, this.b, this.a);
  1994. };
  1995. /**
  1996. * Copies the passed Color4 values into the current one
  1997. * @param source defines the source Color4 object
  1998. * @returns the current updated Color4 object
  1999. */
  2000. Color4.prototype.copyFrom = function (source) {
  2001. this.r = source.r;
  2002. this.g = source.g;
  2003. this.b = source.b;
  2004. this.a = source.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Copies the passed float values into the current one
  2009. * @param r defines the red component to read from
  2010. * @param g defines the green component to read from
  2011. * @param b defines the blue component to read from
  2012. * @param a defines the alpha component to read from
  2013. * @returns the current updated Color4 object
  2014. */
  2015. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2016. this.r = r;
  2017. this.g = g;
  2018. this.b = b;
  2019. this.a = a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Copies the passed float values into the current one
  2024. * @param r defines the red component to read from
  2025. * @param g defines the green component to read from
  2026. * @param b defines the blue component to read from
  2027. * @param a defines the alpha component to read from
  2028. * @returns the current updated Color4 object
  2029. */
  2030. Color4.prototype.set = function (r, g, b, a) {
  2031. return this.copyFromFloats(r, g, b, a);
  2032. };
  2033. /**
  2034. * Compute the Color4 hexadecimal code as a string
  2035. * @returns a string containing the hexadecimal representation of the Color4 object
  2036. */
  2037. Color4.prototype.toHexString = function () {
  2038. var intR = (this.r * 255) | 0;
  2039. var intG = (this.g * 255) | 0;
  2040. var intB = (this.b * 255) | 0;
  2041. var intA = (this.a * 255) | 0;
  2042. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to linear space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toLinearSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toLinearSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the linear space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Computes a new Color4 converted from the current one to gamma space
  2067. * @returns a new Color4 object
  2068. */
  2069. Color4.prototype.toGammaSpace = function () {
  2070. var convertedColor = new Color4();
  2071. this.toGammaSpaceToRef(convertedColor);
  2072. return convertedColor;
  2073. };
  2074. /**
  2075. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2076. * @param convertedColor defines the Color4 object where to store the gamma space version
  2077. * @returns the unmodified Color4
  2078. */
  2079. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2080. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2081. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2082. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2083. convertedColor.a = this.a;
  2084. return this;
  2085. };
  2086. // Statics
  2087. /**
  2088. * Creates a new Color4 from the string containing valid hexadecimal values
  2089. * @param hex defines a string containing valid hexadecimal values
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.FromHexString = function (hex) {
  2093. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2094. return new Color4(0.0, 0.0, 0.0, 0.0);
  2095. }
  2096. var r = parseInt(hex.substring(1, 3), 16);
  2097. var g = parseInt(hex.substring(3, 5), 16);
  2098. var b = parseInt(hex.substring(5, 7), 16);
  2099. var a = parseInt(hex.substring(7, 9), 16);
  2100. return Color4.FromInts(r, g, b, a);
  2101. };
  2102. /**
  2103. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2104. * @param left defines the start value
  2105. * @param right defines the end value
  2106. * @param amount defines the gradient factor
  2107. * @returns a new Color4 object
  2108. */
  2109. Color4.Lerp = function (left, right, amount) {
  2110. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2111. Color4.LerpToRef(left, right, amount, result);
  2112. return result;
  2113. };
  2114. /**
  2115. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2116. * @param left defines the start value
  2117. * @param right defines the end value
  2118. * @param amount defines the gradient factor
  2119. * @param result defines the Color4 object where to store data
  2120. */
  2121. Color4.LerpToRef = function (left, right, amount, result) {
  2122. result.r = left.r + (right.r - left.r) * amount;
  2123. result.g = left.g + (right.g - left.g) * amount;
  2124. result.b = left.b + (right.b - left.b) * amount;
  2125. result.a = left.a + (right.a - left.a) * amount;
  2126. };
  2127. /**
  2128. * Creates a new Color4 from the starting index element of the passed array
  2129. * @param array defines the source array to read from
  2130. * @param offset defines the offset in the source array
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromArray = function (array, offset) {
  2134. if (offset === void 0) { offset = 0; }
  2135. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2136. };
  2137. /**
  2138. * Creates a new Color3 from integer values (< 256)
  2139. * @param r defines the red component to read from (value between 0 and 255)
  2140. * @param g defines the green component to read from (value between 0 and 255)
  2141. * @param b defines the blue component to read from (value between 0 and 255)
  2142. * @param a defines the alpha component to read from (value between 0 and 255)
  2143. * @returns a new Color3 object
  2144. */
  2145. Color4.FromInts = function (r, g, b, a) {
  2146. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2147. };
  2148. /**
  2149. * Check the content of a given array and convert it to an array containing RGBA data
  2150. * If the original array was already containing count * 4 values then it is returned directly
  2151. * @param colors defines the array to check
  2152. * @param count defines the number of RGBA data to expect
  2153. * @returns an array containing count * 4 values (RGBA)
  2154. */
  2155. Color4.CheckColors4 = function (colors, count) {
  2156. // Check if color3 was used
  2157. if (colors.length === count * 3) {
  2158. var colors4 = [];
  2159. for (var index = 0; index < colors.length; index += 3) {
  2160. var newIndex = (index / 3) * 4;
  2161. colors4[newIndex] = colors[index];
  2162. colors4[newIndex + 1] = colors[index + 1];
  2163. colors4[newIndex + 2] = colors[index + 2];
  2164. colors4[newIndex + 3] = 1.0;
  2165. }
  2166. return colors4;
  2167. }
  2168. return colors;
  2169. };
  2170. return Color4;
  2171. }());
  2172. BABYLON.Color4 = Color4;
  2173. var Vector2 = /** @class */ (function () {
  2174. /**
  2175. * Creates a new Vector2 from the passed x and y coordinates.
  2176. */
  2177. function Vector2(x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. }
  2181. /**
  2182. * Returns a string with the Vector2 coordinates.
  2183. */
  2184. Vector2.prototype.toString = function () {
  2185. return "{X: " + this.x + " Y:" + this.y + "}";
  2186. };
  2187. /**
  2188. * Returns the string "Vector2"
  2189. */
  2190. Vector2.prototype.getClassName = function () {
  2191. return "Vector2";
  2192. };
  2193. /**
  2194. * Returns the Vector2 hash code as a number.
  2195. */
  2196. Vector2.prototype.getHashCode = function () {
  2197. var hash = this.x || 0;
  2198. hash = (hash * 397) ^ (this.y || 0);
  2199. return hash;
  2200. };
  2201. // Operators
  2202. /**
  2203. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2204. * Returns the Vector2.
  2205. */
  2206. Vector2.prototype.toArray = function (array, index) {
  2207. if (index === void 0) { index = 0; }
  2208. array[index] = this.x;
  2209. array[index + 1] = this.y;
  2210. return this;
  2211. };
  2212. /**
  2213. * Returns a new array with 2 elements : the Vector2 coordinates.
  2214. */
  2215. Vector2.prototype.asArray = function () {
  2216. var result = new Array();
  2217. this.toArray(result, 0);
  2218. return result;
  2219. };
  2220. /**
  2221. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2222. * Returns the updated Vector2.
  2223. */
  2224. Vector2.prototype.copyFrom = function (source) {
  2225. this.x = source.x;
  2226. this.y = source.y;
  2227. return this;
  2228. };
  2229. /**
  2230. * Sets the Vector2 coordinates with the passed floats.
  2231. * Returns the updated Vector2.
  2232. */
  2233. Vector2.prototype.copyFromFloats = function (x, y) {
  2234. this.x = x;
  2235. this.y = y;
  2236. return this;
  2237. };
  2238. /**
  2239. * Sets the Vector2 coordinates with the passed floats.
  2240. * Returns the updated Vector2.
  2241. */
  2242. Vector2.prototype.set = function (x, y) {
  2243. return this.copyFromFloats(x, y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2247. */
  2248. Vector2.prototype.add = function (otherVector) {
  2249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.addToRef = function (otherVector, result) {
  2256. result.x = this.x + otherVector.x;
  2257. result.y = this.y + otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.addInPlace = function (otherVector) {
  2265. this.x += otherVector.x;
  2266. this.y += otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2271. */
  2272. Vector2.prototype.addVector3 = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2277. */
  2278. Vector2.prototype.subtract = function (otherVector) {
  2279. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2280. };
  2281. /**
  2282. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2283. * Returns the Vector2.
  2284. */
  2285. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2286. result.x = this.x - otherVector.x;
  2287. result.y = this.y - otherVector.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2292. * Returns the updated Vector2.
  2293. */
  2294. Vector2.prototype.subtractInPlace = function (otherVector) {
  2295. this.x -= otherVector.x;
  2296. this.y -= otherVector.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2304. this.x *= otherVector.x;
  2305. this.y *= otherVector.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2310. */
  2311. Vector2.prototype.multiply = function (otherVector) {
  2312. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2313. };
  2314. /**
  2315. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2319. result.x = this.x * otherVector.x;
  2320. result.y = this.y * otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2325. */
  2326. Vector2.prototype.multiplyByFloats = function (x, y) {
  2327. return new Vector2(this.x * x, this.y * y);
  2328. };
  2329. /**
  2330. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2331. */
  2332. Vector2.prototype.divide = function (otherVector) {
  2333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2337. * Returns the Vector2.
  2338. */
  2339. Vector2.prototype.divideToRef = function (otherVector, result) {
  2340. result.x = this.x / otherVector.x;
  2341. result.y = this.y / otherVector.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Divides the current Vector3 coordinates by the passed ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector2.prototype.divideInPlace = function (otherVector) {
  2349. return this.divideToRef(otherVector, this);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 with current Vector2 negated coordinates.
  2353. */
  2354. Vector2.prototype.negate = function () {
  2355. return new Vector2(-this.x, -this.y);
  2356. };
  2357. /**
  2358. * Multiply the Vector2 coordinates by scale.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.scaleInPlace = function (scale) {
  2362. this.x *= scale;
  2363. this.y *= scale;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2368. */
  2369. Vector2.prototype.scale = function (scale) {
  2370. var result = new Vector2(0, 0);
  2371. this.scaleToRef(scale, result);
  2372. return result;
  2373. };
  2374. /**
  2375. * Scale the current Vector2 values by a factor to a given Vector2
  2376. * @param scale defines the scale factor
  2377. * @param result defines the Vector2 object where to store the result
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.scaleToRef = function (scale, result) {
  2381. result.x = this.x * scale;
  2382. result.y = this.y * scale;
  2383. return this;
  2384. };
  2385. /**
  2386. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2387. * @param scale defines the scale factor
  2388. * @param result defines the Vector2 object where to store the result
  2389. * @returns the unmodified current Vector2
  2390. */
  2391. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2392. result.x += this.x * scale;
  2393. result.y += this.y * scale;
  2394. return this;
  2395. };
  2396. /**
  2397. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2398. */
  2399. Vector2.prototype.equals = function (otherVector) {
  2400. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2401. };
  2402. /**
  2403. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2404. */
  2405. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2406. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2407. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2408. };
  2409. // Properties
  2410. /**
  2411. * Returns the vector length (float).
  2412. */
  2413. Vector2.prototype.length = function () {
  2414. return Math.sqrt(this.x * this.x + this.y * this.y);
  2415. };
  2416. /**
  2417. * Returns the vector squared length (float);
  2418. */
  2419. Vector2.prototype.lengthSquared = function () {
  2420. return (this.x * this.x + this.y * this.y);
  2421. };
  2422. // Methods
  2423. /**
  2424. * Normalize the vector.
  2425. * Returns the updated Vector2.
  2426. */
  2427. Vector2.prototype.normalize = function () {
  2428. var len = this.length();
  2429. if (len === 0)
  2430. return this;
  2431. var num = 1.0 / len;
  2432. this.x *= num;
  2433. this.y *= num;
  2434. return this;
  2435. };
  2436. /**
  2437. * Returns a new Vector2 copied from the Vector2.
  2438. */
  2439. Vector2.prototype.clone = function () {
  2440. return new Vector2(this.x, this.y);
  2441. };
  2442. // Statics
  2443. /**
  2444. * Returns a new Vector2(0, 0)
  2445. */
  2446. Vector2.Zero = function () {
  2447. return new Vector2(0, 0);
  2448. };
  2449. /**
  2450. * Returns a new Vector2(1, 1)
  2451. */
  2452. Vector2.One = function () {
  2453. return new Vector2(1, 1);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set from the passed index element of the passed array.
  2457. */
  2458. Vector2.FromArray = function (array, offset) {
  2459. if (offset === void 0) { offset = 0; }
  2460. return new Vector2(array[offset], array[offset + 1]);
  2461. };
  2462. /**
  2463. * Sets "result" from the passed index element of the passed array.
  2464. */
  2465. Vector2.FromArrayToRef = function (array, offset, result) {
  2466. result.x = array[offset];
  2467. result.y = array[offset + 1];
  2468. };
  2469. /**
  2470. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2471. */
  2472. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2473. var squared = amount * amount;
  2474. var cubed = amount * squared;
  2475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * 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".
  2485. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2486. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2487. */
  2488. Vector2.Clamp = function (value, min, max) {
  2489. var x = value.x;
  2490. x = (x > max.x) ? max.x : x;
  2491. x = (x < min.x) ? min.x : x;
  2492. var y = value.y;
  2493. y = (y > max.y) ? max.y : y;
  2494. y = (y < min.y) ? min.y : y;
  2495. return new Vector2(x, y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2499. */
  2500. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2501. var squared = amount * amount;
  2502. var cubed = amount * squared;
  2503. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2504. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2505. var part3 = (cubed - (2.0 * squared)) + amount;
  2506. var part4 = cubed - squared;
  2507. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2508. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2509. return new Vector2(x, y);
  2510. };
  2511. /**
  2512. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2513. */
  2514. Vector2.Lerp = function (start, end, amount) {
  2515. var x = start.x + ((end.x - start.x) * amount);
  2516. var y = start.y + ((end.y - start.y) * amount);
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns the dot product (float) of the vector "left" and the vector "right".
  2521. */
  2522. Vector2.Dot = function (left, right) {
  2523. return left.x * right.x + left.y * right.y;
  2524. };
  2525. /**
  2526. * Returns a new Vector2 equal to the normalized passed vector.
  2527. */
  2528. Vector2.Normalize = function (vector) {
  2529. var newVector = vector.clone();
  2530. newVector.normalize();
  2531. return newVector;
  2532. };
  2533. /**
  2534. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2535. */
  2536. Vector2.Minimize = function (left, right) {
  2537. var x = (left.x < right.x) ? left.x : right.x;
  2538. var y = (left.y < right.y) ? left.y : right.y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2543. */
  2544. Vector2.Maximize = function (left, right) {
  2545. var x = (left.x > right.x) ? left.x : right.x;
  2546. var y = (left.y > right.y) ? left.y : right.y;
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2551. */
  2552. Vector2.Transform = function (vector, transformation) {
  2553. var r = Vector2.Zero();
  2554. Vector2.TransformToRef(vector, transformation, r);
  2555. return r;
  2556. };
  2557. /**
  2558. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2559. */
  2560. Vector2.TransformToRef = function (vector, transformation, result) {
  2561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2563. result.x = x;
  2564. result.y = y;
  2565. };
  2566. /**
  2567. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2568. */
  2569. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2570. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2571. var sign = a < 0 ? -1 : 1;
  2572. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2573. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2574. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2575. };
  2576. /**
  2577. * Returns the distance (float) between the vectors "value1" and "value2".
  2578. */
  2579. Vector2.Distance = function (value1, value2) {
  2580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2581. };
  2582. /**
  2583. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2584. */
  2585. Vector2.DistanceSquared = function (value1, value2) {
  2586. var x = value1.x - value2.x;
  2587. var y = value1.y - value2.y;
  2588. return (x * x) + (y * y);
  2589. };
  2590. /**
  2591. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2592. */
  2593. Vector2.Center = function (value1, value2) {
  2594. var center = value1.add(value2);
  2595. center.scaleInPlace(0.5);
  2596. return center;
  2597. };
  2598. /**
  2599. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2600. */
  2601. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2602. var l2 = Vector2.DistanceSquared(segA, segB);
  2603. if (l2 === 0.0) {
  2604. return Vector2.Distance(p, segA);
  2605. }
  2606. var v = segB.subtract(segA);
  2607. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2608. var proj = segA.add(v.multiplyByFloats(t, t));
  2609. return Vector2.Distance(p, proj);
  2610. };
  2611. return Vector2;
  2612. }());
  2613. BABYLON.Vector2 = Vector2;
  2614. /**
  2615. * Classed used to store (x,y,z) vector representation
  2616. * A Vector3 is the main object used in 3D geometry
  2617. * It can represent etiher the coordinates of a point the space, either a direction
  2618. * Reminder: Babylon.js uses a left handed forward facing system
  2619. */
  2620. var Vector3 = /** @class */ (function () {
  2621. /**
  2622. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2623. * @param x defines the first coordinates (on X axis)
  2624. * @param y defines the second coordinates (on Y axis)
  2625. * @param z defines the third coordinates (on Z axis)
  2626. */
  2627. function Vector3(
  2628. /**
  2629. * Defines the first coordinates (on X axis)
  2630. */
  2631. x,
  2632. /**
  2633. * Defines the second coordinates (on Y axis)
  2634. */
  2635. y,
  2636. /**
  2637. * Defines the third coordinates (on Z axis)
  2638. */
  2639. z) {
  2640. this.x = x;
  2641. this.y = y;
  2642. this.z = z;
  2643. }
  2644. /**
  2645. * Creates a string representation of the Vector3
  2646. * @returns a string with the Vector3 coordinates.
  2647. */
  2648. Vector3.prototype.toString = function () {
  2649. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2650. };
  2651. /**
  2652. * Gets the class name
  2653. * @returns the string "Vector3"
  2654. */
  2655. Vector3.prototype.getClassName = function () {
  2656. return "Vector3";
  2657. };
  2658. /**
  2659. * Creates the Vector3 hash code
  2660. * @returns a number which tends to be unique between Vector3 instances
  2661. */
  2662. Vector3.prototype.getHashCode = function () {
  2663. var hash = this.x || 0;
  2664. hash = (hash * 397) ^ (this.y || 0);
  2665. hash = (hash * 397) ^ (this.z || 0);
  2666. return hash;
  2667. };
  2668. // Operators
  2669. /**
  2670. * Creates an array containing three elements : the coordinates of the Vector3
  2671. * @returns a new array of numbers
  2672. */
  2673. Vector3.prototype.asArray = function () {
  2674. var result = [];
  2675. this.toArray(result, 0);
  2676. return result;
  2677. };
  2678. /**
  2679. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2680. * @param array defines the destination array
  2681. * @param index defines the offset in the destination array
  2682. * @returns the current Vector3
  2683. */
  2684. Vector3.prototype.toArray = function (array, index) {
  2685. if (index === void 0) { index = 0; }
  2686. array[index] = this.x;
  2687. array[index + 1] = this.y;
  2688. array[index + 2] = this.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2693. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2694. */
  2695. Vector3.prototype.toQuaternion = function () {
  2696. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2697. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2698. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2699. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2700. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2701. var cosy = Math.cos(this.y * 0.5);
  2702. var siny = Math.sin(this.y * 0.5);
  2703. result.x = coszMinusx * siny;
  2704. result.y = -sinzMinusx * siny;
  2705. result.z = sinxPlusz * cosy;
  2706. result.w = cosxPlusz * cosy;
  2707. return result;
  2708. };
  2709. /**
  2710. * Adds the passed vector to the current Vector3
  2711. * @param otherVector defines the second operand
  2712. * @returns the current updated Vector3
  2713. */
  2714. Vector3.prototype.addInPlace = function (otherVector) {
  2715. this.x += otherVector.x;
  2716. this.y += otherVector.y;
  2717. this.z += otherVector.z;
  2718. return this;
  2719. };
  2720. /**
  2721. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2722. * @param otherVector defines the second operand
  2723. * @returns the resulting Vector3
  2724. */
  2725. Vector3.prototype.add = function (otherVector) {
  2726. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2727. };
  2728. /**
  2729. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2730. * @param otherVector defines the second operand
  2731. * @param result defines the Vector3 object where to store the result
  2732. * @returns the current Vector3
  2733. */
  2734. Vector3.prototype.addToRef = function (otherVector, result) {
  2735. result.x = this.x + otherVector.x;
  2736. result.y = this.y + otherVector.y;
  2737. result.z = this.z + otherVector.z;
  2738. return this;
  2739. };
  2740. /**
  2741. * Subtract the passed vector from the current Vector3
  2742. * @param otherVector defines the second operand
  2743. * @returns the current updated Vector3
  2744. */
  2745. Vector3.prototype.subtractInPlace = function (otherVector) {
  2746. this.x -= otherVector.x;
  2747. this.y -= otherVector.y;
  2748. this.z -= otherVector.z;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2753. * @param otherVector defines the second operand
  2754. * @returns the resulting Vector3
  2755. */
  2756. Vector3.prototype.subtract = function (otherVector) {
  2757. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2758. };
  2759. /**
  2760. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2761. * @param otherVector defines the second operand
  2762. * @param result defines the Vector3 object where to store the result
  2763. * @returns the current Vector3
  2764. */
  2765. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2766. result.x = this.x - otherVector.x;
  2767. result.y = this.y - otherVector.y;
  2768. result.z = this.z - otherVector.z;
  2769. return this;
  2770. };
  2771. /**
  2772. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2779. return new Vector3(this.x - x, this.y - y, this.z - z);
  2780. };
  2781. /**
  2782. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2790. result.x = this.x - x;
  2791. result.y = this.y - y;
  2792. result.z = this.z - z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2797. * @returns a new Vector3
  2798. */
  2799. Vector3.prototype.negate = function () {
  2800. return new Vector3(-this.x, -this.y, -this.z);
  2801. };
  2802. /**
  2803. * Multiplies the Vector3 coordinates by the float "scale"
  2804. * @param scale defines the multiplier factor
  2805. * @returns the current updated Vector3
  2806. */
  2807. Vector3.prototype.scaleInPlace = function (scale) {
  2808. this.x *= scale;
  2809. this.y *= scale;
  2810. this.z *= scale;
  2811. return this;
  2812. };
  2813. /**
  2814. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2815. * @param scale defines the multiplier factor
  2816. * @returns a new Vector3
  2817. */
  2818. Vector3.prototype.scale = function (scale) {
  2819. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2820. };
  2821. /**
  2822. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2823. * @param scale defines the multiplier factor
  2824. * @param result defines the Vector3 object where to store the result
  2825. * @returns the current Vector3
  2826. */
  2827. Vector3.prototype.scaleToRef = function (scale, result) {
  2828. result.x = this.x * scale;
  2829. result.y = this.y * scale;
  2830. result.z = this.z * scale;
  2831. return this;
  2832. };
  2833. /**
  2834. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2835. * @param scale defines the scale factor
  2836. * @param result defines the Vector3 object where to store the result
  2837. * @returns the unmodified current Vector3
  2838. */
  2839. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2840. result.x += this.x * scale;
  2841. result.y += this.y * scale;
  2842. result.z += this.z * scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2847. * @param otherVector defines the second operand
  2848. * @returns true if both vectors are equals
  2849. */
  2850. Vector3.prototype.equals = function (otherVector) {
  2851. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2852. };
  2853. /**
  2854. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2855. * @param otherVector defines the second operand
  2856. * @param epsilon defines the minimal distance to define values as equals
  2857. * @returns true if both vectors are distant less than epsilon
  2858. */
  2859. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2861. 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);
  2862. };
  2863. /**
  2864. * Returns true if the current Vector3 coordinates equals the passed floats
  2865. * @param x defines the x coordinate of the operand
  2866. * @param y defines the y coordinate of the operand
  2867. * @param z defines the z coordinate of the operand
  2868. * @returns true if both vectors are equals
  2869. */
  2870. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2871. return this.x === x && this.y === y && this.z === z;
  2872. };
  2873. /**
  2874. * Multiplies the current Vector3 coordinates by the passed ones
  2875. * @param otherVector defines the second operand
  2876. * @returns the current updated Vector3
  2877. */
  2878. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. return this;
  2883. };
  2884. /**
  2885. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2886. * @param otherVector defines the second operand
  2887. * @returns the new Vector3
  2888. */
  2889. Vector3.prototype.multiply = function (otherVector) {
  2890. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2891. };
  2892. /**
  2893. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2894. * @param otherVector defines the second operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2899. result.x = this.x * otherVector.x;
  2900. result.y = this.y * otherVector.y;
  2901. result.z = this.z * otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2906. * @param x defines the x coordinate of the operand
  2907. * @param y defines the y coordinate of the operand
  2908. * @param z defines the z coordinate of the operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2912. return new Vector3(this.x * x, this.y * y, this.z * z);
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2916. * @param otherVector defines the second operand
  2917. * @returns the new Vector3
  2918. */
  2919. Vector3.prototype.divide = function (otherVector) {
  2920. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2921. };
  2922. /**
  2923. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2924. * @param otherVector defines the second operand
  2925. * @param result defines the Vector3 object where to store the result
  2926. * @returns the current Vector3
  2927. */
  2928. Vector3.prototype.divideToRef = function (otherVector, result) {
  2929. result.x = this.x / otherVector.x;
  2930. result.y = this.y / otherVector.y;
  2931. result.z = this.z / otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.divideInPlace = function (otherVector) {
  2940. return this.divideToRef(otherVector, this);
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.minimizeInPlace = function (other) {
  2948. if (other.x < this.x)
  2949. this.x = other.x;
  2950. if (other.y < this.y)
  2951. this.y = other.y;
  2952. if (other.z < this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2958. * @param other defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.maximizeInPlace = function (other) {
  2962. if (other.x > this.x)
  2963. this.x = other.x;
  2964. if (other.y > this.y)
  2965. this.y = other.y;
  2966. if (other.z > this.z)
  2967. this.z = other.z;
  2968. return this;
  2969. };
  2970. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2971. /**
  2972. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2973. */
  2974. get: function () {
  2975. var absX = Math.abs(this.x);
  2976. var absY = Math.abs(this.y);
  2977. if (absX !== absY) {
  2978. return true;
  2979. }
  2980. var absZ = Math.abs(this.z);
  2981. if (absX !== absZ) {
  2982. return true;
  2983. }
  2984. if (absY !== absZ) {
  2985. return true;
  2986. }
  2987. return false;
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. // Properties
  2993. /**
  2994. * Gets the length of the Vector3
  2995. * @returns the length of the Vecto3
  2996. */
  2997. Vector3.prototype.length = function () {
  2998. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2999. };
  3000. /**
  3001. * Gets the squared length of the Vector3
  3002. * @returns squared length of the Vector3
  3003. */
  3004. Vector3.prototype.lengthSquared = function () {
  3005. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3006. };
  3007. /**
  3008. * Normalize the current Vector3.
  3009. * Please note that this is an in place operation.
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.normalize = function () {
  3013. var len = this.length();
  3014. if (len === 0 || len === 1.0)
  3015. return this;
  3016. var num = 1.0 / len;
  3017. this.x *= num;
  3018. this.y *= num;
  3019. this.z *= num;
  3020. return this;
  3021. };
  3022. /**
  3023. * Normalize the current Vector3 to a new vector
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.normalizeToNew = function () {
  3027. var normalized = new Vector3(0, 0, 0);
  3028. this.normalizeToRef(normalized);
  3029. return normalized;
  3030. };
  3031. /**
  3032. * Normalize the current Vector3 to the reference
  3033. * @param reference define the Vector3 to update
  3034. * @returns the updated Vector3
  3035. */
  3036. Vector3.prototype.normalizeToRef = function (reference) {
  3037. var len = this.length();
  3038. if (len === 0 || len === 1.0) {
  3039. reference.set(this.x, this.y, this.z);
  3040. return reference;
  3041. }
  3042. var scale = 1.0 / len;
  3043. this.scaleToRef(scale, reference);
  3044. return reference;
  3045. };
  3046. /**
  3047. * Creates a new Vector3 copied from the current Vector3
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.clone = function () {
  3051. return new Vector3(this.x, this.y, this.z);
  3052. };
  3053. /**
  3054. * Copies the passed vector coordinates to the current Vector3 ones
  3055. * @param source defines the source Vector3
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.copyFrom = function (source) {
  3059. this.x = source.x;
  3060. this.y = source.y;
  3061. this.z = source.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Copies the passed floats to the current Vector3 coordinates
  3066. * @param x defines the x coordinate of the operand
  3067. * @param y defines the y coordinate of the operand
  3068. * @param z defines the z coordinate of the operand
  3069. * @returns the current updated Vector3
  3070. */
  3071. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3072. this.x = x;
  3073. this.y = y;
  3074. this.z = z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Copies the passed floats to the current Vector3 coordinates
  3079. * @param x defines the x coordinate of the operand
  3080. * @param y defines the y coordinate of the operand
  3081. * @param z defines the z coordinate of the operand
  3082. * @returns the current updated Vector3
  3083. */
  3084. Vector3.prototype.set = function (x, y, z) {
  3085. return this.copyFromFloats(x, y, z);
  3086. };
  3087. // Statics
  3088. /**
  3089. * Get the clip factor between two vectors
  3090. * @param vector0 defines the first operand
  3091. * @param vector1 defines the second operand
  3092. * @param axis defines the axis to use
  3093. * @param size defines the size along the axis
  3094. * @returns the clip factor
  3095. */
  3096. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3097. var d0 = Vector3.Dot(vector0, axis) - size;
  3098. var d1 = Vector3.Dot(vector1, axis) - size;
  3099. var s = d0 / (d0 - d1);
  3100. return s;
  3101. };
  3102. /**
  3103. * Get angle between two vectors
  3104. * @param vector0 angle between vector0 and vector1
  3105. * @param vector1 angle between vector0 and vector1
  3106. * @param normal direction of the normal
  3107. * @return the angle between vector0 and vector1
  3108. */
  3109. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3110. var v0 = vector0.clone().normalize();
  3111. var v1 = vector1.clone().normalize();
  3112. var dot = Vector3.Dot(v0, v1);
  3113. var n = Vector3.Cross(v0, v1);
  3114. if (Vector3.Dot(n, normal) > 0) {
  3115. return Math.acos(dot);
  3116. }
  3117. return -Math.acos(dot);
  3118. };
  3119. /**
  3120. * Returns a new Vector3 set from the index "offset" of the passed array
  3121. * @param array defines the source array
  3122. * @param offset defines the offset in the source array
  3123. * @returns the new Vector3
  3124. */
  3125. Vector3.FromArray = function (array, offset) {
  3126. if (!offset) {
  3127. offset = 0;
  3128. }
  3129. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3133. * This function is deprecated. Use FromArray instead
  3134. * @param array defines the source array
  3135. * @param offset defines the offset in the source array
  3136. * @returns the new Vector3
  3137. */
  3138. Vector3.FromFloatArray = function (array, offset) {
  3139. return Vector3.FromArray(array, offset);
  3140. };
  3141. /**
  3142. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @param result defines the Vector3 where to store the result
  3146. */
  3147. Vector3.FromArrayToRef = function (array, offset, result) {
  3148. result.x = array[offset];
  3149. result.y = array[offset + 1];
  3150. result.z = array[offset + 2];
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3154. * This function is deprecated. Use FromArrayToRef instead.
  3155. * @param array defines the source array
  3156. * @param offset defines the offset in the source array
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3160. return Vector3.FromArrayToRef(array, offset, result);
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" with the passed floats.
  3164. * @param x defines the x coordinate of the source
  3165. * @param y defines the y coordinate of the source
  3166. * @param z defines the z coordinate of the source
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3170. result.x = x;
  3171. result.y = y;
  3172. result.z = z;
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3176. * @returns a new empty Vector3
  3177. */
  3178. Vector3.Zero = function () {
  3179. return new Vector3(0.0, 0.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3183. * @returns a new unit Vector3
  3184. */
  3185. Vector3.One = function () {
  3186. return new Vector3(1.0, 1.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3190. * @returns a new up Vector3
  3191. */
  3192. Vector3.Up = function () {
  3193. return new Vector3(0.0, 1.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3197. * @returns a new forward Vector3
  3198. */
  3199. Vector3.Forward = function () {
  3200. return new Vector3(0.0, 0.0, 1.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3204. * @returns a new right Vector3
  3205. */
  3206. Vector3.Right = function () {
  3207. return new Vector3(1.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3211. * @returns a new left Vector3
  3212. */
  3213. Vector3.Left = function () {
  3214. return new Vector3(-1.0, 0.0, 0.0);
  3215. };
  3216. /**
  3217. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3218. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3219. * @param vector defines the Vector3 to transform
  3220. * @param transformation defines the transformation matrix
  3221. * @returns the transformed Vector3
  3222. */
  3223. Vector3.TransformCoordinates = function (vector, transformation) {
  3224. var result = Vector3.Zero();
  3225. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3230. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3231. * @param vector defines the Vector3 to transform
  3232. * @param transformation defines the transformation matrix
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3239. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3240. result.x = x / w;
  3241. result.y = y / w;
  3242. result.z = z / w;
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3246. * This method computes tranformed coordinates only, not transformed direction vectors
  3247. * @param x define the x coordinate of the source vector
  3248. * @param y define the y coordinate of the source vector
  3249. * @param z define the z coordinate of the source vector
  3250. * @param transformation defines the transformation matrix
  3251. * @param result defines the Vector3 where to store the result
  3252. */
  3253. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3254. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3255. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3256. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3257. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3258. result.x = rx / rw;
  3259. result.y = ry / rw;
  3260. result.z = rz / rw;
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3264. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3265. * @param vector defines the Vector3 to transform
  3266. * @param transformation defines the transformation matrix
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.TransformNormal = function (vector, transformation) {
  3270. var result = Vector3.Zero();
  3271. Vector3.TransformNormalToRef(vector, transformation, result);
  3272. return result;
  3273. };
  3274. /**
  3275. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3276. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3277. * @param vector defines the Vector3 to transform
  3278. * @param transformation defines the transformation matrix
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param x define the x coordinate of the source vector
  3293. * @param y define the y coordinate of the source vector
  3294. * @param z define the z coordinate of the source vector
  3295. * @param transformation defines the transformation matrix
  3296. * @param result defines the Vector3 where to store the result
  3297. */
  3298. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3299. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3300. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3301. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3305. * @param value1 defines the first control point
  3306. * @param value2 defines the second control point
  3307. * @param value3 defines the third control point
  3308. * @param value4 defines the fourth control point
  3309. * @param amount defines the amount on the spline to use
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3313. var squared = amount * amount;
  3314. var cubed = amount * squared;
  3315. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3316. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3317. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3318. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3319. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3320. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3321. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3322. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3323. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3324. return new Vector3(x, y, z);
  3325. };
  3326. /**
  3327. * 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"
  3328. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3329. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3330. * @param value defines the current value
  3331. * @param min defines the lower range value
  3332. * @param max defines the upper range value
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.Clamp = function (value, min, max) {
  3336. var x = value.x;
  3337. x = (x > max.x) ? max.x : x;
  3338. x = (x < min.x) ? min.x : x;
  3339. var y = value.y;
  3340. y = (y > max.y) ? max.y : y;
  3341. y = (y < min.y) ? min.y : y;
  3342. var z = value.z;
  3343. z = (z > max.z) ? max.z : z;
  3344. z = (z < min.z) ? min.z : z;
  3345. return new Vector3(x, y, z);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3349. * @param value1 defines the first control point
  3350. * @param tangent1 defines the first tangent vector
  3351. * @param value2 defines the second control point
  3352. * @param tangent2 defines the second tangent vector
  3353. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3361. var part3 = (cubed - (2.0 * squared)) + amount;
  3362. var part4 = cubed - squared;
  3363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3365. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3366. return new Vector3(x, y, z);
  3367. };
  3368. /**
  3369. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3370. * @param start defines the start value
  3371. * @param end defines the end value
  3372. * @param amount max defines amount between both (between 0 and 1)
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Lerp = function (start, end, amount) {
  3376. var result = new Vector3(0, 0, 0);
  3377. Vector3.LerpToRef(start, end, amount, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3382. * @param start defines the start value
  3383. * @param end defines the end value
  3384. * @param amount max defines amount between both (between 0 and 1)
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.LerpToRef = function (start, end, amount, result) {
  3388. result.x = start.x + ((end.x - start.x) * amount);
  3389. result.y = start.y + ((end.y - start.y) * amount);
  3390. result.z = start.z + ((end.z - start.z) * amount);
  3391. };
  3392. /**
  3393. * Returns the dot product (float) between the vectors "left" and "right"
  3394. * @param left defines the left operand
  3395. * @param right defines the right operand
  3396. * @returns the dot product
  3397. */
  3398. Vector3.Dot = function (left, right) {
  3399. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3403. * The cross product is then orthogonal to both "left" and "right"
  3404. * @param left defines the left operand
  3405. * @param right defines the right operand
  3406. * @returns the cross product
  3407. */
  3408. Vector3.Cross = function (left, right) {
  3409. var result = Vector3.Zero();
  3410. Vector3.CrossToRef(left, right, result);
  3411. return result;
  3412. };
  3413. /**
  3414. * Sets the passed vector "result" with the cross product of "left" and "right"
  3415. * The cross product is then orthogonal to both "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.CrossToRef = function (left, right, result) {
  3421. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3422. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3423. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3424. result.copyFrom(MathTmp.Vector3[0]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 as the normalization of the passed vector
  3428. * @param vector defines the Vector3 to normalize
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Normalize = function (vector) {
  3432. var result = Vector3.Zero();
  3433. Vector3.NormalizeToRef(vector, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the normalization of the passed first vector
  3438. * @param vector defines the Vector3 to normalize
  3439. * @param result defines the Vector3 where to store the result
  3440. */
  3441. Vector3.NormalizeToRef = function (vector, result) {
  3442. result.copyFrom(vector);
  3443. result.normalize();
  3444. };
  3445. /**
  3446. * Project a Vector3 onto screen space
  3447. * @param vector defines the Vector3 to project
  3448. * @param world defines the world matrix to use
  3449. * @param transform defines the transform (view x projection) matrix to use
  3450. * @param viewport defines the screen viewport to use
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Project = function (vector, world, transform, viewport) {
  3454. var cw = viewport.width;
  3455. var ch = viewport.height;
  3456. var cx = viewport.x;
  3457. var cy = viewport.y;
  3458. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3459. 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);
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(transform, matrix);
  3462. matrix.multiplyToRef(viewportMatrix, matrix);
  3463. return Vector3.TransformCoordinates(vector, matrix);
  3464. };
  3465. /**
  3466. * Unproject from screen space to object space
  3467. * @param source defines the screen space Vector3 to use
  3468. * @param viewportWidth defines the current width of the viewport
  3469. * @param viewportHeight defines the current height of the viewport
  3470. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3475. var matrix = MathTmp.Matrix[0];
  3476. world.multiplyToRef(transform, matrix);
  3477. matrix.invert();
  3478. source.x = source.x / viewportWidth * 2 - 1;
  3479. source.y = -(source.y / viewportHeight * 2 - 1);
  3480. var vector = Vector3.TransformCoordinates(source, matrix);
  3481. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3482. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3483. vector = vector.scale(1.0 / num);
  3484. }
  3485. return vector;
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param view defines the view matrix to use
  3494. * @param projection defines the projection matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3498. var result = Vector3.Zero();
  3499. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Unproject from screen space to object space
  3504. * @param source defines the screen space Vector3 to use
  3505. * @param viewportWidth defines the current width of the viewport
  3506. * @param viewportHeight defines the current height of the viewport
  3507. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3508. * @param view defines the view matrix to use
  3509. * @param projection defines the projection matrix to use
  3510. * @param result defines the Vector3 where to store the result
  3511. */
  3512. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3513. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3514. };
  3515. /**
  3516. * Unproject from screen space to object space
  3517. * @param sourceX defines the screen space x coordinate to use
  3518. * @param sourceY defines the screen space y coordinate to use
  3519. * @param sourceZ defines the screen space z coordinate to use
  3520. * @param viewportWidth defines the current width of the viewport
  3521. * @param viewportHeight defines the current height of the viewport
  3522. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3523. * @param view defines the view matrix to use
  3524. * @param projection defines the projection matrix to use
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3528. var matrix = MathTmp.Matrix[0];
  3529. world.multiplyToRef(view, matrix);
  3530. matrix.multiplyToRef(projection, matrix);
  3531. matrix.invert();
  3532. var screenSource = MathTmp.Vector3[0];
  3533. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3534. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3535. screenSource.z = 2 * sourceZ - 1.0;
  3536. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3537. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3538. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3539. result.scaleInPlace(1.0 / num);
  3540. }
  3541. };
  3542. /**
  3543. * Gets the minimal coordinate values between two Vector3
  3544. * @param left defines the first operand
  3545. * @param right defines the second operand
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Minimize = function (left, right) {
  3549. var min = left.clone();
  3550. min.minimizeInPlace(right);
  3551. return min;
  3552. };
  3553. /**
  3554. * Gets the maximal coordinate values between two Vector3
  3555. * @param left defines the first operand
  3556. * @param right defines the second operand
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Maximize = function (left, right) {
  3560. var max = left.clone();
  3561. max.maximizeInPlace(right);
  3562. return max;
  3563. };
  3564. /**
  3565. * Returns the distance between the vectors "value1" and "value2"
  3566. * @param value1 defines the first operand
  3567. * @param value2 defines the second operand
  3568. * @returns the distance
  3569. */
  3570. Vector3.Distance = function (value1, value2) {
  3571. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3572. };
  3573. /**
  3574. * Returns the squared distance between the vectors "value1" and "value2"
  3575. * @param value1 defines the first operand
  3576. * @param value2 defines the second operand
  3577. * @returns the squared distance
  3578. */
  3579. Vector3.DistanceSquared = function (value1, value2) {
  3580. var x = value1.x - value2.x;
  3581. var y = value1.y - value2.y;
  3582. var z = value1.z - value2.z;
  3583. return (x * x) + (y * y) + (z * z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located at the center between "value1" and "value2"
  3587. * @param value1 defines the first operand
  3588. * @param value2 defines the second operand
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Center = function (value1, value2) {
  3592. var center = value1.add(value2);
  3593. center.scaleInPlace(0.5);
  3594. return center;
  3595. };
  3596. /**
  3597. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3598. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3599. * to something in order to rotate it from its local system to the given target system
  3600. * Note: axis1, axis2 and axis3 are normalized during this operation
  3601. * @param axis1 defines the first axis
  3602. * @param axis2 defines the second axis
  3603. * @param axis3 defines the third axis
  3604. * @returns a new Vector3
  3605. */
  3606. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3607. var rotation = Vector3.Zero();
  3608. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3609. return rotation;
  3610. };
  3611. /**
  3612. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3613. * @param axis1 defines the first axis
  3614. * @param axis2 defines the second axis
  3615. * @param axis3 defines the third axis
  3616. * @param ref defines the Vector3 where to store the result
  3617. */
  3618. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3619. var quat = MathTmp.Quaternion[0];
  3620. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3621. quat.toEulerAnglesToRef(ref);
  3622. };
  3623. return Vector3;
  3624. }());
  3625. BABYLON.Vector3 = Vector3;
  3626. //Vector4 class created for EulerAngle class conversion to Quaternion
  3627. var Vector4 = /** @class */ (function () {
  3628. /**
  3629. * Creates a Vector4 object from the passed floats.
  3630. */
  3631. function Vector4(x, y, z, w) {
  3632. this.x = x;
  3633. this.y = y;
  3634. this.z = z;
  3635. this.w = w;
  3636. }
  3637. /**
  3638. * Returns the string with the Vector4 coordinates.
  3639. */
  3640. Vector4.prototype.toString = function () {
  3641. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3642. };
  3643. /**
  3644. * Returns the string "Vector4".
  3645. */
  3646. Vector4.prototype.getClassName = function () {
  3647. return "Vector4";
  3648. };
  3649. /**
  3650. * Returns the Vector4 hash code.
  3651. */
  3652. Vector4.prototype.getHashCode = function () {
  3653. var hash = this.x || 0;
  3654. hash = (hash * 397) ^ (this.y || 0);
  3655. hash = (hash * 397) ^ (this.z || 0);
  3656. hash = (hash * 397) ^ (this.w || 0);
  3657. return hash;
  3658. };
  3659. // Operators
  3660. /**
  3661. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.asArray = function () {
  3664. var result = new Array();
  3665. this.toArray(result, 0);
  3666. return result;
  3667. };
  3668. /**
  3669. * Populates the passed array from the passed index with the Vector4 coordinates.
  3670. * Returns the Vector4.
  3671. */
  3672. Vector4.prototype.toArray = function (array, index) {
  3673. if (index === undefined) {
  3674. index = 0;
  3675. }
  3676. array[index] = this.x;
  3677. array[index + 1] = this.y;
  3678. array[index + 2] = this.z;
  3679. array[index + 3] = this.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Adds the passed vector to the current Vector4.
  3684. * Returns the updated Vector4.
  3685. */
  3686. Vector4.prototype.addInPlace = function (otherVector) {
  3687. this.x += otherVector.x;
  3688. this.y += otherVector.y;
  3689. this.z += otherVector.z;
  3690. this.w += otherVector.w;
  3691. return this;
  3692. };
  3693. /**
  3694. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3695. */
  3696. Vector4.prototype.add = function (otherVector) {
  3697. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3698. };
  3699. /**
  3700. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3701. * Returns the current Vector4.
  3702. */
  3703. Vector4.prototype.addToRef = function (otherVector, result) {
  3704. result.x = this.x + otherVector.x;
  3705. result.y = this.y + otherVector.y;
  3706. result.z = this.z + otherVector.z;
  3707. result.w = this.w + otherVector.w;
  3708. return this;
  3709. };
  3710. /**
  3711. * Subtract in place the passed vector from the current Vector4.
  3712. * Returns the updated Vector4.
  3713. */
  3714. Vector4.prototype.subtractInPlace = function (otherVector) {
  3715. this.x -= otherVector.x;
  3716. this.y -= otherVector.y;
  3717. this.z -= otherVector.z;
  3718. this.w -= otherVector.w;
  3719. return this;
  3720. };
  3721. /**
  3722. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3723. */
  3724. Vector4.prototype.subtract = function (otherVector) {
  3725. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3726. };
  3727. /**
  3728. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3729. * Returns the current Vector4.
  3730. */
  3731. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3732. result.x = this.x - otherVector.x;
  3733. result.y = this.y - otherVector.y;
  3734. result.z = this.z - otherVector.z;
  3735. result.w = this.w - otherVector.w;
  3736. return this;
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3742. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3743. };
  3744. /**
  3745. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3749. result.x = this.x - x;
  3750. result.y = this.y - y;
  3751. result.z = this.z - z;
  3752. result.w = this.w - w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3757. */
  3758. Vector4.prototype.negate = function () {
  3759. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3760. };
  3761. /**
  3762. * Multiplies the current Vector4 coordinates by scale (float).
  3763. * Returns the updated Vector4.
  3764. */
  3765. Vector4.prototype.scaleInPlace = function (scale) {
  3766. this.x *= scale;
  3767. this.y *= scale;
  3768. this.z *= scale;
  3769. this.w *= scale;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3774. */
  3775. Vector4.prototype.scale = function (scale) {
  3776. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3777. };
  3778. /**
  3779. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3780. * Returns the current Vector4.
  3781. */
  3782. Vector4.prototype.scaleToRef = function (scale, result) {
  3783. result.x = this.x * scale;
  3784. result.y = this.y * scale;
  3785. result.z = this.z * scale;
  3786. result.w = this.w * scale;
  3787. return this;
  3788. };
  3789. /**
  3790. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3791. * @param scale defines the scale factor
  3792. * @param result defines the Vector4 object where to store the result
  3793. * @returns the unmodified current Vector4
  3794. */
  3795. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3796. result.x += this.x * scale;
  3797. result.y += this.y * scale;
  3798. result.z += this.z * scale;
  3799. result.w += this.w * scale;
  3800. return this;
  3801. };
  3802. /**
  3803. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3804. */
  3805. Vector4.prototype.equals = function (otherVector) {
  3806. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3807. };
  3808. /**
  3809. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3810. */
  3811. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3812. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3813. return otherVector
  3814. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3815. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3816. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3817. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3818. };
  3819. /**
  3820. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3821. */
  3822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3823. return this.x === x && this.y === y && this.z === z && this.w === w;
  3824. };
  3825. /**
  3826. * Multiplies in place the current Vector4 by the passed one.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3830. this.x *= otherVector.x;
  3831. this.y *= otherVector.y;
  3832. this.z *= otherVector.z;
  3833. this.w *= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3838. */
  3839. Vector4.prototype.multiply = function (otherVector) {
  3840. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3841. };
  3842. /**
  3843. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3847. result.x = this.x * otherVector.x;
  3848. result.y = this.y * otherVector.y;
  3849. result.z = this.z * otherVector.z;
  3850. result.w = this.w * otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3861. */
  3862. Vector4.prototype.divide = function (otherVector) {
  3863. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3864. };
  3865. /**
  3866. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.divideToRef = function (otherVector, result) {
  3870. result.x = this.x / otherVector.x;
  3871. result.y = this.y / otherVector.y;
  3872. result.z = this.z / otherVector.z;
  3873. result.w = this.w / otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Divides the current Vector3 coordinates by the passed ones.
  3878. * @returns the updated Vector3.
  3879. */
  3880. Vector4.prototype.divideInPlace = function (otherVector) {
  3881. return this.divideToRef(otherVector, this);
  3882. };
  3883. /**
  3884. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3885. * @param other defines the second operand
  3886. * @returns the current updated Vector4
  3887. */
  3888. Vector4.prototype.minimizeInPlace = function (other) {
  3889. if (other.x < this.x)
  3890. this.x = other.x;
  3891. if (other.y < this.y)
  3892. this.y = other.y;
  3893. if (other.z < this.z)
  3894. this.z = other.z;
  3895. if (other.w < this.w)
  3896. this.w = other.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3901. * @param other defines the second operand
  3902. * @returns the current updated Vector4
  3903. */
  3904. Vector4.prototype.maximizeInPlace = function (other) {
  3905. if (other.x > this.x)
  3906. this.x = other.x;
  3907. if (other.y > this.y)
  3908. this.y = other.y;
  3909. if (other.z > this.z)
  3910. this.z = other.z;
  3911. if (other.w > this.w)
  3912. this.w = other.w;
  3913. return this;
  3914. };
  3915. // Properties
  3916. /**
  3917. * Returns the Vector4 length (float).
  3918. */
  3919. Vector4.prototype.length = function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. };
  3922. /**
  3923. * Returns the Vector4 squared length (float).
  3924. */
  3925. Vector4.prototype.lengthSquared = function () {
  3926. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3927. };
  3928. // Methods
  3929. /**
  3930. * Normalizes in place the Vector4.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.normalize = function () {
  3934. var len = this.length();
  3935. if (len === 0)
  3936. return this;
  3937. var num = 1.0 / len;
  3938. this.x *= num;
  3939. this.y *= num;
  3940. this.z *= num;
  3941. this.w *= num;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3946. */
  3947. Vector4.prototype.toVector3 = function () {
  3948. return new Vector3(this.x, this.y, this.z);
  3949. };
  3950. /**
  3951. * Returns a new Vector4 copied from the current one.
  3952. */
  3953. Vector4.prototype.clone = function () {
  3954. return new Vector4(this.x, this.y, this.z, this.w);
  3955. };
  3956. /**
  3957. * Updates the current Vector4 with the passed one coordinates.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.copyFrom = function (source) {
  3961. this.x = source.x;
  3962. this.y = source.y;
  3963. this.z = source.z;
  3964. this.w = source.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Updates the current Vector4 coordinates with the passed floats.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3972. this.x = x;
  3973. this.y = y;
  3974. this.z = z;
  3975. this.w = w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Updates the current Vector4 coordinates with the passed floats.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.set = function (x, y, z, w) {
  3983. return this.copyFromFloats(x, y, z, w);
  3984. };
  3985. // Statics
  3986. /**
  3987. * Returns a new Vector4 set from the starting index of the passed array.
  3988. */
  3989. Vector4.FromArray = function (array, offset) {
  3990. if (!offset) {
  3991. offset = 0;
  3992. }
  3993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3994. };
  3995. /**
  3996. * Updates the passed vector "result" from the starting index of the passed array.
  3997. */
  3998. Vector4.FromArrayToRef = function (array, offset, result) {
  3999. result.x = array[offset];
  4000. result.y = array[offset + 1];
  4001. result.z = array[offset + 2];
  4002. result.w = array[offset + 3];
  4003. };
  4004. /**
  4005. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the passed vector "result" coordinates from the passed floats.
  4012. */
  4013. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4014. result.x = x;
  4015. result.y = y;
  4016. result.z = z;
  4017. result.w = w;
  4018. };
  4019. /**
  4020. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4021. */
  4022. Vector4.Zero = function () {
  4023. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4027. */
  4028. Vector4.One = function () {
  4029. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4030. };
  4031. /**
  4032. * Returns a new normalized Vector4 from the passed one.
  4033. */
  4034. Vector4.Normalize = function (vector) {
  4035. var result = Vector4.Zero();
  4036. Vector4.NormalizeToRef(vector, result);
  4037. return result;
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the normalization of the passed one.
  4041. */
  4042. Vector4.NormalizeToRef = function (vector, result) {
  4043. result.copyFrom(vector);
  4044. result.normalize();
  4045. };
  4046. Vector4.Minimize = function (left, right) {
  4047. var min = left.clone();
  4048. min.minimizeInPlace(right);
  4049. return min;
  4050. };
  4051. Vector4.Maximize = function (left, right) {
  4052. var max = left.clone();
  4053. max.maximizeInPlace(right);
  4054. return max;
  4055. };
  4056. /**
  4057. * Returns the distance (float) between the vectors "value1" and "value2".
  4058. */
  4059. Vector4.Distance = function (value1, value2) {
  4060. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4061. };
  4062. /**
  4063. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4064. */
  4065. Vector4.DistanceSquared = function (value1, value2) {
  4066. var x = value1.x - value2.x;
  4067. var y = value1.y - value2.y;
  4068. var z = value1.z - value2.z;
  4069. var w = value1.w - value2.w;
  4070. return (x * x) + (y * y) + (z * z) + (w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.Center = function (value1, value2) {
  4076. var center = value1.add(value2);
  4077. center.scaleInPlace(0.5);
  4078. return center;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4082. * This methods computes transformed normalized direction vectors only.
  4083. */
  4084. Vector4.TransformNormal = function (vector, transformation) {
  4085. var result = Vector4.Zero();
  4086. Vector4.TransformNormalToRef(vector, transformation, result);
  4087. return result;
  4088. };
  4089. /**
  4090. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4091. * This methods computes transformed normalized direction vectors only.
  4092. */
  4093. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4094. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4095. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4096. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4097. result.x = x;
  4098. result.y = y;
  4099. result.z = z;
  4100. result.w = vector.w;
  4101. };
  4102. /**
  4103. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4107. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4108. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4109. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4110. result.w = w;
  4111. };
  4112. return Vector4;
  4113. }());
  4114. BABYLON.Vector4 = Vector4;
  4115. var Size = /** @class */ (function () {
  4116. /**
  4117. * Creates a Size object from the passed width and height (floats).
  4118. */
  4119. function Size(width, height) {
  4120. this.width = width;
  4121. this.height = height;
  4122. }
  4123. // Returns a string with the Size width and height.
  4124. Size.prototype.toString = function () {
  4125. return "{W: " + this.width + ", H: " + this.height + "}";
  4126. };
  4127. /**
  4128. * Returns the string "Size"
  4129. */
  4130. Size.prototype.getClassName = function () {
  4131. return "Size";
  4132. };
  4133. /**
  4134. * Returns the Size hash code.
  4135. */
  4136. Size.prototype.getHashCode = function () {
  4137. var hash = this.width || 0;
  4138. hash = (hash * 397) ^ (this.height || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Updates the current size from the passed one.
  4143. * Returns the updated Size.
  4144. */
  4145. Size.prototype.copyFrom = function (src) {
  4146. this.width = src.width;
  4147. this.height = src.height;
  4148. };
  4149. /**
  4150. * Updates in place the current Size from the passed floats.
  4151. * Returns the updated Size.
  4152. */
  4153. Size.prototype.copyFromFloats = function (width, height) {
  4154. this.width = width;
  4155. this.height = height;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates in place the current Size from the passed floats.
  4160. * Returns the updated Size.
  4161. */
  4162. Size.prototype.set = function (width, height) {
  4163. return this.copyFromFloats(width, height);
  4164. };
  4165. /**
  4166. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4167. */
  4168. Size.prototype.multiplyByFloats = function (w, h) {
  4169. return new Size(this.width * w, this.height * h);
  4170. };
  4171. /**
  4172. * Returns a new Size copied from the passed one.
  4173. */
  4174. Size.prototype.clone = function () {
  4175. return new Size(this.width, this.height);
  4176. };
  4177. /**
  4178. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4179. */
  4180. Size.prototype.equals = function (other) {
  4181. if (!other) {
  4182. return false;
  4183. }
  4184. return (this.width === other.width) && (this.height === other.height);
  4185. };
  4186. Object.defineProperty(Size.prototype, "surface", {
  4187. /**
  4188. * Returns the surface of the Size : width * height (float).
  4189. */
  4190. get: function () {
  4191. return this.width * this.height;
  4192. },
  4193. enumerable: true,
  4194. configurable: true
  4195. });
  4196. /**
  4197. * Returns a new Size set to (0.0, 0.0)
  4198. */
  4199. Size.Zero = function () {
  4200. return new Size(0.0, 0.0);
  4201. };
  4202. /**
  4203. * Returns a new Size set as the addition result of the current Size and the passed one.
  4204. */
  4205. Size.prototype.add = function (otherSize) {
  4206. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4211. */
  4212. Size.prototype.subtract = function (otherSize) {
  4213. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4214. return r;
  4215. };
  4216. /**
  4217. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4218. */
  4219. Size.Lerp = function (start, end, amount) {
  4220. var w = start.width + ((end.width - start.width) * amount);
  4221. var h = start.height + ((end.height - start.height) * amount);
  4222. return new Size(w, h);
  4223. };
  4224. return Size;
  4225. }());
  4226. BABYLON.Size = Size;
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the passed floats.
  4230. */
  4231. function Quaternion(x, y, z, w) {
  4232. if (x === void 0) { x = 0.0; }
  4233. if (y === void 0) { y = 0.0; }
  4234. if (z === void 0) { z = 0.0; }
  4235. if (w === void 0) { w = 1.0; }
  4236. this.x = x;
  4237. this.y = y;
  4238. this.z = z;
  4239. this.w = w;
  4240. }
  4241. /**
  4242. * Returns a string with the Quaternion coordinates.
  4243. */
  4244. Quaternion.prototype.toString = function () {
  4245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4246. };
  4247. /**
  4248. * Returns the string "Quaternion".
  4249. */
  4250. Quaternion.prototype.getClassName = function () {
  4251. return "Quaternion";
  4252. };
  4253. /**
  4254. * Returns the Quaternion hash code.
  4255. */
  4256. Quaternion.prototype.getHashCode = function () {
  4257. var hash = this.x || 0;
  4258. hash = (hash * 397) ^ (this.y || 0);
  4259. hash = (hash * 397) ^ (this.z || 0);
  4260. hash = (hash * 397) ^ (this.w || 0);
  4261. return hash;
  4262. };
  4263. /**
  4264. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.asArray = function () {
  4267. return [this.x, this.y, this.z, this.w];
  4268. };
  4269. /**
  4270. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4271. */
  4272. Quaternion.prototype.equals = function (otherQuaternion) {
  4273. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4274. };
  4275. /**
  4276. * Returns a new Quaternion copied from the current one.
  4277. */
  4278. Quaternion.prototype.clone = function () {
  4279. return new Quaternion(this.x, this.y, this.z, this.w);
  4280. };
  4281. /**
  4282. * Updates the current Quaternion from the passed one coordinates.
  4283. * Returns the updated Quaterion.
  4284. */
  4285. Quaternion.prototype.copyFrom = function (other) {
  4286. this.x = other.x;
  4287. this.y = other.y;
  4288. this.z = other.z;
  4289. this.w = other.w;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates the current Quaternion from the passed float coordinates.
  4294. * Returns the updated Quaterion.
  4295. */
  4296. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed float coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.set = function (x, y, z, w) {
  4308. return this.copyFromFloats(x, y, z, w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4312. */
  4313. Quaternion.prototype.add = function (other) {
  4314. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4315. };
  4316. /**
  4317. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4318. */
  4319. Quaternion.prototype.subtract = function (other) {
  4320. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4321. };
  4322. /**
  4323. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4324. */
  4325. Quaternion.prototype.scale = function (value) {
  4326. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4327. };
  4328. /**
  4329. * Scale the current Quaternion values by a factor to a given Quaternion
  4330. * @param scale defines the scale factor
  4331. * @param result defines the Quaternion object where to store the result
  4332. * @returns the unmodified current Quaternion
  4333. */
  4334. Quaternion.prototype.scaleToRef = function (scale, result) {
  4335. result.x = this.x * scale;
  4336. result.y = this.y * scale;
  4337. result.z = this.z * scale;
  4338. result.w = this.w * scale;
  4339. return this;
  4340. };
  4341. /**
  4342. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4343. * @param scale defines the scale factor
  4344. * @param result defines the Quaternion object where to store the result
  4345. * @returns the unmodified current Quaternion
  4346. */
  4347. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4348. result.x += this.x * scale;
  4349. result.y += this.y * scale;
  4350. result.z += this.z * scale;
  4351. result.w += this.w * scale;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4356. */
  4357. Quaternion.prototype.multiply = function (q1) {
  4358. var result = new Quaternion(0, 0, 0, 1.0);
  4359. this.multiplyToRef(q1, result);
  4360. return result;
  4361. };
  4362. /**
  4363. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4364. * Returns the current Quaternion.
  4365. */
  4366. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4367. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4368. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4369. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4370. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4371. result.copyFromFloats(x, y, z, w);
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4376. * Returns the updated Quaternion.
  4377. */
  4378. Quaternion.prototype.multiplyInPlace = function (q1) {
  4379. this.multiplyToRef(q1, this);
  4380. return this;
  4381. };
  4382. /**
  4383. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4384. * Returns the current Quaternion.
  4385. */
  4386. Quaternion.prototype.conjugateToRef = function (ref) {
  4387. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4388. return this;
  4389. };
  4390. /**
  4391. * Conjugates in place the current Quaternion.
  4392. * Returns the updated Quaternion.
  4393. */
  4394. Quaternion.prototype.conjugateInPlace = function () {
  4395. this.x *= -1;
  4396. this.y *= -1;
  4397. this.z *= -1;
  4398. return this;
  4399. };
  4400. /**
  4401. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4402. */
  4403. Quaternion.prototype.conjugate = function () {
  4404. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4405. return result;
  4406. };
  4407. /**
  4408. * Returns the Quaternion length (float).
  4409. */
  4410. Quaternion.prototype.length = function () {
  4411. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4412. };
  4413. /**
  4414. * Normalize in place the current Quaternion.
  4415. * Returns the updated Quaternion.
  4416. */
  4417. Quaternion.prototype.normalize = function () {
  4418. var length = 1.0 / this.length();
  4419. this.x *= length;
  4420. this.y *= length;
  4421. this.z *= length;
  4422. this.w *= length;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4427. * @param order is a reserved parameter and is ignore for now
  4428. * @returns the new Vector3
  4429. */
  4430. Quaternion.prototype.toEulerAngles = function (order) {
  4431. if (order === void 0) { order = "YZX"; }
  4432. var result = Vector3.Zero();
  4433. this.toEulerAnglesToRef(result, order);
  4434. return result;
  4435. };
  4436. /**
  4437. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4438. * @param result defines the vector which will be filled with the Euler angles
  4439. * @param order is a reserved parameter and is ignore for now
  4440. * @returns the current Quaternion
  4441. */
  4442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4443. if (order === void 0) { order = "YZX"; }
  4444. var qz = this.z;
  4445. var qx = this.x;
  4446. var qy = this.y;
  4447. var qw = this.w;
  4448. var sqw = qw * qw;
  4449. var sqz = qz * qz;
  4450. var sqx = qx * qx;
  4451. var sqy = qy * qy;
  4452. var zAxisY = qy * qz - qx * qw;
  4453. var limit = .4999999;
  4454. if (zAxisY < -limit) {
  4455. result.y = 2 * Math.atan2(qy, qw);
  4456. result.x = Math.PI / 2;
  4457. result.z = 0;
  4458. }
  4459. else if (zAxisY > limit) {
  4460. result.y = 2 * Math.atan2(qy, qw);
  4461. result.x = -Math.PI / 2;
  4462. result.z = 0;
  4463. }
  4464. else {
  4465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4468. }
  4469. return this;
  4470. };
  4471. /**
  4472. * Updates the passed rotation matrix with the current Quaternion values.
  4473. * Returns the current Quaternion.
  4474. */
  4475. Quaternion.prototype.toRotationMatrix = function (result) {
  4476. var xx = this.x * this.x;
  4477. var yy = this.y * this.y;
  4478. var zz = this.z * this.z;
  4479. var xy = this.x * this.y;
  4480. var zw = this.z * this.w;
  4481. var zx = this.z * this.x;
  4482. var yw = this.y * this.w;
  4483. var yz = this.y * this.z;
  4484. var xw = this.x * this.w;
  4485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4486. result.m[1] = 2.0 * (xy + zw);
  4487. result.m[2] = 2.0 * (zx - yw);
  4488. result.m[3] = 0;
  4489. result.m[4] = 2.0 * (xy - zw);
  4490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4491. result.m[6] = 2.0 * (yz + xw);
  4492. result.m[7] = 0;
  4493. result.m[8] = 2.0 * (zx + yw);
  4494. result.m[9] = 2.0 * (yz - xw);
  4495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4496. result.m[11] = 0;
  4497. result.m[12] = 0;
  4498. result.m[13] = 0;
  4499. result.m[14] = 0;
  4500. result.m[15] = 1.0;
  4501. result._markAsUpdated();
  4502. return this;
  4503. };
  4504. /**
  4505. * Updates the current Quaternion from the passed rotation matrix values.
  4506. * Returns the updated Quaternion.
  4507. */
  4508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4509. Quaternion.FromRotationMatrixToRef(matrix, this);
  4510. return this;
  4511. };
  4512. // Statics
  4513. /**
  4514. * Returns a new Quaternion set from the passed rotation matrix values.
  4515. */
  4516. Quaternion.FromRotationMatrix = function (matrix) {
  4517. var result = new Quaternion();
  4518. Quaternion.FromRotationMatrixToRef(matrix, result);
  4519. return result;
  4520. };
  4521. /**
  4522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4523. */
  4524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4525. var data = matrix.m;
  4526. var m11 = data[0], m12 = data[4], m13 = data[8];
  4527. var m21 = data[1], m22 = data[5], m23 = data[9];
  4528. var m31 = data[2], m32 = data[6], m33 = data[10];
  4529. var trace = m11 + m22 + m33;
  4530. var s;
  4531. if (trace > 0) {
  4532. s = 0.5 / Math.sqrt(trace + 1.0);
  4533. result.w = 0.25 / s;
  4534. result.x = (m32 - m23) * s;
  4535. result.y = (m13 - m31) * s;
  4536. result.z = (m21 - m12) * s;
  4537. }
  4538. else if (m11 > m22 && m11 > m33) {
  4539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4540. result.w = (m32 - m23) / s;
  4541. result.x = 0.25 * s;
  4542. result.y = (m12 + m21) / s;
  4543. result.z = (m13 + m31) / s;
  4544. }
  4545. else if (m22 > m33) {
  4546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4547. result.w = (m13 - m31) / s;
  4548. result.x = (m12 + m21) / s;
  4549. result.y = 0.25 * s;
  4550. result.z = (m23 + m32) / s;
  4551. }
  4552. else {
  4553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4554. result.w = (m21 - m12) / s;
  4555. result.x = (m13 + m31) / s;
  4556. result.y = (m23 + m32) / s;
  4557. result.z = 0.25 * s;
  4558. }
  4559. };
  4560. /**
  4561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4562. */
  4563. Quaternion.Zero = function () {
  4564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4565. };
  4566. /**
  4567. * Returns a new Quaternion as the inverted current Quaternion.
  4568. */
  4569. Quaternion.Inverse = function (q) {
  4570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4571. };
  4572. /**
  4573. * Returns the identity Quaternion.
  4574. */
  4575. Quaternion.Identity = function () {
  4576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4577. };
  4578. Quaternion.IsIdentity = function (quaternion) {
  4579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4580. };
  4581. /**
  4582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4583. */
  4584. Quaternion.RotationAxis = function (axis, angle) {
  4585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4586. };
  4587. /**
  4588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4589. */
  4590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4591. var sin = Math.sin(angle / 2);
  4592. axis.normalize();
  4593. result.w = Math.cos(angle / 2);
  4594. result.x = axis.x * sin;
  4595. result.y = axis.y * sin;
  4596. result.z = axis.z * sin;
  4597. return result;
  4598. };
  4599. /**
  4600. * Retuns a new Quaternion set from the starting index of the passed array.
  4601. */
  4602. Quaternion.FromArray = function (array, offset) {
  4603. if (!offset) {
  4604. offset = 0;
  4605. }
  4606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4610. */
  4611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4612. var q = new Quaternion();
  4613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4614. return q;
  4615. };
  4616. /**
  4617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4618. */
  4619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4621. var halfRoll = roll * 0.5;
  4622. var halfPitch = pitch * 0.5;
  4623. var halfYaw = yaw * 0.5;
  4624. var sinRoll = Math.sin(halfRoll);
  4625. var cosRoll = Math.cos(halfRoll);
  4626. var sinPitch = Math.sin(halfPitch);
  4627. var cosPitch = Math.cos(halfPitch);
  4628. var sinYaw = Math.sin(halfYaw);
  4629. var cosYaw = Math.cos(halfYaw);
  4630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4637. */
  4638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4639. var result = new Quaternion();
  4640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4645. */
  4646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4647. // Produces a quaternion from Euler angles in the z-x-z orientation
  4648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4650. var halfBeta = beta * 0.5;
  4651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4655. };
  4656. /**
  4657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4658. * cf to Vector3.RotationFromAxis() documentation.
  4659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4660. */
  4661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4664. return quat;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4668. * cf to Vector3.RotationFromAxis() documentation.
  4669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4670. */
  4671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4672. var rotMat = MathTmp.Matrix[0];
  4673. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4674. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4675. };
  4676. Quaternion.Slerp = function (left, right, amount) {
  4677. var result = Quaternion.Identity();
  4678. Quaternion.SlerpToRef(left, right, amount, result);
  4679. return result;
  4680. };
  4681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4682. var num2;
  4683. var num3;
  4684. var num = amount;
  4685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4686. var flag = false;
  4687. if (num4 < 0) {
  4688. flag = true;
  4689. num4 = -num4;
  4690. }
  4691. if (num4 > 0.999999) {
  4692. num3 = 1 - num;
  4693. num2 = flag ? -num : num;
  4694. }
  4695. else {
  4696. var num5 = Math.acos(num4);
  4697. var num6 = (1.0 / Math.sin(num5));
  4698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4700. }
  4701. result.x = (num3 * left.x) + (num2 * right.x);
  4702. result.y = (num3 * left.y) + (num2 * right.y);
  4703. result.z = (num3 * left.z) + (num2 * right.z);
  4704. result.w = (num3 * left.w) + (num2 * right.w);
  4705. };
  4706. /**
  4707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4708. */
  4709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4710. var squared = amount * amount;
  4711. var cubed = amount * squared;
  4712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4714. var part3 = (cubed - (2.0 * squared)) + amount;
  4715. var part4 = cubed - squared;
  4716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4720. return new Quaternion(x, y, z, w);
  4721. };
  4722. return Quaternion;
  4723. }());
  4724. BABYLON.Quaternion = Quaternion;
  4725. var Matrix = /** @class */ (function () {
  4726. function Matrix() {
  4727. this._isIdentity = false;
  4728. this._isIdentityDirty = true;
  4729. this.m = new Float32Array(16);
  4730. this._markAsUpdated();
  4731. }
  4732. Matrix.prototype._markAsUpdated = function () {
  4733. this.updateFlag = Matrix._updateFlagSeed++;
  4734. this._isIdentityDirty = true;
  4735. };
  4736. // Properties
  4737. /**
  4738. * Boolean : True is the matrix is the identity matrix
  4739. */
  4740. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4741. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4742. if (this._isIdentityDirty) {
  4743. this._isIdentityDirty = false;
  4744. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4745. this._isIdentity = false;
  4746. }
  4747. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4751. this._isIdentity = false;
  4752. }
  4753. else {
  4754. this._isIdentity = true;
  4755. }
  4756. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4757. this._isIdentity = false;
  4758. }
  4759. }
  4760. return this._isIdentity;
  4761. };
  4762. /**
  4763. * Returns the matrix determinant (float).
  4764. */
  4765. Matrix.prototype.determinant = function () {
  4766. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4767. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4768. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4769. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4770. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4771. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4772. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4773. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4774. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4775. };
  4776. // Methods
  4777. /**
  4778. * Returns the matrix underlying array.
  4779. */
  4780. Matrix.prototype.toArray = function () {
  4781. return this.m;
  4782. };
  4783. /**
  4784. * Returns the matrix underlying array.
  4785. */
  4786. Matrix.prototype.asArray = function () {
  4787. return this.toArray();
  4788. };
  4789. /**
  4790. * Inverts in place the Matrix.
  4791. * Returns the Matrix inverted.
  4792. */
  4793. Matrix.prototype.invert = function () {
  4794. this.invertToRef(this);
  4795. return this;
  4796. };
  4797. /**
  4798. * Sets all the matrix elements to zero.
  4799. * Returns the Matrix.
  4800. */
  4801. Matrix.prototype.reset = function () {
  4802. for (var index = 0; index < 16; index++) {
  4803. this.m[index] = 0.0;
  4804. }
  4805. this._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4810. */
  4811. Matrix.prototype.add = function (other) {
  4812. var result = new Matrix();
  4813. this.addToRef(other, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.addToRef = function (other, result) {
  4821. for (var index = 0; index < 16; index++) {
  4822. result.m[index] = this.m[index] + other.m[index];
  4823. }
  4824. result._markAsUpdated();
  4825. return this;
  4826. };
  4827. /**
  4828. * Adds in place the passed matrix to the current Matrix.
  4829. * Returns the updated Matrix.
  4830. */
  4831. Matrix.prototype.addToSelf = function (other) {
  4832. for (var index = 0; index < 16; index++) {
  4833. this.m[index] += other.m[index];
  4834. }
  4835. this._markAsUpdated();
  4836. return this;
  4837. };
  4838. /**
  4839. * Sets the passed matrix with the current inverted Matrix.
  4840. * Returns the unmodified current Matrix.
  4841. */
  4842. Matrix.prototype.invertToRef = function (other) {
  4843. var l1 = this.m[0];
  4844. var l2 = this.m[1];
  4845. var l3 = this.m[2];
  4846. var l4 = this.m[3];
  4847. var l5 = this.m[4];
  4848. var l6 = this.m[5];
  4849. var l7 = this.m[6];
  4850. var l8 = this.m[7];
  4851. var l9 = this.m[8];
  4852. var l10 = this.m[9];
  4853. var l11 = this.m[10];
  4854. var l12 = this.m[11];
  4855. var l13 = this.m[12];
  4856. var l14 = this.m[13];
  4857. var l15 = this.m[14];
  4858. var l16 = this.m[15];
  4859. var l17 = (l11 * l16) - (l12 * l15);
  4860. var l18 = (l10 * l16) - (l12 * l14);
  4861. var l19 = (l10 * l15) - (l11 * l14);
  4862. var l20 = (l9 * l16) - (l12 * l13);
  4863. var l21 = (l9 * l15) - (l11 * l13);
  4864. var l22 = (l9 * l14) - (l10 * l13);
  4865. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4866. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4867. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4868. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4869. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4870. var l28 = (l7 * l16) - (l8 * l15);
  4871. var l29 = (l6 * l16) - (l8 * l14);
  4872. var l30 = (l6 * l15) - (l7 * l14);
  4873. var l31 = (l5 * l16) - (l8 * l13);
  4874. var l32 = (l5 * l15) - (l7 * l13);
  4875. var l33 = (l5 * l14) - (l6 * l13);
  4876. var l34 = (l7 * l12) - (l8 * l11);
  4877. var l35 = (l6 * l12) - (l8 * l10);
  4878. var l36 = (l6 * l11) - (l7 * l10);
  4879. var l37 = (l5 * l12) - (l8 * l9);
  4880. var l38 = (l5 * l11) - (l7 * l9);
  4881. var l39 = (l5 * l10) - (l6 * l9);
  4882. other.m[0] = l23 * l27;
  4883. other.m[4] = l24 * l27;
  4884. other.m[8] = l25 * l27;
  4885. other.m[12] = l26 * l27;
  4886. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4887. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4888. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4889. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4890. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4891. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4892. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4893. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4894. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4895. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4896. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4897. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4898. other._markAsUpdated();
  4899. return this;
  4900. };
  4901. /**
  4902. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4903. * Returns the updated Matrix.
  4904. */
  4905. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4906. this.m[12] = x;
  4907. this.m[13] = y;
  4908. this.m[14] = z;
  4909. this._markAsUpdated();
  4910. return this;
  4911. };
  4912. /**
  4913. * Inserts the translation vector in the current Matrix.
  4914. * Returns the updated Matrix.
  4915. */
  4916. Matrix.prototype.setTranslation = function (vector3) {
  4917. this.m[12] = vector3.x;
  4918. this.m[13] = vector3.y;
  4919. this.m[14] = vector3.z;
  4920. this._markAsUpdated();
  4921. return this;
  4922. };
  4923. /**
  4924. * Returns a new Vector3 as the extracted translation from the Matrix.
  4925. */
  4926. Matrix.prototype.getTranslation = function () {
  4927. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4928. };
  4929. /**
  4930. * Fill a Vector3 with the extracted translation from the Matrix.
  4931. */
  4932. Matrix.prototype.getTranslationToRef = function (result) {
  4933. result.x = this.m[12];
  4934. result.y = this.m[13];
  4935. result.z = this.m[14];
  4936. return this;
  4937. };
  4938. /**
  4939. * Remove rotation and scaling part from the Matrix.
  4940. * Returns the updated Matrix.
  4941. */
  4942. Matrix.prototype.removeRotationAndScaling = function () {
  4943. this.setRowFromFloats(0, 1, 0, 0, 0);
  4944. this.setRowFromFloats(1, 0, 1, 0, 0);
  4945. this.setRowFromFloats(2, 0, 0, 1, 0);
  4946. return this;
  4947. };
  4948. /**
  4949. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4950. */
  4951. Matrix.prototype.multiply = function (other) {
  4952. var result = new Matrix();
  4953. this.multiplyToRef(other, result);
  4954. return result;
  4955. };
  4956. /**
  4957. * Updates the current Matrix from the passed one values.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.copyFrom = function (other) {
  4961. for (var index = 0; index < 16; index++) {
  4962. this.m[index] = other.m[index];
  4963. }
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Populates the passed array from the starting index with the Matrix values.
  4969. * Returns the Matrix.
  4970. */
  4971. Matrix.prototype.copyToArray = function (array, offset) {
  4972. if (offset === void 0) { offset = 0; }
  4973. for (var index = 0; index < 16; index++) {
  4974. array[offset + index] = this.m[index];
  4975. }
  4976. return this;
  4977. };
  4978. /**
  4979. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4980. */
  4981. Matrix.prototype.multiplyToRef = function (other, result) {
  4982. this.multiplyToArray(other, result.m, 0);
  4983. result._markAsUpdated();
  4984. return this;
  4985. };
  4986. /**
  4987. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4988. */
  4989. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4990. var tm0 = this.m[0];
  4991. var tm1 = this.m[1];
  4992. var tm2 = this.m[2];
  4993. var tm3 = this.m[3];
  4994. var tm4 = this.m[4];
  4995. var tm5 = this.m[5];
  4996. var tm6 = this.m[6];
  4997. var tm7 = this.m[7];
  4998. var tm8 = this.m[8];
  4999. var tm9 = this.m[9];
  5000. var tm10 = this.m[10];
  5001. var tm11 = this.m[11];
  5002. var tm12 = this.m[12];
  5003. var tm13 = this.m[13];
  5004. var tm14 = this.m[14];
  5005. var tm15 = this.m[15];
  5006. var om0 = other.m[0];
  5007. var om1 = other.m[1];
  5008. var om2 = other.m[2];
  5009. var om3 = other.m[3];
  5010. var om4 = other.m[4];
  5011. var om5 = other.m[5];
  5012. var om6 = other.m[6];
  5013. var om7 = other.m[7];
  5014. var om8 = other.m[8];
  5015. var om9 = other.m[9];
  5016. var om10 = other.m[10];
  5017. var om11 = other.m[11];
  5018. var om12 = other.m[12];
  5019. var om13 = other.m[13];
  5020. var om14 = other.m[14];
  5021. var om15 = other.m[15];
  5022. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5023. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5024. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5025. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5026. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5027. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5028. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5029. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5030. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5031. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5032. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5033. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5034. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5035. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5036. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5037. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5038. return this;
  5039. };
  5040. /**
  5041. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5042. */
  5043. Matrix.prototype.equals = function (value) {
  5044. return value &&
  5045. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5046. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5047. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5048. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5049. };
  5050. /**
  5051. * Returns a new Matrix from the current Matrix.
  5052. */
  5053. Matrix.prototype.clone = function () {
  5054. 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]);
  5055. };
  5056. /**
  5057. * Returns the string "Matrix"
  5058. */
  5059. Matrix.prototype.getClassName = function () {
  5060. return "Matrix";
  5061. };
  5062. /**
  5063. * Returns the Matrix hash code.
  5064. */
  5065. Matrix.prototype.getHashCode = function () {
  5066. var hash = this.m[0] || 0;
  5067. for (var i = 1; i < 16; i++) {
  5068. hash = (hash * 397) ^ (this.m[i] || 0);
  5069. }
  5070. return hash;
  5071. };
  5072. /**
  5073. * Decomposes the current Matrix into :
  5074. * - a scale vector3 passed as a reference to update,
  5075. * - a rotation quaternion passed as a reference to update,
  5076. * - a translation vector3 passed as a reference to update.
  5077. * Returns the true if operation was successful.
  5078. */
  5079. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5080. translation.x = this.m[12];
  5081. translation.y = this.m[13];
  5082. translation.z = this.m[14];
  5083. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5084. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5085. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5086. if (this.determinant() <= 0) {
  5087. scale.y *= -1;
  5088. }
  5089. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5090. rotation.x = 0;
  5091. rotation.y = 0;
  5092. rotation.z = 0;
  5093. rotation.w = 1;
  5094. return false;
  5095. }
  5096. 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]);
  5097. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5098. return true;
  5099. };
  5100. /**
  5101. * Returns the index-th row of the current matrix as a new Vector4.
  5102. */
  5103. Matrix.prototype.getRow = function (index) {
  5104. if (index < 0 || index > 3) {
  5105. return null;
  5106. }
  5107. var i = index * 4;
  5108. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5109. };
  5110. /**
  5111. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5112. * Returns the updated Matrix.
  5113. */
  5114. Matrix.prototype.setRow = function (index, row) {
  5115. if (index < 0 || index > 3) {
  5116. return this;
  5117. }
  5118. var i = index * 4;
  5119. this.m[i + 0] = row.x;
  5120. this.m[i + 1] = row.y;
  5121. this.m[i + 2] = row.z;
  5122. this.m[i + 3] = row.w;
  5123. this._markAsUpdated();
  5124. return this;
  5125. };
  5126. /**
  5127. * Compute the transpose of the matrix.
  5128. * Returns a new Matrix.
  5129. */
  5130. Matrix.prototype.transpose = function () {
  5131. return Matrix.Transpose(this);
  5132. };
  5133. /**
  5134. * Compute the transpose of the matrix.
  5135. * Returns the current matrix.
  5136. */
  5137. Matrix.prototype.transposeToRef = function (result) {
  5138. Matrix.TransposeToRef(this, result);
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5143. * Returns the updated Matrix.
  5144. */
  5145. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5146. if (index < 0 || index > 3) {
  5147. return this;
  5148. }
  5149. var i = index * 4;
  5150. this.m[i + 0] = x;
  5151. this.m[i + 1] = y;
  5152. this.m[i + 2] = z;
  5153. this.m[i + 3] = w;
  5154. this._markAsUpdated();
  5155. return this;
  5156. };
  5157. /**
  5158. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5159. * @param scale defines the scale factor
  5160. * @returns a new Matrix
  5161. */
  5162. Matrix.prototype.scale = function (scale) {
  5163. var result = new Matrix();
  5164. this.scaleToRef(scale, result);
  5165. return result;
  5166. };
  5167. /**
  5168. * Scale the current Matrix values by a factor to a given result Matrix
  5169. * @param scale defines the scale factor
  5170. * @param result defines the Matrix to store the result
  5171. * @returns the current Matrix
  5172. */
  5173. Matrix.prototype.scaleToRef = function (scale, result) {
  5174. for (var index = 0; index < 16; index++) {
  5175. result.m[index] = this.m[index] * scale;
  5176. }
  5177. result._markAsUpdated();
  5178. return this;
  5179. };
  5180. /**
  5181. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5182. * @param scale defines the scale factor
  5183. * @param result defines the Matrix to store the result
  5184. * @returns the current Matrix
  5185. */
  5186. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5187. for (var index = 0; index < 16; index++) {
  5188. result.m[index] += this.m[index] * scale;
  5189. }
  5190. result._markAsUpdated();
  5191. return this;
  5192. };
  5193. /**
  5194. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5195. * @param ref matrix to store the result
  5196. */
  5197. Matrix.prototype.toNormalMatrix = function (ref) {
  5198. this.invertToRef(ref);
  5199. ref.transpose();
  5200. var m = ref.m;
  5201. 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);
  5202. };
  5203. /**
  5204. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5205. */
  5206. Matrix.prototype.getRotationMatrix = function () {
  5207. var result = Matrix.Identity();
  5208. this.getRotationMatrixToRef(result);
  5209. return result;
  5210. };
  5211. /**
  5212. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5213. * Returns the current Matrix.
  5214. */
  5215. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5216. var m = this.m;
  5217. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5218. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5219. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5220. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5221. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5222. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5223. 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);
  5224. return this;
  5225. };
  5226. // Statics
  5227. /**
  5228. * Returns a new Matrix set from the starting index of the passed array.
  5229. */
  5230. Matrix.FromArray = function (array, offset) {
  5231. var result = new Matrix();
  5232. if (!offset) {
  5233. offset = 0;
  5234. }
  5235. Matrix.FromArrayToRef(array, offset, result);
  5236. return result;
  5237. };
  5238. /**
  5239. * Sets the passed "result" matrix from the starting index of the passed array.
  5240. */
  5241. Matrix.FromArrayToRef = function (array, offset, result) {
  5242. for (var index = 0; index < 16; index++) {
  5243. result.m[index] = array[index + offset];
  5244. }
  5245. result._markAsUpdated();
  5246. };
  5247. /**
  5248. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5249. */
  5250. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5251. for (var index = 0; index < 16; index++) {
  5252. result.m[index] = array[index + offset] * scale;
  5253. }
  5254. result._markAsUpdated();
  5255. };
  5256. /**
  5257. * Sets the passed matrix "result" with the 16 passed floats.
  5258. */
  5259. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5260. result.m[0] = initialM11;
  5261. result.m[1] = initialM12;
  5262. result.m[2] = initialM13;
  5263. result.m[3] = initialM14;
  5264. result.m[4] = initialM21;
  5265. result.m[5] = initialM22;
  5266. result.m[6] = initialM23;
  5267. result.m[7] = initialM24;
  5268. result.m[8] = initialM31;
  5269. result.m[9] = initialM32;
  5270. result.m[10] = initialM33;
  5271. result.m[11] = initialM34;
  5272. result.m[12] = initialM41;
  5273. result.m[13] = initialM42;
  5274. result.m[14] = initialM43;
  5275. result.m[15] = initialM44;
  5276. result._markAsUpdated();
  5277. };
  5278. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5279. /**
  5280. * Static identity matrix to be used as readonly matrix
  5281. * Must not be updated.
  5282. */
  5283. get: function () {
  5284. return Matrix._identityReadOnly;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. /**
  5290. * Returns a new Matrix set from the 16 passed floats.
  5291. */
  5292. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5293. var result = new Matrix();
  5294. result.m[0] = initialM11;
  5295. result.m[1] = initialM12;
  5296. result.m[2] = initialM13;
  5297. result.m[3] = initialM14;
  5298. result.m[4] = initialM21;
  5299. result.m[5] = initialM22;
  5300. result.m[6] = initialM23;
  5301. result.m[7] = initialM24;
  5302. result.m[8] = initialM31;
  5303. result.m[9] = initialM32;
  5304. result.m[10] = initialM33;
  5305. result.m[11] = initialM34;
  5306. result.m[12] = initialM41;
  5307. result.m[13] = initialM42;
  5308. result.m[14] = initialM43;
  5309. result.m[15] = initialM44;
  5310. return result;
  5311. };
  5312. /**
  5313. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5314. */
  5315. Matrix.Compose = function (scale, rotation, translation) {
  5316. var result = Matrix.Identity();
  5317. Matrix.ComposeToRef(scale, rotation, translation, result);
  5318. return result;
  5319. };
  5320. /**
  5321. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5322. */
  5323. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5324. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5325. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5326. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5327. result.setTranslation(translation);
  5328. };
  5329. /**
  5330. * Returns a new indentity Matrix.
  5331. */
  5332. Matrix.Identity = function () {
  5333. 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);
  5334. };
  5335. /**
  5336. * Sets the passed "result" as an identity matrix.
  5337. */
  5338. Matrix.IdentityToRef = function (result) {
  5339. 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);
  5340. };
  5341. /**
  5342. * Returns a new zero Matrix.
  5343. */
  5344. Matrix.Zero = function () {
  5345. 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);
  5346. };
  5347. /**
  5348. * Returns a new rotation matrix for "angle" radians around the X axis.
  5349. */
  5350. Matrix.RotationX = function (angle) {
  5351. var result = new Matrix();
  5352. Matrix.RotationXToRef(angle, result);
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix as the passed inverted one.
  5357. */
  5358. Matrix.Invert = function (source) {
  5359. var result = new Matrix();
  5360. source.invertToRef(result);
  5361. return result;
  5362. };
  5363. /**
  5364. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5365. */
  5366. Matrix.RotationXToRef = function (angle, result) {
  5367. var s = Math.sin(angle);
  5368. var c = Math.cos(angle);
  5369. result.m[0] = 1.0;
  5370. result.m[15] = 1.0;
  5371. result.m[5] = c;
  5372. result.m[10] = c;
  5373. result.m[9] = -s;
  5374. result.m[6] = s;
  5375. result.m[1] = 0.0;
  5376. result.m[2] = 0.0;
  5377. result.m[3] = 0.0;
  5378. result.m[4] = 0.0;
  5379. result.m[7] = 0.0;
  5380. result.m[8] = 0.0;
  5381. result.m[11] = 0.0;
  5382. result.m[12] = 0.0;
  5383. result.m[13] = 0.0;
  5384. result.m[14] = 0.0;
  5385. result._markAsUpdated();
  5386. };
  5387. /**
  5388. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5389. */
  5390. Matrix.RotationY = function (angle) {
  5391. var result = new Matrix();
  5392. Matrix.RotationYToRef(angle, result);
  5393. return result;
  5394. };
  5395. /**
  5396. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5397. */
  5398. Matrix.RotationYToRef = function (angle, result) {
  5399. var s = Math.sin(angle);
  5400. var c = Math.cos(angle);
  5401. result.m[5] = 1.0;
  5402. result.m[15] = 1.0;
  5403. result.m[0] = c;
  5404. result.m[2] = -s;
  5405. result.m[8] = s;
  5406. result.m[10] = c;
  5407. result.m[1] = 0.0;
  5408. result.m[3] = 0.0;
  5409. result.m[4] = 0.0;
  5410. result.m[6] = 0.0;
  5411. result.m[7] = 0.0;
  5412. result.m[9] = 0.0;
  5413. result.m[11] = 0.0;
  5414. result.m[12] = 0.0;
  5415. result.m[13] = 0.0;
  5416. result.m[14] = 0.0;
  5417. result._markAsUpdated();
  5418. };
  5419. /**
  5420. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5421. */
  5422. Matrix.RotationZ = function (angle) {
  5423. var result = new Matrix();
  5424. Matrix.RotationZToRef(angle, result);
  5425. return result;
  5426. };
  5427. /**
  5428. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5429. */
  5430. Matrix.RotationZToRef = function (angle, result) {
  5431. var s = Math.sin(angle);
  5432. var c = Math.cos(angle);
  5433. result.m[10] = 1.0;
  5434. result.m[15] = 1.0;
  5435. result.m[0] = c;
  5436. result.m[1] = s;
  5437. result.m[4] = -s;
  5438. result.m[5] = c;
  5439. result.m[2] = 0.0;
  5440. result.m[3] = 0.0;
  5441. result.m[6] = 0.0;
  5442. result.m[7] = 0.0;
  5443. result.m[8] = 0.0;
  5444. result.m[9] = 0.0;
  5445. result.m[11] = 0.0;
  5446. result.m[12] = 0.0;
  5447. result.m[13] = 0.0;
  5448. result.m[14] = 0.0;
  5449. result._markAsUpdated();
  5450. };
  5451. /**
  5452. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5453. */
  5454. Matrix.RotationAxis = function (axis, angle) {
  5455. var result = Matrix.Zero();
  5456. Matrix.RotationAxisToRef(axis, angle, result);
  5457. return result;
  5458. };
  5459. /**
  5460. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5461. */
  5462. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5463. var s = Math.sin(-angle);
  5464. var c = Math.cos(-angle);
  5465. var c1 = 1 - c;
  5466. axis.normalize();
  5467. result.m[0] = (axis.x * axis.x) * c1 + c;
  5468. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5469. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5470. result.m[3] = 0.0;
  5471. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5472. result.m[5] = (axis.y * axis.y) * c1 + c;
  5473. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5474. result.m[7] = 0.0;
  5475. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5476. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5477. result.m[10] = (axis.z * axis.z) * c1 + c;
  5478. result.m[11] = 0.0;
  5479. result.m[15] = 1.0;
  5480. result._markAsUpdated();
  5481. };
  5482. /**
  5483. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5484. */
  5485. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5486. var result = new Matrix();
  5487. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5492. */
  5493. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5494. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5495. this._tempQuaternion.toRotationMatrix(result);
  5496. };
  5497. /**
  5498. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5499. */
  5500. Matrix.Scaling = function (x, y, z) {
  5501. var result = Matrix.Zero();
  5502. Matrix.ScalingToRef(x, y, z, result);
  5503. return result;
  5504. };
  5505. /**
  5506. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5507. */
  5508. Matrix.ScalingToRef = function (x, y, z, result) {
  5509. result.m[0] = x;
  5510. result.m[1] = 0.0;
  5511. result.m[2] = 0.0;
  5512. result.m[3] = 0.0;
  5513. result.m[4] = 0.0;
  5514. result.m[5] = y;
  5515. result.m[6] = 0.0;
  5516. result.m[7] = 0.0;
  5517. result.m[8] = 0.0;
  5518. result.m[9] = 0.0;
  5519. result.m[10] = z;
  5520. result.m[11] = 0.0;
  5521. result.m[12] = 0.0;
  5522. result.m[13] = 0.0;
  5523. result.m[14] = 0.0;
  5524. result.m[15] = 1.0;
  5525. result._markAsUpdated();
  5526. };
  5527. /**
  5528. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5529. */
  5530. Matrix.Translation = function (x, y, z) {
  5531. var result = Matrix.Identity();
  5532. Matrix.TranslationToRef(x, y, z, result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5537. */
  5538. Matrix.TranslationToRef = function (x, y, z, result) {
  5539. 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);
  5540. };
  5541. /**
  5542. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5543. * @param startValue defines the start value
  5544. * @param endValue defines the end value
  5545. * @param gradient defines the gradient factor
  5546. * @returns the new matrix
  5547. */
  5548. Matrix.Lerp = function (startValue, endValue, gradient) {
  5549. var result = Matrix.Zero();
  5550. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5551. return result;
  5552. };
  5553. /**
  5554. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5555. * @param startValue defines the start value
  5556. * @param endValue defines the end value
  5557. * @param gradient defines the gradient factor
  5558. * @param result defines the Matrix object where to store data
  5559. */
  5560. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5561. for (var index = 0; index < 16; index++) {
  5562. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5563. }
  5564. result._markAsUpdated();
  5565. };
  5566. /**
  5567. * Returns a new Matrix whose values are computed by :
  5568. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5569. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5570. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5571. */
  5572. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5573. var startScale = new Vector3(0, 0, 0);
  5574. var startRotation = new Quaternion();
  5575. var startTranslation = new Vector3(0, 0, 0);
  5576. startValue.decompose(startScale, startRotation, startTranslation);
  5577. var endScale = new Vector3(0, 0, 0);
  5578. var endRotation = new Quaternion();
  5579. var endTranslation = new Vector3(0, 0, 0);
  5580. endValue.decompose(endScale, endRotation, endTranslation);
  5581. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5582. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5583. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5584. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5585. };
  5586. /**
  5587. * 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".
  5588. * This methods works for a Left-Handed system.
  5589. */
  5590. Matrix.LookAtLH = function (eye, target, up) {
  5591. var result = Matrix.Zero();
  5592. Matrix.LookAtLHToRef(eye, target, up, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * 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".
  5597. * This methods works for a Left-Handed system.
  5598. */
  5599. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5600. // Z axis
  5601. target.subtractToRef(eye, this._zAxis);
  5602. this._zAxis.normalize();
  5603. // X axis
  5604. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5605. if (this._xAxis.lengthSquared() === 0) {
  5606. this._xAxis.x = 1.0;
  5607. }
  5608. else {
  5609. this._xAxis.normalize();
  5610. }
  5611. // Y axis
  5612. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5613. this._yAxis.normalize();
  5614. // Eye angles
  5615. var ex = -Vector3.Dot(this._xAxis, eye);
  5616. var ey = -Vector3.Dot(this._yAxis, eye);
  5617. var ez = -Vector3.Dot(this._zAxis, eye);
  5618. 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);
  5619. };
  5620. /**
  5621. * 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".
  5622. * This methods works for a Right-Handed system.
  5623. */
  5624. Matrix.LookAtRH = function (eye, target, up) {
  5625. var result = Matrix.Zero();
  5626. Matrix.LookAtRHToRef(eye, target, up, result);
  5627. return result;
  5628. };
  5629. /**
  5630. * 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".
  5631. * This methods works for a Left-Handed system.
  5632. */
  5633. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5634. // Z axis
  5635. eye.subtractToRef(target, this._zAxis);
  5636. this._zAxis.normalize();
  5637. // X axis
  5638. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5639. if (this._xAxis.lengthSquared() === 0) {
  5640. this._xAxis.x = 1.0;
  5641. }
  5642. else {
  5643. this._xAxis.normalize();
  5644. }
  5645. // Y axis
  5646. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5647. this._yAxis.normalize();
  5648. // Eye angles
  5649. var ex = -Vector3.Dot(this._xAxis, eye);
  5650. var ey = -Vector3.Dot(this._yAxis, eye);
  5651. var ez = -Vector3.Dot(this._zAxis, eye);
  5652. 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);
  5653. };
  5654. /**
  5655. * 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.
  5656. */
  5657. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * 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.
  5664. */
  5665. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5666. var n = znear;
  5667. var f = zfar;
  5668. var a = 2.0 / width;
  5669. var b = 2.0 / height;
  5670. var c = 2.0 / (f - n);
  5671. var d = -(f + n) / (f - n);
  5672. 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);
  5673. };
  5674. /**
  5675. * 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.
  5676. */
  5677. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5678. var matrix = Matrix.Zero();
  5679. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5680. return matrix;
  5681. };
  5682. /**
  5683. * 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.
  5684. */
  5685. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5686. var n = znear;
  5687. var f = zfar;
  5688. var a = 2.0 / (right - left);
  5689. var b = 2.0 / (top - bottom);
  5690. var c = 2.0 / (f - n);
  5691. var d = -(f + n) / (f - n);
  5692. var i0 = (left + right) / (left - right);
  5693. var i1 = (top + bottom) / (bottom - top);
  5694. 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);
  5695. };
  5696. /**
  5697. * 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.
  5698. */
  5699. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5700. var matrix = Matrix.Zero();
  5701. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5702. return matrix;
  5703. };
  5704. /**
  5705. * 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.
  5706. */
  5707. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5708. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5709. result.m[10] *= -1.0;
  5710. };
  5711. /**
  5712. * 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.
  5713. */
  5714. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5715. var matrix = Matrix.Zero();
  5716. var n = znear;
  5717. var f = zfar;
  5718. var a = 2.0 * n / width;
  5719. var b = 2.0 * n / height;
  5720. var c = (f + n) / (f - n);
  5721. var d = -2.0 * f * n / (f - n);
  5722. 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);
  5723. return matrix;
  5724. };
  5725. /**
  5726. * 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.
  5727. */
  5728. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5729. var matrix = Matrix.Zero();
  5730. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5731. return matrix;
  5732. };
  5733. /**
  5734. * 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.
  5735. */
  5736. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5737. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5738. var n = znear;
  5739. var f = zfar;
  5740. var t = 1.0 / (Math.tan(fov * 0.5));
  5741. var a = isVerticalFovFixed ? (t / aspect) : t;
  5742. var b = isVerticalFovFixed ? t : (t * aspect);
  5743. var c = (f + n) / (f - n);
  5744. var d = -2.0 * f * n / (f - n);
  5745. 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);
  5746. };
  5747. /**
  5748. * 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.
  5749. */
  5750. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5751. var matrix = Matrix.Zero();
  5752. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5753. return matrix;
  5754. };
  5755. /**
  5756. * 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.
  5757. */
  5758. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5759. //alternatively this could be expressed as:
  5760. // m = PerspectiveFovLHToRef
  5761. // m[10] *= -1.0;
  5762. // m[11] *= -1.0;
  5763. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5764. var n = znear;
  5765. var f = zfar;
  5766. var t = 1.0 / (Math.tan(fov * 0.5));
  5767. var a = isVerticalFovFixed ? (t / aspect) : t;
  5768. var b = isVerticalFovFixed ? t : (t * aspect);
  5769. var c = -(f + n) / (f - n);
  5770. var d = -2 * f * n / (f - n);
  5771. 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);
  5772. };
  5773. /**
  5774. * 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.
  5775. */
  5776. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5777. if (rightHanded === void 0) { rightHanded = false; }
  5778. var rightHandedFactor = rightHanded ? -1 : 1;
  5779. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5780. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5781. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5782. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5783. var xScale = 2.0 / (leftTan + rightTan);
  5784. var yScale = 2.0 / (upTan + downTan);
  5785. result.m[0] = xScale;
  5786. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5787. result.m[5] = yScale;
  5788. result.m[6] = result.m[7] = 0.0;
  5789. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5790. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5791. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5792. result.m[10] = -zfar / (znear - zfar);
  5793. result.m[11] = 1.0 * rightHandedFactor;
  5794. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5795. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5796. // result.m[14] = (znear * zfar) / (znear - zfar);
  5797. result._markAsUpdated();
  5798. };
  5799. /**
  5800. * Returns the final transformation matrix : world * view * projection * viewport
  5801. */
  5802. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5803. var cw = viewport.width;
  5804. var ch = viewport.height;
  5805. var cx = viewport.x;
  5806. var cy = viewport.y;
  5807. 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);
  5808. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5809. };
  5810. /**
  5811. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5812. */
  5813. Matrix.GetAsMatrix2x2 = function (matrix) {
  5814. return new Float32Array([
  5815. matrix.m[0], matrix.m[1],
  5816. matrix.m[4], matrix.m[5]
  5817. ]);
  5818. };
  5819. /**
  5820. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5821. */
  5822. Matrix.GetAsMatrix3x3 = function (matrix) {
  5823. return new Float32Array([
  5824. matrix.m[0], matrix.m[1], matrix.m[2],
  5825. matrix.m[4], matrix.m[5], matrix.m[6],
  5826. matrix.m[8], matrix.m[9], matrix.m[10]
  5827. ]);
  5828. };
  5829. /**
  5830. * Compute the transpose of the passed Matrix.
  5831. * Returns a new Matrix.
  5832. */
  5833. Matrix.Transpose = function (matrix) {
  5834. var result = new Matrix();
  5835. Matrix.TransposeToRef(matrix, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5840. */
  5841. Matrix.TransposeToRef = function (matrix, result) {
  5842. result.m[0] = matrix.m[0];
  5843. result.m[1] = matrix.m[4];
  5844. result.m[2] = matrix.m[8];
  5845. result.m[3] = matrix.m[12];
  5846. result.m[4] = matrix.m[1];
  5847. result.m[5] = matrix.m[5];
  5848. result.m[6] = matrix.m[9];
  5849. result.m[7] = matrix.m[13];
  5850. result.m[8] = matrix.m[2];
  5851. result.m[9] = matrix.m[6];
  5852. result.m[10] = matrix.m[10];
  5853. result.m[11] = matrix.m[14];
  5854. result.m[12] = matrix.m[3];
  5855. result.m[13] = matrix.m[7];
  5856. result.m[14] = matrix.m[11];
  5857. result.m[15] = matrix.m[15];
  5858. };
  5859. /**
  5860. * Returns a new Matrix as the reflection matrix across the passed plane.
  5861. */
  5862. Matrix.Reflection = function (plane) {
  5863. var matrix = new Matrix();
  5864. Matrix.ReflectionToRef(plane, matrix);
  5865. return matrix;
  5866. };
  5867. /**
  5868. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5869. */
  5870. Matrix.ReflectionToRef = function (plane, result) {
  5871. plane.normalize();
  5872. var x = plane.normal.x;
  5873. var y = plane.normal.y;
  5874. var z = plane.normal.z;
  5875. var temp = -2 * x;
  5876. var temp2 = -2 * y;
  5877. var temp3 = -2 * z;
  5878. result.m[0] = (temp * x) + 1;
  5879. result.m[1] = temp2 * x;
  5880. result.m[2] = temp3 * x;
  5881. result.m[3] = 0.0;
  5882. result.m[4] = temp * y;
  5883. result.m[5] = (temp2 * y) + 1;
  5884. result.m[6] = temp3 * y;
  5885. result.m[7] = 0.0;
  5886. result.m[8] = temp * z;
  5887. result.m[9] = temp2 * z;
  5888. result.m[10] = (temp3 * z) + 1;
  5889. result.m[11] = 0.0;
  5890. result.m[12] = temp * plane.d;
  5891. result.m[13] = temp2 * plane.d;
  5892. result.m[14] = temp3 * plane.d;
  5893. result.m[15] = 1.0;
  5894. result._markAsUpdated();
  5895. };
  5896. /**
  5897. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5898. */
  5899. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5900. result.m[0] = xaxis.x;
  5901. result.m[1] = xaxis.y;
  5902. result.m[2] = xaxis.z;
  5903. result.m[3] = 0.0;
  5904. result.m[4] = yaxis.x;
  5905. result.m[5] = yaxis.y;
  5906. result.m[6] = yaxis.z;
  5907. result.m[7] = 0.0;
  5908. result.m[8] = zaxis.x;
  5909. result.m[9] = zaxis.y;
  5910. result.m[10] = zaxis.z;
  5911. result.m[11] = 0.0;
  5912. result.m[12] = 0.0;
  5913. result.m[13] = 0.0;
  5914. result.m[14] = 0.0;
  5915. result.m[15] = 1.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5920. */
  5921. Matrix.FromQuaternionToRef = function (quat, result) {
  5922. var xx = quat.x * quat.x;
  5923. var yy = quat.y * quat.y;
  5924. var zz = quat.z * quat.z;
  5925. var xy = quat.x * quat.y;
  5926. var zw = quat.z * quat.w;
  5927. var zx = quat.z * quat.x;
  5928. var yw = quat.y * quat.w;
  5929. var yz = quat.y * quat.z;
  5930. var xw = quat.x * quat.w;
  5931. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5932. result.m[1] = 2.0 * (xy + zw);
  5933. result.m[2] = 2.0 * (zx - yw);
  5934. result.m[3] = 0.0;
  5935. result.m[4] = 2.0 * (xy - zw);
  5936. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5937. result.m[6] = 2.0 * (yz + xw);
  5938. result.m[7] = 0.0;
  5939. result.m[8] = 2.0 * (zx + yw);
  5940. result.m[9] = 2.0 * (yz - xw);
  5941. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5942. result.m[11] = 0.0;
  5943. result.m[12] = 0.0;
  5944. result.m[13] = 0.0;
  5945. result.m[14] = 0.0;
  5946. result.m[15] = 1.0;
  5947. result._markAsUpdated();
  5948. };
  5949. Matrix._tempQuaternion = new Quaternion();
  5950. Matrix._xAxis = Vector3.Zero();
  5951. Matrix._yAxis = Vector3.Zero();
  5952. Matrix._zAxis = Vector3.Zero();
  5953. Matrix._updateFlagSeed = 0;
  5954. Matrix._identityReadOnly = Matrix.Identity();
  5955. return Matrix;
  5956. }());
  5957. BABYLON.Matrix = Matrix;
  5958. var Plane = /** @class */ (function () {
  5959. /**
  5960. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5961. */
  5962. function Plane(a, b, c, d) {
  5963. this.normal = new Vector3(a, b, c);
  5964. this.d = d;
  5965. }
  5966. /**
  5967. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5968. */
  5969. Plane.prototype.asArray = function () {
  5970. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5971. };
  5972. // Methods
  5973. /**
  5974. * Returns a new plane copied from the current Plane.
  5975. */
  5976. Plane.prototype.clone = function () {
  5977. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5978. };
  5979. /**
  5980. * Returns the string "Plane".
  5981. */
  5982. Plane.prototype.getClassName = function () {
  5983. return "Plane";
  5984. };
  5985. /**
  5986. * Returns the Plane hash code.
  5987. */
  5988. Plane.prototype.getHashCode = function () {
  5989. var hash = this.normal.getHashCode();
  5990. hash = (hash * 397) ^ (this.d || 0);
  5991. return hash;
  5992. };
  5993. /**
  5994. * Normalize the current Plane in place.
  5995. * Returns the updated Plane.
  5996. */
  5997. Plane.prototype.normalize = function () {
  5998. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5999. var magnitude = 0.0;
  6000. if (norm !== 0) {
  6001. magnitude = 1.0 / norm;
  6002. }
  6003. this.normal.x *= magnitude;
  6004. this.normal.y *= magnitude;
  6005. this.normal.z *= magnitude;
  6006. this.d *= magnitude;
  6007. return this;
  6008. };
  6009. /**
  6010. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6011. */
  6012. Plane.prototype.transform = function (transformation) {
  6013. var transposedMatrix = Matrix.Transpose(transformation);
  6014. var x = this.normal.x;
  6015. var y = this.normal.y;
  6016. var z = this.normal.z;
  6017. var d = this.d;
  6018. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6019. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6020. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6021. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6022. return new Plane(normalX, normalY, normalZ, finalD);
  6023. };
  6024. /**
  6025. * Returns the dot product (float) of the point coordinates and the plane normal.
  6026. */
  6027. Plane.prototype.dotCoordinate = function (point) {
  6028. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6029. };
  6030. /**
  6031. * Updates the current Plane from the plane defined by the three passed points.
  6032. * Returns the updated Plane.
  6033. */
  6034. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6035. var x1 = point2.x - point1.x;
  6036. var y1 = point2.y - point1.y;
  6037. var z1 = point2.z - point1.z;
  6038. var x2 = point3.x - point1.x;
  6039. var y2 = point3.y - point1.y;
  6040. var z2 = point3.z - point1.z;
  6041. var yz = (y1 * z2) - (z1 * y2);
  6042. var xz = (z1 * x2) - (x1 * z2);
  6043. var xy = (x1 * y2) - (y1 * x2);
  6044. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6045. var invPyth;
  6046. if (pyth !== 0) {
  6047. invPyth = 1.0 / pyth;
  6048. }
  6049. else {
  6050. invPyth = 0.0;
  6051. }
  6052. this.normal.x = yz * invPyth;
  6053. this.normal.y = xz * invPyth;
  6054. this.normal.z = xy * invPyth;
  6055. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6056. return this;
  6057. };
  6058. /**
  6059. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6060. */
  6061. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6062. var dot = Vector3.Dot(this.normal, direction);
  6063. return (dot <= epsilon);
  6064. };
  6065. /**
  6066. * Returns the signed distance (float) from the passed point to the Plane.
  6067. */
  6068. Plane.prototype.signedDistanceTo = function (point) {
  6069. return Vector3.Dot(point, this.normal) + this.d;
  6070. };
  6071. // Statics
  6072. /**
  6073. * Returns a new Plane from the passed array.
  6074. */
  6075. Plane.FromArray = function (array) {
  6076. return new Plane(array[0], array[1], array[2], array[3]);
  6077. };
  6078. /**
  6079. * Returns a new Plane defined by the three passed points.
  6080. */
  6081. Plane.FromPoints = function (point1, point2, point3) {
  6082. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6083. result.copyFromPoints(point1, point2, point3);
  6084. return result;
  6085. };
  6086. /**
  6087. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6088. * Note : the vector "normal" is updated because normalized.
  6089. */
  6090. Plane.FromPositionAndNormal = function (origin, normal) {
  6091. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6092. normal.normalize();
  6093. result.normal = normal;
  6094. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6095. return result;
  6096. };
  6097. /**
  6098. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6099. */
  6100. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6101. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6102. return Vector3.Dot(point, normal) + d;
  6103. };
  6104. return Plane;
  6105. }());
  6106. BABYLON.Plane = Plane;
  6107. var Viewport = /** @class */ (function () {
  6108. /**
  6109. * Creates a Viewport object located at (x, y) and sized (width, height).
  6110. */
  6111. function Viewport(x, y, width, height) {
  6112. this.x = x;
  6113. this.y = y;
  6114. this.width = width;
  6115. this.height = height;
  6116. }
  6117. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6118. if (renderWidthOrEngine.getRenderWidth) {
  6119. var engine = renderWidthOrEngine;
  6120. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6121. }
  6122. var renderWidth = renderWidthOrEngine;
  6123. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6124. };
  6125. /**
  6126. * Returns a new Viewport copied from the current one.
  6127. */
  6128. Viewport.prototype.clone = function () {
  6129. return new Viewport(this.x, this.y, this.width, this.height);
  6130. };
  6131. return Viewport;
  6132. }());
  6133. BABYLON.Viewport = Viewport;
  6134. var Frustum = /** @class */ (function () {
  6135. function Frustum() {
  6136. }
  6137. /**
  6138. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6139. */
  6140. Frustum.GetPlanes = function (transform) {
  6141. var frustumPlanes = [];
  6142. for (var index = 0; index < 6; index++) {
  6143. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6144. }
  6145. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6146. return frustumPlanes;
  6147. };
  6148. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6149. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6150. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6151. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6152. frustumPlane.d = transform.m[15] + transform.m[14];
  6153. frustumPlane.normalize();
  6154. };
  6155. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6156. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6157. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6158. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6159. frustumPlane.d = transform.m[15] - transform.m[14];
  6160. frustumPlane.normalize();
  6161. };
  6162. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6163. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6164. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6165. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6166. frustumPlane.d = transform.m[15] + transform.m[12];
  6167. frustumPlane.normalize();
  6168. };
  6169. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6170. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6171. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6172. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6173. frustumPlane.d = transform.m[15] - transform.m[12];
  6174. frustumPlane.normalize();
  6175. };
  6176. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6177. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6178. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6179. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6180. frustumPlane.d = transform.m[15] - transform.m[13];
  6181. frustumPlane.normalize();
  6182. };
  6183. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6184. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6185. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6186. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6187. frustumPlane.d = transform.m[15] + transform.m[13];
  6188. frustumPlane.normalize();
  6189. };
  6190. /**
  6191. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6192. */
  6193. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6194. // Near
  6195. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6196. // Far
  6197. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6198. // Left
  6199. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6200. // Right
  6201. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6202. // Top
  6203. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6204. // Bottom
  6205. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6206. };
  6207. return Frustum;
  6208. }());
  6209. BABYLON.Frustum = Frustum;
  6210. var Space;
  6211. (function (Space) {
  6212. Space[Space["LOCAL"] = 0] = "LOCAL";
  6213. Space[Space["WORLD"] = 1] = "WORLD";
  6214. Space[Space["BONE"] = 2] = "BONE";
  6215. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6216. var Axis = /** @class */ (function () {
  6217. function Axis() {
  6218. }
  6219. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6220. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6222. return Axis;
  6223. }());
  6224. BABYLON.Axis = Axis;
  6225. ;
  6226. var BezierCurve = /** @class */ (function () {
  6227. function BezierCurve() {
  6228. }
  6229. /**
  6230. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6231. */
  6232. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6233. // Extract X (which is equal to time here)
  6234. var f0 = 1 - 3 * x2 + 3 * x1;
  6235. var f1 = 3 * x2 - 6 * x1;
  6236. var f2 = 3 * x1;
  6237. var refinedT = t;
  6238. for (var i = 0; i < 5; i++) {
  6239. var refinedT2 = refinedT * refinedT;
  6240. var refinedT3 = refinedT2 * refinedT;
  6241. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6242. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6243. refinedT -= (x - t) * slope;
  6244. refinedT = Math.min(1, Math.max(0, refinedT));
  6245. }
  6246. // Resolve cubic bezier for the given x
  6247. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6248. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6249. Math.pow(refinedT, 3);
  6250. };
  6251. return BezierCurve;
  6252. }());
  6253. BABYLON.BezierCurve = BezierCurve;
  6254. var Orientation;
  6255. (function (Orientation) {
  6256. Orientation[Orientation["CW"] = 0] = "CW";
  6257. Orientation[Orientation["CCW"] = 1] = "CCW";
  6258. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6259. var Angle = /** @class */ (function () {
  6260. /**
  6261. * Creates an Angle object of "radians" radians (float).
  6262. */
  6263. function Angle(radians) {
  6264. var _this = this;
  6265. /**
  6266. * Returns the Angle value in degrees (float).
  6267. */
  6268. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6269. /**
  6270. * Returns the Angle value in radians (float).
  6271. */
  6272. this.radians = function () { return _this._radians; };
  6273. this._radians = radians;
  6274. if (this._radians < 0.0)
  6275. this._radians += (2.0 * Math.PI);
  6276. }
  6277. /**
  6278. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6279. */
  6280. Angle.BetweenTwoPoints = function (a, b) {
  6281. var delta = b.subtract(a);
  6282. var theta = Math.atan2(delta.y, delta.x);
  6283. return new Angle(theta);
  6284. };
  6285. /**
  6286. * Returns a new Angle object from the passed float in radians.
  6287. */
  6288. Angle.FromRadians = function (radians) {
  6289. return new Angle(radians);
  6290. };
  6291. /**
  6292. * Returns a new Angle object from the passed float in degrees.
  6293. */
  6294. Angle.FromDegrees = function (degrees) {
  6295. return new Angle(degrees * Math.PI / 180.0);
  6296. };
  6297. return Angle;
  6298. }());
  6299. BABYLON.Angle = Angle;
  6300. var Arc2 = /** @class */ (function () {
  6301. /**
  6302. * Creates an Arc object from the three passed points : start, middle and end.
  6303. */
  6304. function Arc2(startPoint, midPoint, endPoint) {
  6305. this.startPoint = startPoint;
  6306. this.midPoint = midPoint;
  6307. this.endPoint = endPoint;
  6308. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6309. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6310. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6311. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6312. 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);
  6313. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6314. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6315. var a1 = this.startAngle.degrees();
  6316. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6317. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6318. // angles correction
  6319. if (a2 - a1 > +180.0)
  6320. a2 -= 360.0;
  6321. if (a2 - a1 < -180.0)
  6322. a2 += 360.0;
  6323. if (a3 - a2 > +180.0)
  6324. a3 -= 360.0;
  6325. if (a3 - a2 < -180.0)
  6326. a3 += 360.0;
  6327. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6328. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6329. }
  6330. return Arc2;
  6331. }());
  6332. BABYLON.Arc2 = Arc2;
  6333. var Path2 = /** @class */ (function () {
  6334. /**
  6335. * Creates a Path2 object from the starting 2D coordinates x and y.
  6336. */
  6337. function Path2(x, y) {
  6338. this._points = new Array();
  6339. this._length = 0.0;
  6340. this.closed = false;
  6341. this._points.push(new Vector2(x, y));
  6342. }
  6343. /**
  6344. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6345. * Returns the updated Path2.
  6346. */
  6347. Path2.prototype.addLineTo = function (x, y) {
  6348. if (this.closed) {
  6349. return this;
  6350. }
  6351. var newPoint = new Vector2(x, y);
  6352. var previousPoint = this._points[this._points.length - 1];
  6353. this._points.push(newPoint);
  6354. this._length += newPoint.subtract(previousPoint).length();
  6355. return this;
  6356. };
  6357. /**
  6358. * 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.
  6359. * Returns the updated Path2.
  6360. */
  6361. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6362. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6363. if (this.closed) {
  6364. return this;
  6365. }
  6366. var startPoint = this._points[this._points.length - 1];
  6367. var midPoint = new Vector2(midX, midY);
  6368. var endPoint = new Vector2(endX, endY);
  6369. var arc = new Arc2(startPoint, midPoint, endPoint);
  6370. var increment = arc.angle.radians() / numberOfSegments;
  6371. if (arc.orientation === Orientation.CW)
  6372. increment *= -1;
  6373. var currentAngle = arc.startAngle.radians() + increment;
  6374. for (var i = 0; i < numberOfSegments; i++) {
  6375. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6376. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6377. this.addLineTo(x, y);
  6378. currentAngle += increment;
  6379. }
  6380. return this;
  6381. };
  6382. /**
  6383. * Closes the Path2.
  6384. * Returns the Path2.
  6385. */
  6386. Path2.prototype.close = function () {
  6387. this.closed = true;
  6388. return this;
  6389. };
  6390. /**
  6391. * Returns the Path2 total length (float).
  6392. */
  6393. Path2.prototype.length = function () {
  6394. var result = this._length;
  6395. if (!this.closed) {
  6396. var lastPoint = this._points[this._points.length - 1];
  6397. var firstPoint = this._points[0];
  6398. result += (firstPoint.subtract(lastPoint).length());
  6399. }
  6400. return result;
  6401. };
  6402. /**
  6403. * Returns the Path2 internal array of points.
  6404. */
  6405. Path2.prototype.getPoints = function () {
  6406. return this._points;
  6407. };
  6408. /**
  6409. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6410. */
  6411. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6412. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6413. return Vector2.Zero();
  6414. }
  6415. var lengthPosition = normalizedLengthPosition * this.length();
  6416. var previousOffset = 0;
  6417. for (var i = 0; i < this._points.length; i++) {
  6418. var j = (i + 1) % this._points.length;
  6419. var a = this._points[i];
  6420. var b = this._points[j];
  6421. var bToA = b.subtract(a);
  6422. var nextOffset = (bToA.length() + previousOffset);
  6423. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6424. var dir = bToA.normalize();
  6425. var localOffset = lengthPosition - previousOffset;
  6426. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6427. }
  6428. previousOffset = nextOffset;
  6429. }
  6430. return Vector2.Zero();
  6431. };
  6432. /**
  6433. * Returns a new Path2 starting at the coordinates (x, y).
  6434. */
  6435. Path2.StartingAt = function (x, y) {
  6436. return new Path2(x, y);
  6437. };
  6438. return Path2;
  6439. }());
  6440. BABYLON.Path2 = Path2;
  6441. var Path3D = /** @class */ (function () {
  6442. /**
  6443. * new Path3D(path, normal, raw)
  6444. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6445. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6446. * path : an array of Vector3, the curve axis of the Path3D
  6447. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6448. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6449. */
  6450. function Path3D(path, firstNormal, raw) {
  6451. if (firstNormal === void 0) { firstNormal = null; }
  6452. this.path = path;
  6453. this._curve = new Array();
  6454. this._distances = new Array();
  6455. this._tangents = new Array();
  6456. this._normals = new Array();
  6457. this._binormals = new Array();
  6458. for (var p = 0; p < path.length; p++) {
  6459. this._curve[p] = path[p].clone(); // hard copy
  6460. }
  6461. this._raw = raw || false;
  6462. this._compute(firstNormal);
  6463. }
  6464. /**
  6465. * Returns the Path3D array of successive Vector3 designing its curve.
  6466. */
  6467. Path3D.prototype.getCurve = function () {
  6468. return this._curve;
  6469. };
  6470. /**
  6471. * Returns an array populated with tangent vectors on each Path3D curve point.
  6472. */
  6473. Path3D.prototype.getTangents = function () {
  6474. return this._tangents;
  6475. };
  6476. /**
  6477. * Returns an array populated with normal vectors on each Path3D curve point.
  6478. */
  6479. Path3D.prototype.getNormals = function () {
  6480. return this._normals;
  6481. };
  6482. /**
  6483. * Returns an array populated with binormal vectors on each Path3D curve point.
  6484. */
  6485. Path3D.prototype.getBinormals = function () {
  6486. return this._binormals;
  6487. };
  6488. /**
  6489. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6490. */
  6491. Path3D.prototype.getDistances = function () {
  6492. return this._distances;
  6493. };
  6494. /**
  6495. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6496. * Returns the same object updated.
  6497. */
  6498. Path3D.prototype.update = function (path, firstNormal) {
  6499. if (firstNormal === void 0) { firstNormal = null; }
  6500. for (var p = 0; p < path.length; p++) {
  6501. this._curve[p].x = path[p].x;
  6502. this._curve[p].y = path[p].y;
  6503. this._curve[p].z = path[p].z;
  6504. }
  6505. this._compute(firstNormal);
  6506. return this;
  6507. };
  6508. // private function compute() : computes tangents, normals and binormals
  6509. Path3D.prototype._compute = function (firstNormal) {
  6510. var l = this._curve.length;
  6511. // first and last tangents
  6512. this._tangents[0] = this._getFirstNonNullVector(0);
  6513. if (!this._raw) {
  6514. this._tangents[0].normalize();
  6515. }
  6516. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6517. if (!this._raw) {
  6518. this._tangents[l - 1].normalize();
  6519. }
  6520. // normals and binormals at first point : arbitrary vector with _normalVector()
  6521. var tg0 = this._tangents[0];
  6522. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6523. this._normals[0] = pp0;
  6524. if (!this._raw) {
  6525. this._normals[0].normalize();
  6526. }
  6527. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6528. if (!this._raw) {
  6529. this._binormals[0].normalize();
  6530. }
  6531. this._distances[0] = 0.0;
  6532. // normals and binormals : next points
  6533. var prev; // previous vector (segment)
  6534. var cur; // current vector (segment)
  6535. var curTang; // current tangent
  6536. // previous normal
  6537. var prevBinor; // previous binormal
  6538. for (var i = 1; i < l; i++) {
  6539. // tangents
  6540. prev = this._getLastNonNullVector(i);
  6541. if (i < l - 1) {
  6542. cur = this._getFirstNonNullVector(i);
  6543. this._tangents[i] = prev.add(cur);
  6544. this._tangents[i].normalize();
  6545. }
  6546. this._distances[i] = this._distances[i - 1] + prev.length();
  6547. // normals and binormals
  6548. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6549. curTang = this._tangents[i];
  6550. prevBinor = this._binormals[i - 1];
  6551. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6552. if (!this._raw) {
  6553. this._normals[i].normalize();
  6554. }
  6555. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6556. if (!this._raw) {
  6557. this._binormals[i].normalize();
  6558. }
  6559. }
  6560. };
  6561. // private function getFirstNonNullVector(index)
  6562. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6563. Path3D.prototype._getFirstNonNullVector = function (index) {
  6564. var i = 1;
  6565. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6566. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6567. i++;
  6568. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6569. }
  6570. return nNVector;
  6571. };
  6572. // private function getLastNonNullVector(index)
  6573. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6574. Path3D.prototype._getLastNonNullVector = function (index) {
  6575. var i = 1;
  6576. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6577. while (nLVector.length() === 0 && index > i + 1) {
  6578. i++;
  6579. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6580. }
  6581. return nLVector;
  6582. };
  6583. // private function normalVector(v0, vt, va) :
  6584. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6585. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6586. Path3D.prototype._normalVector = function (v0, vt, va) {
  6587. var normal0;
  6588. var tgl = vt.length();
  6589. if (tgl === 0.0) {
  6590. tgl = 1.0;
  6591. }
  6592. if (va === undefined || va === null) {
  6593. var point;
  6594. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6595. point = new Vector3(0.0, -1.0, 0.0);
  6596. }
  6597. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6598. point = new Vector3(1.0, 0.0, 0.0);
  6599. }
  6600. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6601. point = new Vector3(0.0, 0.0, 1.0);
  6602. }
  6603. else {
  6604. point = Vector3.Zero();
  6605. }
  6606. normal0 = Vector3.Cross(vt, point);
  6607. }
  6608. else {
  6609. normal0 = Vector3.Cross(vt, va);
  6610. Vector3.CrossToRef(normal0, vt, normal0);
  6611. }
  6612. normal0.normalize();
  6613. return normal0;
  6614. };
  6615. return Path3D;
  6616. }());
  6617. BABYLON.Path3D = Path3D;
  6618. var Curve3 = /** @class */ (function () {
  6619. /**
  6620. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6621. * A Curve3 is designed from a series of successive Vector3.
  6622. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6623. */
  6624. function Curve3(points) {
  6625. this._length = 0.0;
  6626. this._points = points;
  6627. this._length = this._computeLength(points);
  6628. }
  6629. /**
  6630. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6631. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6632. * @param v1 (Vector3) the control point
  6633. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6634. * @param nbPoints (integer) the wanted number of points in the curve
  6635. */
  6636. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6637. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6638. var bez = new Array();
  6639. var equation = function (t, val0, val1, val2) {
  6640. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6641. return res;
  6642. };
  6643. for (var i = 0; i <= nbPoints; i++) {
  6644. 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)));
  6645. }
  6646. return new Curve3(bez);
  6647. };
  6648. /**
  6649. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6650. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6651. * @param v1 (Vector3) the first control point
  6652. * @param v2 (Vector3) the second control point
  6653. * @param v3 (Vector3) the end point of the Cubic Bezier
  6654. * @param nbPoints (integer) the wanted number of points in the curve
  6655. */
  6656. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6657. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6658. var bez = new Array();
  6659. var equation = function (t, val0, val1, val2, val3) {
  6660. 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;
  6661. return res;
  6662. };
  6663. for (var i = 0; i <= nbPoints; i++) {
  6664. 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)));
  6665. }
  6666. return new Curve3(bez);
  6667. };
  6668. /**
  6669. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6670. * @param p1 (Vector3) the origin point of the Hermite Spline
  6671. * @param t1 (Vector3) the tangent vector at the origin point
  6672. * @param p2 (Vector3) the end point of the Hermite Spline
  6673. * @param t2 (Vector3) the tangent vector at the end point
  6674. * @param nbPoints (integer) the wanted number of points in the curve
  6675. */
  6676. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6677. var hermite = new Array();
  6678. var step = 1.0 / nbPoints;
  6679. for (var i = 0; i <= nbPoints; i++) {
  6680. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6681. }
  6682. return new Curve3(hermite);
  6683. };
  6684. /**
  6685. * Returns a Curve3 object along a CatmullRom Spline curve :
  6686. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6687. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6688. */
  6689. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6690. var totalPoints = new Array();
  6691. totalPoints.push(points[0].clone());
  6692. Array.prototype.push.apply(totalPoints, points);
  6693. totalPoints.push(points[points.length - 1].clone());
  6694. var catmullRom = new Array();
  6695. var step = 1.0 / nbPoints;
  6696. var amount = 0.0;
  6697. for (var i = 0; i < totalPoints.length - 3; i++) {
  6698. amount = 0;
  6699. for (var c = 0; c < nbPoints; c++) {
  6700. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6701. amount += step;
  6702. }
  6703. }
  6704. i--;
  6705. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6706. return new Curve3(catmullRom);
  6707. };
  6708. /**
  6709. * Returns the Curve3 stored array of successive Vector3
  6710. */
  6711. Curve3.prototype.getPoints = function () {
  6712. return this._points;
  6713. };
  6714. /**
  6715. * Returns the computed length (float) of the curve.
  6716. */
  6717. Curve3.prototype.length = function () {
  6718. return this._length;
  6719. };
  6720. /**
  6721. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6722. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6723. * curveA and curveB keep unchanged.
  6724. */
  6725. Curve3.prototype.continue = function (curve) {
  6726. var lastPoint = this._points[this._points.length - 1];
  6727. var continuedPoints = this._points.slice();
  6728. var curvePoints = curve.getPoints();
  6729. for (var i = 1; i < curvePoints.length; i++) {
  6730. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6731. }
  6732. var continuedCurve = new Curve3(continuedPoints);
  6733. return continuedCurve;
  6734. };
  6735. Curve3.prototype._computeLength = function (path) {
  6736. var l = 0;
  6737. for (var i = 1; i < path.length; i++) {
  6738. l += (path[i].subtract(path[i - 1])).length();
  6739. }
  6740. return l;
  6741. };
  6742. return Curve3;
  6743. }());
  6744. BABYLON.Curve3 = Curve3;
  6745. // Vertex formats
  6746. var PositionNormalVertex = /** @class */ (function () {
  6747. function PositionNormalVertex(position, normal) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. this.position = position;
  6751. this.normal = normal;
  6752. }
  6753. PositionNormalVertex.prototype.clone = function () {
  6754. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6755. };
  6756. return PositionNormalVertex;
  6757. }());
  6758. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6759. var PositionNormalTextureVertex = /** @class */ (function () {
  6760. function PositionNormalTextureVertex(position, normal, uv) {
  6761. if (position === void 0) { position = Vector3.Zero(); }
  6762. if (normal === void 0) { normal = Vector3.Up(); }
  6763. if (uv === void 0) { uv = Vector2.Zero(); }
  6764. this.position = position;
  6765. this.normal = normal;
  6766. this.uv = uv;
  6767. }
  6768. PositionNormalTextureVertex.prototype.clone = function () {
  6769. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6770. };
  6771. return PositionNormalTextureVertex;
  6772. }());
  6773. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6774. // Temporary pre-allocated objects for engine internal use
  6775. // usage in any internal function :
  6776. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6777. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6778. var Tmp = /** @class */ (function () {
  6779. function Tmp() {
  6780. }
  6781. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6782. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6783. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6784. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6785. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6786. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6787. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6788. Matrix.Zero(), Matrix.Zero(),
  6789. Matrix.Zero(), Matrix.Zero(),
  6790. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6791. return Tmp;
  6792. }());
  6793. BABYLON.Tmp = Tmp;
  6794. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6795. var MathTmp = /** @class */ (function () {
  6796. function MathTmp() {
  6797. }
  6798. MathTmp.Vector3 = [Vector3.Zero()];
  6799. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6800. MathTmp.Quaternion = [Quaternion.Zero()];
  6801. return MathTmp;
  6802. }());
  6803. })(BABYLON || (BABYLON = {}));
  6804. //# sourceMappingURL=babylon.math.js.map
  6805. "use strict";
  6806. var BABYLON;
  6807. (function (BABYLON) {
  6808. var Scalar = /** @class */ (function () {
  6809. function Scalar() {
  6810. }
  6811. /**
  6812. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6813. */
  6814. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6815. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6816. var num = a - b;
  6817. return -epsilon <= num && num <= epsilon;
  6818. };
  6819. /**
  6820. * Returns a string : the upper case translation of the number i to hexadecimal.
  6821. */
  6822. Scalar.ToHex = function (i) {
  6823. var str = i.toString(16);
  6824. if (i <= 15) {
  6825. return ("0" + str).toUpperCase();
  6826. }
  6827. return str.toUpperCase();
  6828. };
  6829. /**
  6830. * Returns -1 if value is negative and +1 is value is positive.
  6831. * Returns the value itself if it's equal to zero.
  6832. */
  6833. Scalar.Sign = function (value) {
  6834. value = +value; // convert to a number
  6835. if (value === 0 || isNaN(value))
  6836. return value;
  6837. return value > 0 ? 1 : -1;
  6838. };
  6839. /**
  6840. * Returns the value itself if it's between min and max.
  6841. * Returns min if the value is lower than min.
  6842. * Returns max if the value is greater than max.
  6843. */
  6844. Scalar.Clamp = function (value, min, max) {
  6845. if (min === void 0) { min = 0; }
  6846. if (max === void 0) { max = 1; }
  6847. return Math.min(max, Math.max(min, value));
  6848. };
  6849. /**
  6850. * Returns the log2 of value.
  6851. */
  6852. Scalar.Log2 = function (value) {
  6853. return Math.log(value) * Math.LOG2E;
  6854. };
  6855. /**
  6856. * Loops the value, so that it is never larger than length and never smaller than 0.
  6857. *
  6858. * This is similar to the modulo operator but it works with floating point numbers.
  6859. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6860. * With t = 5 and length = 2.5, the result would be 0.0.
  6861. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6862. */
  6863. Scalar.Repeat = function (value, length) {
  6864. return value - Math.floor(value / length) * length;
  6865. };
  6866. /**
  6867. * Normalize the value between 0.0 and 1.0 using min and max values
  6868. */
  6869. Scalar.Normalize = function (value, min, max) {
  6870. return (value - min) / (max - min);
  6871. };
  6872. /**
  6873. * Denormalize the value from 0.0 and 1.0 using min and max values
  6874. */
  6875. Scalar.Denormalize = function (normalized, min, max) {
  6876. return (normalized * (max - min) + min);
  6877. };
  6878. /**
  6879. * Calculates the shortest difference between two given angles given in degrees.
  6880. */
  6881. Scalar.DeltaAngle = function (current, target) {
  6882. var num = Scalar.Repeat(target - current, 360.0);
  6883. if (num > 180.0) {
  6884. num -= 360.0;
  6885. }
  6886. return num;
  6887. };
  6888. /**
  6889. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6890. *
  6891. * The returned value will move back and forth between 0 and length
  6892. */
  6893. Scalar.PingPong = function (tx, length) {
  6894. var t = Scalar.Repeat(tx, length * 2.0);
  6895. return length - Math.abs(t - length);
  6896. };
  6897. /**
  6898. * Interpolates between min and max with smoothing at the limits.
  6899. *
  6900. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6901. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6902. */
  6903. Scalar.SmoothStep = function (from, to, tx) {
  6904. var t = Scalar.Clamp(tx);
  6905. t = -2.0 * t * t * t + 3.0 * t * t;
  6906. return to * t + from * (1.0 - t);
  6907. };
  6908. /**
  6909. * Moves a value current towards target.
  6910. *
  6911. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6912. * Negative values of maxDelta pushes the value away from target.
  6913. */
  6914. Scalar.MoveTowards = function (current, target, maxDelta) {
  6915. var result = 0;
  6916. if (Math.abs(target - current) <= maxDelta) {
  6917. result = target;
  6918. }
  6919. else {
  6920. result = current + Scalar.Sign(target - current) * maxDelta;
  6921. }
  6922. return result;
  6923. };
  6924. /**
  6925. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6926. *
  6927. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6928. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6929. */
  6930. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6931. var num = Scalar.DeltaAngle(current, target);
  6932. var result = 0;
  6933. if (-maxDelta < num && num < maxDelta) {
  6934. result = target;
  6935. }
  6936. else {
  6937. target = current + num;
  6938. result = Scalar.MoveTowards(current, target, maxDelta);
  6939. }
  6940. return result;
  6941. };
  6942. /**
  6943. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6944. */
  6945. Scalar.Lerp = function (start, end, amount) {
  6946. return start + ((end - start) * amount);
  6947. };
  6948. /**
  6949. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6950. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6951. */
  6952. Scalar.LerpAngle = function (start, end, amount) {
  6953. var num = Scalar.Repeat(end - start, 360.0);
  6954. if (num > 180.0) {
  6955. num -= 360.0;
  6956. }
  6957. return start + num * Scalar.Clamp(amount);
  6958. };
  6959. /**
  6960. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6961. */
  6962. Scalar.InverseLerp = function (a, b, value) {
  6963. var result = 0;
  6964. if (a != b) {
  6965. result = Scalar.Clamp((value - a) / (b - a));
  6966. }
  6967. else {
  6968. result = 0.0;
  6969. }
  6970. return result;
  6971. };
  6972. /**
  6973. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6974. */
  6975. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6976. var squared = amount * amount;
  6977. var cubed = amount * squared;
  6978. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6979. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6980. var part3 = (cubed - (2.0 * squared)) + amount;
  6981. var part4 = cubed - squared;
  6982. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6983. };
  6984. /**
  6985. * Returns a random float number between and min and max values
  6986. */
  6987. Scalar.RandomRange = function (min, max) {
  6988. if (min === max)
  6989. return min;
  6990. return ((Math.random() * (max - min)) + min);
  6991. };
  6992. /**
  6993. * This function returns percentage of a number in a given range.
  6994. *
  6995. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6996. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6997. */
  6998. Scalar.RangeToPercent = function (number, min, max) {
  6999. return ((number - min) / (max - min));
  7000. };
  7001. /**
  7002. * This function returns number that corresponds to the percentage in a given range.
  7003. *
  7004. * PercentToRange(0.34,0,100) will return 34.
  7005. */
  7006. Scalar.PercentToRange = function (percent, min, max) {
  7007. return ((max - min) * percent + min);
  7008. };
  7009. /**
  7010. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7011. * @param angle The angle to normalize in radian.
  7012. * @return The converted angle.
  7013. */
  7014. Scalar.NormalizeRadians = function (angle) {
  7015. // More precise but slower version kept for reference.
  7016. // angle = angle % Tools.TwoPi;
  7017. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7018. //if (angle > Math.PI) {
  7019. // angle -= Tools.TwoPi;
  7020. //}
  7021. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7022. return angle;
  7023. };
  7024. /**
  7025. * Two pi constants convenient for computation.
  7026. */
  7027. Scalar.TwoPi = Math.PI * 2;
  7028. return Scalar;
  7029. }());
  7030. BABYLON.Scalar = Scalar;
  7031. })(BABYLON || (BABYLON = {}));
  7032. //# sourceMappingURL=babylon.math.scalar.js.map
  7033. "use strict";
  7034. //# sourceMappingURL=babylon.mixins.js.map
  7035. "use strict";
  7036. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7037. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7038. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7039. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7040. //# sourceMappingURL=babylon.webgl2.js.map
  7041. "use strict";
  7042. var BABYLON;
  7043. (function (BABYLON) {
  7044. var __decoratorInitialStore = {};
  7045. var __mergedStore = {};
  7046. var _copySource = function (creationFunction, source, instanciate) {
  7047. var destination = creationFunction();
  7048. // Tags
  7049. if (BABYLON.Tags) {
  7050. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7051. }
  7052. var classStore = getMergedStore(destination);
  7053. // Properties
  7054. for (var property in classStore) {
  7055. var propertyDescriptor = classStore[property];
  7056. var sourceProperty = source[property];
  7057. var propertyType = propertyDescriptor.type;
  7058. if (sourceProperty !== undefined && sourceProperty !== null) {
  7059. switch (propertyType) {
  7060. case 0: // Value
  7061. case 6:// Mesh reference
  7062. destination[property] = sourceProperty;
  7063. break;
  7064. case 1:// Texture
  7065. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7066. break;
  7067. case 2: // Color3
  7068. case 3: // FresnelParameters
  7069. case 4: // Vector2
  7070. case 5: // Vector3
  7071. case 7: // Color Curves
  7072. case 10:// Quaternion
  7073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7074. break;
  7075. }
  7076. }
  7077. }
  7078. return destination;
  7079. };
  7080. function getDirectStore(target) {
  7081. var classKey = target.getClassName();
  7082. if (!__decoratorInitialStore[classKey]) {
  7083. __decoratorInitialStore[classKey] = {};
  7084. }
  7085. return __decoratorInitialStore[classKey];
  7086. }
  7087. /**
  7088. * Return the list of properties flagged as serializable
  7089. * @param target: host object
  7090. */
  7091. function getMergedStore(target) {
  7092. var classKey = target.getClassName();
  7093. if (__mergedStore[classKey]) {
  7094. return __mergedStore[classKey];
  7095. }
  7096. __mergedStore[classKey] = {};
  7097. var store = __mergedStore[classKey];
  7098. var currentTarget = target;
  7099. var currentKey = classKey;
  7100. while (currentKey) {
  7101. var initialStore = __decoratorInitialStore[currentKey];
  7102. for (var property in initialStore) {
  7103. store[property] = initialStore[property];
  7104. }
  7105. var parent_1 = void 0;
  7106. var done = false;
  7107. do {
  7108. parent_1 = Object.getPrototypeOf(currentTarget);
  7109. if (!parent_1.getClassName) {
  7110. done = true;
  7111. break;
  7112. }
  7113. if (parent_1.getClassName() !== currentKey) {
  7114. break;
  7115. }
  7116. currentTarget = parent_1;
  7117. } while (parent_1);
  7118. if (done) {
  7119. break;
  7120. }
  7121. currentKey = parent_1.getClassName();
  7122. currentTarget = parent_1;
  7123. }
  7124. return store;
  7125. }
  7126. function generateSerializableMember(type, sourceName) {
  7127. return function (target, propertyKey) {
  7128. var classStore = getDirectStore(target);
  7129. if (!classStore[propertyKey]) {
  7130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7131. }
  7132. };
  7133. }
  7134. function generateExpandMember(setCallback, targetKey) {
  7135. if (targetKey === void 0) { targetKey = null; }
  7136. return function (target, propertyKey) {
  7137. var key = targetKey || ("_" + propertyKey);
  7138. Object.defineProperty(target, propertyKey, {
  7139. get: function () {
  7140. return this[key];
  7141. },
  7142. set: function (value) {
  7143. if (this[key] === value) {
  7144. return;
  7145. }
  7146. this[key] = value;
  7147. target[setCallback].apply(this);
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. };
  7153. }
  7154. function expandToProperty(callback, targetKey) {
  7155. if (targetKey === void 0) { targetKey = null; }
  7156. return generateExpandMember(callback, targetKey);
  7157. }
  7158. BABYLON.expandToProperty = expandToProperty;
  7159. function serialize(sourceName) {
  7160. return generateSerializableMember(0, sourceName); // value member
  7161. }
  7162. BABYLON.serialize = serialize;
  7163. function serializeAsTexture(sourceName) {
  7164. return generateSerializableMember(1, sourceName); // texture member
  7165. }
  7166. BABYLON.serializeAsTexture = serializeAsTexture;
  7167. function serializeAsColor3(sourceName) {
  7168. return generateSerializableMember(2, sourceName); // color3 member
  7169. }
  7170. BABYLON.serializeAsColor3 = serializeAsColor3;
  7171. function serializeAsFresnelParameters(sourceName) {
  7172. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7173. }
  7174. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7175. function serializeAsVector2(sourceName) {
  7176. return generateSerializableMember(4, sourceName); // vector2 member
  7177. }
  7178. BABYLON.serializeAsVector2 = serializeAsVector2;
  7179. function serializeAsVector3(sourceName) {
  7180. return generateSerializableMember(5, sourceName); // vector3 member
  7181. }
  7182. BABYLON.serializeAsVector3 = serializeAsVector3;
  7183. function serializeAsMeshReference(sourceName) {
  7184. return generateSerializableMember(6, sourceName); // mesh reference member
  7185. }
  7186. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7187. function serializeAsColorCurves(sourceName) {
  7188. return generateSerializableMember(7, sourceName); // color curves
  7189. }
  7190. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7191. function serializeAsColor4(sourceName) {
  7192. return generateSerializableMember(8, sourceName); // color 4
  7193. }
  7194. BABYLON.serializeAsColor4 = serializeAsColor4;
  7195. function serializeAsImageProcessingConfiguration(sourceName) {
  7196. return generateSerializableMember(9, sourceName); // image processing
  7197. }
  7198. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7199. function serializeAsQuaternion(sourceName) {
  7200. return generateSerializableMember(10, sourceName); // quaternion member
  7201. }
  7202. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7203. var SerializationHelper = /** @class */ (function () {
  7204. function SerializationHelper() {
  7205. }
  7206. SerializationHelper.Serialize = function (entity, serializationObject) {
  7207. if (!serializationObject) {
  7208. serializationObject = {};
  7209. }
  7210. // Tags
  7211. if (BABYLON.Tags) {
  7212. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7213. }
  7214. var serializedProperties = getMergedStore(entity);
  7215. // Properties
  7216. for (var property in serializedProperties) {
  7217. var propertyDescriptor = serializedProperties[property];
  7218. var targetPropertyName = propertyDescriptor.sourceName || property;
  7219. var propertyType = propertyDescriptor.type;
  7220. var sourceProperty = entity[property];
  7221. if (sourceProperty !== undefined && sourceProperty !== null) {
  7222. switch (propertyType) {
  7223. case 0:// Value
  7224. serializationObject[targetPropertyName] = sourceProperty;
  7225. break;
  7226. case 1:// Texture
  7227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7228. break;
  7229. case 2:// Color3
  7230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7231. break;
  7232. case 3:// FresnelParameters
  7233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7234. break;
  7235. case 4:// Vector2
  7236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7237. break;
  7238. case 5:// Vector3
  7239. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7240. break;
  7241. case 6:// Mesh reference
  7242. serializationObject[targetPropertyName] = sourceProperty.id;
  7243. break;
  7244. case 7:// Color Curves
  7245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7246. break;
  7247. case 8:// Color 4
  7248. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7249. break;
  7250. case 9:// Image Processing
  7251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7252. break;
  7253. }
  7254. }
  7255. }
  7256. return serializationObject;
  7257. };
  7258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7259. if (rootUrl === void 0) { rootUrl = null; }
  7260. var destination = creationFunction();
  7261. if (!rootUrl) {
  7262. rootUrl = "";
  7263. }
  7264. // Tags
  7265. if (BABYLON.Tags) {
  7266. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7267. }
  7268. var classStore = getMergedStore(destination);
  7269. // Properties
  7270. for (var property in classStore) {
  7271. var propertyDescriptor = classStore[property];
  7272. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7273. var propertyType = propertyDescriptor.type;
  7274. if (sourceProperty !== undefined && sourceProperty !== null) {
  7275. var dest = destination;
  7276. switch (propertyType) {
  7277. case 0:// Value
  7278. dest[property] = sourceProperty;
  7279. break;
  7280. case 1:// Texture
  7281. if (scene) {
  7282. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7283. }
  7284. break;
  7285. case 2:// Color3
  7286. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7287. break;
  7288. case 3:// FresnelParameters
  7289. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7290. break;
  7291. case 4:// Vector2
  7292. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7293. break;
  7294. case 5:// Vector3
  7295. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7296. break;
  7297. case 6:// Mesh reference
  7298. if (scene) {
  7299. dest[property] = scene.getLastMeshByID(sourceProperty);
  7300. }
  7301. break;
  7302. case 7:// Color Curves
  7303. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7304. break;
  7305. case 8:// Color 4
  7306. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7307. break;
  7308. case 9:// Image Processing
  7309. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7310. break;
  7311. }
  7312. }
  7313. }
  7314. return destination;
  7315. };
  7316. SerializationHelper.Clone = function (creationFunction, source) {
  7317. return _copySource(creationFunction, source, false);
  7318. };
  7319. SerializationHelper.Instanciate = function (creationFunction, source) {
  7320. return _copySource(creationFunction, source, true);
  7321. };
  7322. return SerializationHelper;
  7323. }());
  7324. BABYLON.SerializationHelper = SerializationHelper;
  7325. })(BABYLON || (BABYLON = {}));
  7326. //# sourceMappingURL=babylon.decorators.js.map
  7327. "use strict";
  7328. var BABYLON;
  7329. (function (BABYLON) {
  7330. /**
  7331. * Wrapper class for promise with external resolve and reject.
  7332. */
  7333. var Deferred = /** @class */ (function () {
  7334. /**
  7335. * Constructor for this deferred object.
  7336. */
  7337. function Deferred() {
  7338. var _this = this;
  7339. this.promise = new Promise(function (resolve, reject) {
  7340. _this._resolve = resolve;
  7341. _this._reject = reject;
  7342. });
  7343. }
  7344. Object.defineProperty(Deferred.prototype, "resolve", {
  7345. /**
  7346. * The resolve method of the promise associated with this deferred object.
  7347. */
  7348. get: function () {
  7349. return this._resolve;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Deferred.prototype, "reject", {
  7355. /**
  7356. * The reject method of the promise associated with this deferred object.
  7357. */
  7358. get: function () {
  7359. return this._reject;
  7360. },
  7361. enumerable: true,
  7362. configurable: true
  7363. });
  7364. return Deferred;
  7365. }());
  7366. BABYLON.Deferred = Deferred;
  7367. })(BABYLON || (BABYLON = {}));
  7368. //# sourceMappingURL=babylon.deferred.js.map
  7369. "use strict";
  7370. var BABYLON;
  7371. (function (BABYLON) {
  7372. /**
  7373. * A class serves as a medium between the observable and its observers
  7374. */
  7375. var EventState = /** @class */ (function () {
  7376. /**
  7377. * Create a new EventState
  7378. * @param mask defines the mask associated with this state
  7379. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7380. * @param target defines the original target of the state
  7381. * @param currentTarget defines the current target of the state
  7382. */
  7383. function EventState(mask, skipNextObservers, target, currentTarget) {
  7384. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7385. this.initalize(mask, skipNextObservers, target, currentTarget);
  7386. }
  7387. /**
  7388. * Initialize the current event state
  7389. * @param mask defines the mask associated with this state
  7390. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7391. * @param target defines the original target of the state
  7392. * @param currentTarget defines the current target of the state
  7393. * @returns the current event state
  7394. */
  7395. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7396. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7397. this.mask = mask;
  7398. this.skipNextObservers = skipNextObservers;
  7399. this.target = target;
  7400. this.currentTarget = currentTarget;
  7401. return this;
  7402. };
  7403. return EventState;
  7404. }());
  7405. BABYLON.EventState = EventState;
  7406. /**
  7407. * Represent an Observer registered to a given Observable object.
  7408. */
  7409. var Observer = /** @class */ (function () {
  7410. /**
  7411. * Creates a new observer
  7412. * @param callback defines the callback to call when the observer is notified
  7413. * @param mask defines the mask of the observer (used to filter notifications)
  7414. * @param scope defines the current scope used to restore the JS context
  7415. */
  7416. function Observer(
  7417. /**
  7418. * Defines the callback to call when the observer is notified
  7419. */
  7420. callback,
  7421. /**
  7422. * Defines the mask of the observer (used to filter notifications)
  7423. */
  7424. mask,
  7425. /**
  7426. * Defines the current scope used to restore the JS context
  7427. */
  7428. scope) {
  7429. if (scope === void 0) { scope = null; }
  7430. this.callback = callback;
  7431. this.mask = mask;
  7432. this.scope = scope;
  7433. /** @ignore */
  7434. this._willBeUnregistered = false;
  7435. /**
  7436. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7437. */
  7438. this.unregisterOnNextCall = false;
  7439. }
  7440. return Observer;
  7441. }());
  7442. BABYLON.Observer = Observer;
  7443. /**
  7444. * Represent a list of observers registered to multiple Observables object.
  7445. */
  7446. var MultiObserver = /** @class */ (function () {
  7447. function MultiObserver() {
  7448. }
  7449. /**
  7450. * Release associated resources
  7451. */
  7452. MultiObserver.prototype.dispose = function () {
  7453. if (this._observers && this._observables) {
  7454. for (var index = 0; index < this._observers.length; index++) {
  7455. this._observables[index].remove(this._observers[index]);
  7456. }
  7457. }
  7458. this._observers = null;
  7459. this._observables = null;
  7460. };
  7461. /**
  7462. * Raise a callback when one of the observable will notify
  7463. * @param observables defines a list of observables to watch
  7464. * @param callback defines the callback to call on notification
  7465. * @param mask defines the mask used to filter notifications
  7466. * @param scope defines the current scope used to restore the JS context
  7467. * @returns the new MultiObserver
  7468. */
  7469. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7470. if (mask === void 0) { mask = -1; }
  7471. if (scope === void 0) { scope = null; }
  7472. var result = new MultiObserver();
  7473. result._observers = new Array();
  7474. result._observables = observables;
  7475. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7476. var observable = observables_1[_i];
  7477. var observer = observable.add(callback, mask, false, scope);
  7478. if (observer) {
  7479. result._observers.push(observer);
  7480. }
  7481. }
  7482. return result;
  7483. };
  7484. return MultiObserver;
  7485. }());
  7486. BABYLON.MultiObserver = MultiObserver;
  7487. /**
  7488. * The Observable class is a simple implementation of the Observable pattern.
  7489. *
  7490. * 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.
  7491. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7492. * 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).
  7493. * 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.
  7494. */
  7495. var Observable = /** @class */ (function () {
  7496. /**
  7497. * Creates a new observable
  7498. * @param onObserverAdded defines a callback to call when a new observer is added
  7499. */
  7500. function Observable(onObserverAdded) {
  7501. this._observers = new Array();
  7502. this._eventState = new EventState(0);
  7503. if (onObserverAdded) {
  7504. this._onObserverAdded = onObserverAdded;
  7505. }
  7506. }
  7507. /**
  7508. * Create a new Observer with the specified callback
  7509. * @param callback the callback that will be executed for that Observer
  7510. * @param mask the mask used to filter observers
  7511. * @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.
  7512. * @param scope optional scope for the callback to be called from
  7513. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7514. * @returns the new observer created for the callback
  7515. */
  7516. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7517. if (mask === void 0) { mask = -1; }
  7518. if (insertFirst === void 0) { insertFirst = false; }
  7519. if (scope === void 0) { scope = null; }
  7520. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7521. if (!callback) {
  7522. return null;
  7523. }
  7524. var observer = new Observer(callback, mask, scope);
  7525. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7526. if (insertFirst) {
  7527. this._observers.unshift(observer);
  7528. }
  7529. else {
  7530. this._observers.push(observer);
  7531. }
  7532. if (this._onObserverAdded) {
  7533. this._onObserverAdded(observer);
  7534. }
  7535. return observer;
  7536. };
  7537. /**
  7538. * Remove an Observer from the Observable object
  7539. * @param observer the instance of the Observer to remove
  7540. * @returns false if it doesn't belong to this Observable
  7541. */
  7542. Observable.prototype.remove = function (observer) {
  7543. if (!observer) {
  7544. return false;
  7545. }
  7546. var index = this._observers.indexOf(observer);
  7547. if (index !== -1) {
  7548. this._observers.splice(index, 1);
  7549. return true;
  7550. }
  7551. return false;
  7552. };
  7553. /**
  7554. * Remove a callback from the Observable object
  7555. * @param callback the callback to remove
  7556. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7557. * @returns false if it doesn't belong to this Observable
  7558. */
  7559. Observable.prototype.removeCallback = function (callback, scope) {
  7560. for (var index = 0; index < this._observers.length; index++) {
  7561. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7562. this._observers.splice(index, 1);
  7563. return true;
  7564. }
  7565. }
  7566. return false;
  7567. };
  7568. Observable.prototype._deferUnregister = function (observer) {
  7569. var _this = this;
  7570. observer.unregisterOnNextCall = false;
  7571. observer._willBeUnregistered = true;
  7572. BABYLON.Tools.SetImmediate(function () {
  7573. _this.remove(observer);
  7574. });
  7575. };
  7576. /**
  7577. * Notify all Observers by calling their respective callback with the given data
  7578. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7579. * @param eventData defines the data to send to all observers
  7580. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7581. * @param target defines the original target of the state
  7582. * @param currentTarget defines the current target of the state
  7583. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7584. */
  7585. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7586. if (mask === void 0) { mask = -1; }
  7587. if (!this._observers.length) {
  7588. return true;
  7589. }
  7590. var state = this._eventState;
  7591. state.mask = mask;
  7592. state.target = target;
  7593. state.currentTarget = currentTarget;
  7594. state.skipNextObservers = false;
  7595. state.lastReturnValue = eventData;
  7596. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7597. var obs = _a[_i];
  7598. if (obs._willBeUnregistered) {
  7599. continue;
  7600. }
  7601. if (obs.mask & mask) {
  7602. if (obs.scope) {
  7603. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7604. }
  7605. else {
  7606. state.lastReturnValue = obs.callback(eventData, state);
  7607. }
  7608. if (obs.unregisterOnNextCall) {
  7609. this._deferUnregister(obs);
  7610. }
  7611. }
  7612. if (state.skipNextObservers) {
  7613. return false;
  7614. }
  7615. }
  7616. return true;
  7617. };
  7618. /**
  7619. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7620. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7621. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7622. * and it is crucial that all callbacks will be executed.
  7623. * The order of the callbacks is kept, callbacks are not executed parallel.
  7624. *
  7625. * @param eventData The data to be sent to each callback
  7626. * @param mask is used to filter observers defaults to -1
  7627. * @param target defines the callback target (see EventState)
  7628. * @param currentTarget defines he current object in the bubbling phase
  7629. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7630. */
  7631. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7632. var _this = this;
  7633. if (mask === void 0) { mask = -1; }
  7634. // create an empty promise
  7635. var p = Promise.resolve(eventData);
  7636. // no observers? return this promise.
  7637. if (!this._observers.length) {
  7638. return p;
  7639. }
  7640. var state = this._eventState;
  7641. state.mask = mask;
  7642. state.target = target;
  7643. state.currentTarget = currentTarget;
  7644. state.skipNextObservers = false;
  7645. // execute one callback after another (not using Promise.all, the order is important)
  7646. this._observers.forEach(function (obs) {
  7647. if (state.skipNextObservers) {
  7648. return;
  7649. }
  7650. if (obs._willBeUnregistered) {
  7651. return;
  7652. }
  7653. if (obs.mask & mask) {
  7654. if (obs.scope) {
  7655. p = p.then(function (lastReturnedValue) {
  7656. state.lastReturnValue = lastReturnedValue;
  7657. return obs.callback.apply(obs.scope, [eventData, state]);
  7658. });
  7659. }
  7660. else {
  7661. p = p.then(function (lastReturnedValue) {
  7662. state.lastReturnValue = lastReturnedValue;
  7663. return obs.callback(eventData, state);
  7664. });
  7665. }
  7666. if (obs.unregisterOnNextCall) {
  7667. _this._deferUnregister(obs);
  7668. }
  7669. }
  7670. });
  7671. // return the eventData
  7672. return p.then(function () { return eventData; });
  7673. };
  7674. /**
  7675. * Notify a specific observer
  7676. * @param observer defines the observer to notify
  7677. * @param eventData defines the data to be sent to each callback
  7678. * @param mask is used to filter observers defaults to -1
  7679. */
  7680. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7681. if (mask === void 0) { mask = -1; }
  7682. var state = this._eventState;
  7683. state.mask = mask;
  7684. state.skipNextObservers = false;
  7685. observer.callback(eventData, state);
  7686. };
  7687. /**
  7688. * Gets a boolean indicating if the observable has at least one observer
  7689. * @returns true is the Observable has at least one Observer registered
  7690. */
  7691. Observable.prototype.hasObservers = function () {
  7692. return this._observers.length > 0;
  7693. };
  7694. /**
  7695. * Clear the list of observers
  7696. */
  7697. Observable.prototype.clear = function () {
  7698. this._observers = new Array();
  7699. this._onObserverAdded = null;
  7700. };
  7701. /**
  7702. * Clone the current observable
  7703. * @returns a new observable
  7704. */
  7705. Observable.prototype.clone = function () {
  7706. var result = new Observable();
  7707. result._observers = this._observers.slice(0);
  7708. return result;
  7709. };
  7710. /**
  7711. * Does this observable handles observer registered with a given mask
  7712. * @param mask defines the mask to be tested
  7713. * @return whether or not one observer registered with the given mask is handeled
  7714. **/
  7715. Observable.prototype.hasSpecificMask = function (mask) {
  7716. if (mask === void 0) { mask = -1; }
  7717. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7718. var obs = _a[_i];
  7719. if (obs.mask & mask || obs.mask === mask) {
  7720. return true;
  7721. }
  7722. }
  7723. return false;
  7724. };
  7725. return Observable;
  7726. }());
  7727. BABYLON.Observable = Observable;
  7728. })(BABYLON || (BABYLON = {}));
  7729. //# sourceMappingURL=babylon.observable.js.map
  7730. "use strict";
  7731. var BABYLON;
  7732. (function (BABYLON) {
  7733. var SmartArray = /** @class */ (function () {
  7734. function SmartArray(capacity) {
  7735. this.length = 0;
  7736. this.data = new Array(capacity);
  7737. this._id = SmartArray._GlobalId++;
  7738. }
  7739. SmartArray.prototype.push = function (value) {
  7740. this.data[this.length++] = value;
  7741. if (this.length > this.data.length) {
  7742. this.data.length *= 2;
  7743. }
  7744. };
  7745. SmartArray.prototype.forEach = function (func) {
  7746. for (var index = 0; index < this.length; index++) {
  7747. func(this.data[index]);
  7748. }
  7749. };
  7750. SmartArray.prototype.sort = function (compareFn) {
  7751. this.data.sort(compareFn);
  7752. };
  7753. SmartArray.prototype.reset = function () {
  7754. this.length = 0;
  7755. };
  7756. SmartArray.prototype.dispose = function () {
  7757. this.reset();
  7758. if (this.data) {
  7759. this.data.length = 0;
  7760. this.data = [];
  7761. }
  7762. };
  7763. SmartArray.prototype.concat = function (array) {
  7764. if (array.length === 0) {
  7765. return;
  7766. }
  7767. if (this.length + array.length > this.data.length) {
  7768. this.data.length = (this.length + array.length) * 2;
  7769. }
  7770. for (var index = 0; index < array.length; index++) {
  7771. this.data[this.length++] = (array.data || array)[index];
  7772. }
  7773. };
  7774. SmartArray.prototype.indexOf = function (value) {
  7775. var position = this.data.indexOf(value);
  7776. if (position >= this.length) {
  7777. return -1;
  7778. }
  7779. return position;
  7780. };
  7781. SmartArray.prototype.contains = function (value) {
  7782. return this.data.indexOf(value) !== -1;
  7783. };
  7784. // Statics
  7785. SmartArray._GlobalId = 0;
  7786. return SmartArray;
  7787. }());
  7788. BABYLON.SmartArray = SmartArray;
  7789. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7790. __extends(SmartArrayNoDuplicate, _super);
  7791. function SmartArrayNoDuplicate() {
  7792. var _this = _super !== null && _super.apply(this, arguments) || this;
  7793. _this._duplicateId = 0;
  7794. return _this;
  7795. }
  7796. SmartArrayNoDuplicate.prototype.push = function (value) {
  7797. _super.prototype.push.call(this, value);
  7798. if (!value.__smartArrayFlags) {
  7799. value.__smartArrayFlags = {};
  7800. }
  7801. value.__smartArrayFlags[this._id] = this._duplicateId;
  7802. };
  7803. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7804. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7805. return false;
  7806. }
  7807. this.push(value);
  7808. return true;
  7809. };
  7810. SmartArrayNoDuplicate.prototype.reset = function () {
  7811. _super.prototype.reset.call(this);
  7812. this._duplicateId++;
  7813. };
  7814. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7815. if (array.length === 0) {
  7816. return;
  7817. }
  7818. if (this.length + array.length > this.data.length) {
  7819. this.data.length = (this.length + array.length) * 2;
  7820. }
  7821. for (var index = 0; index < array.length; index++) {
  7822. var item = (array.data || array)[index];
  7823. this.pushNoDuplicate(item);
  7824. }
  7825. };
  7826. return SmartArrayNoDuplicate;
  7827. }(SmartArray));
  7828. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7829. })(BABYLON || (BABYLON = {}));
  7830. //# sourceMappingURL=babylon.smartArray.js.map
  7831. "use strict";
  7832. var BABYLON;
  7833. (function (BABYLON) {
  7834. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7835. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7836. var LoadFileError = /** @class */ (function (_super) {
  7837. __extends(LoadFileError, _super);
  7838. function LoadFileError(message, request) {
  7839. var _this = _super.call(this, message) || this;
  7840. _this.request = request;
  7841. _this.name = "LoadFileError";
  7842. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7843. return _this;
  7844. }
  7845. // Polyfill for Object.setPrototypeOf if necessary.
  7846. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7847. return LoadFileError;
  7848. }(Error));
  7849. BABYLON.LoadFileError = LoadFileError;
  7850. var RetryStrategy = /** @class */ (function () {
  7851. function RetryStrategy() {
  7852. }
  7853. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7854. if (maxRetries === void 0) { maxRetries = 3; }
  7855. if (baseInterval === void 0) { baseInterval = 500; }
  7856. return function (url, request, retryIndex) {
  7857. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7858. return -1;
  7859. }
  7860. return Math.pow(2, retryIndex) * baseInterval;
  7861. };
  7862. };
  7863. return RetryStrategy;
  7864. }());
  7865. BABYLON.RetryStrategy = RetryStrategy;
  7866. // Screenshots
  7867. var screenshotCanvas;
  7868. var cloneValue = function (source, destinationObject) {
  7869. if (!source)
  7870. return null;
  7871. if (source instanceof BABYLON.Mesh) {
  7872. return null;
  7873. }
  7874. if (source instanceof BABYLON.SubMesh) {
  7875. return source.clone(destinationObject);
  7876. }
  7877. else if (source.clone) {
  7878. return source.clone();
  7879. }
  7880. return null;
  7881. };
  7882. var Tools = /** @class */ (function () {
  7883. function Tools() {
  7884. }
  7885. /**
  7886. * Interpolates between a and b via alpha
  7887. * @param a The lower value (returned when alpha = 0)
  7888. * @param b The upper value (returned when alpha = 1)
  7889. * @param alpha The interpolation-factor
  7890. * @return The mixed value
  7891. */
  7892. Tools.Mix = function (a, b, alpha) {
  7893. return a * (1 - alpha) + b * alpha;
  7894. };
  7895. Tools.Instantiate = function (className) {
  7896. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7897. return Tools.RegisteredExternalClasses[className];
  7898. }
  7899. var arr = className.split(".");
  7900. var fn = (window || this);
  7901. for (var i = 0, len = arr.length; i < len; i++) {
  7902. fn = fn[arr[i]];
  7903. }
  7904. if (typeof fn !== "function") {
  7905. return null;
  7906. }
  7907. return fn;
  7908. };
  7909. /**
  7910. * Provides a slice function that will work even on IE
  7911. * @param data defines the array to slice
  7912. * @returns the new sliced array
  7913. */
  7914. Tools.Slice = function (data) {
  7915. if (data.slice) {
  7916. return data.slice();
  7917. }
  7918. return Array.prototype.slice.call(data);
  7919. };
  7920. Tools.SetImmediate = function (action) {
  7921. if (window.setImmediate) {
  7922. window.setImmediate(action);
  7923. }
  7924. else {
  7925. setTimeout(action, 1);
  7926. }
  7927. };
  7928. Tools.IsExponentOfTwo = function (value) {
  7929. var count = 1;
  7930. do {
  7931. count *= 2;
  7932. } while (count < value);
  7933. return count === value;
  7934. };
  7935. /**
  7936. * Find the next highest power of two.
  7937. * @param x Number to start search from.
  7938. * @return Next highest power of two.
  7939. */
  7940. Tools.CeilingPOT = function (x) {
  7941. x--;
  7942. x |= x >> 1;
  7943. x |= x >> 2;
  7944. x |= x >> 4;
  7945. x |= x >> 8;
  7946. x |= x >> 16;
  7947. x++;
  7948. return x;
  7949. };
  7950. /**
  7951. * Find the next lowest power of two.
  7952. * @param x Number to start search from.
  7953. * @return Next lowest power of two.
  7954. */
  7955. Tools.FloorPOT = function (x) {
  7956. x = x | (x >> 1);
  7957. x = x | (x >> 2);
  7958. x = x | (x >> 4);
  7959. x = x | (x >> 8);
  7960. x = x | (x >> 16);
  7961. return x - (x >> 1);
  7962. };
  7963. /**
  7964. * Find the nearest power of two.
  7965. * @param x Number to start search from.
  7966. * @return Next nearest power of two.
  7967. */
  7968. Tools.NearestPOT = function (x) {
  7969. var c = Tools.CeilingPOT(x);
  7970. var f = Tools.FloorPOT(x);
  7971. return (c - x) > (x - f) ? f : c;
  7972. };
  7973. Tools.GetExponentOfTwo = function (value, max, mode) {
  7974. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7975. var pot;
  7976. switch (mode) {
  7977. case BABYLON.Engine.SCALEMODE_FLOOR:
  7978. pot = Tools.FloorPOT(value);
  7979. break;
  7980. case BABYLON.Engine.SCALEMODE_NEAREST:
  7981. pot = Tools.NearestPOT(value);
  7982. break;
  7983. case BABYLON.Engine.SCALEMODE_CEILING:
  7984. default:
  7985. pot = Tools.CeilingPOT(value);
  7986. break;
  7987. }
  7988. return Math.min(pot, max);
  7989. };
  7990. Tools.GetFilename = function (path) {
  7991. var index = path.lastIndexOf("/");
  7992. if (index < 0)
  7993. return path;
  7994. return path.substring(index + 1);
  7995. };
  7996. /**
  7997. * Extracts the "folder" part of a path (everything before the filename).
  7998. * @param uri The URI to extract the info from
  7999. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8000. * @returns The "folder" part of the path
  8001. */
  8002. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8003. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8004. var index = uri.lastIndexOf("/");
  8005. if (index < 0) {
  8006. if (returnUnchangedIfNoSlash) {
  8007. return uri;
  8008. }
  8009. return "";
  8010. }
  8011. return uri.substring(0, index + 1);
  8012. };
  8013. Tools.GetDOMTextContent = function (element) {
  8014. var result = "";
  8015. var child = element.firstChild;
  8016. while (child) {
  8017. if (child.nodeType === 3) {
  8018. result += child.textContent;
  8019. }
  8020. child = child.nextSibling;
  8021. }
  8022. return result;
  8023. };
  8024. Tools.ToDegrees = function (angle) {
  8025. return angle * 180 / Math.PI;
  8026. };
  8027. Tools.ToRadians = function (angle) {
  8028. return angle * Math.PI / 180;
  8029. };
  8030. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8031. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8032. var output = "";
  8033. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8034. var i = 0;
  8035. var bytes = new Uint8Array(buffer);
  8036. while (i < bytes.length) {
  8037. chr1 = bytes[i++];
  8038. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8039. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8040. enc1 = chr1 >> 2;
  8041. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8042. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8043. enc4 = chr3 & 63;
  8044. if (isNaN(chr2)) {
  8045. enc3 = enc4 = 64;
  8046. }
  8047. else if (isNaN(chr3)) {
  8048. enc4 = 64;
  8049. }
  8050. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8051. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8052. }
  8053. return "data:image/png;base64," + output;
  8054. };
  8055. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8056. if (bias === void 0) { bias = null; }
  8057. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8058. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8059. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8060. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8061. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8062. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8063. }
  8064. if (bias) {
  8065. minimum.x -= minimum.x * bias.x + bias.y;
  8066. minimum.y -= minimum.y * bias.x + bias.y;
  8067. minimum.z -= minimum.z * bias.x + bias.y;
  8068. maximum.x += maximum.x * bias.x + bias.y;
  8069. maximum.y += maximum.y * bias.x + bias.y;
  8070. maximum.z += maximum.z * bias.x + bias.y;
  8071. }
  8072. return {
  8073. minimum: minimum,
  8074. maximum: maximum
  8075. };
  8076. };
  8077. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8078. if (bias === void 0) { bias = null; }
  8079. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8080. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8081. if (!stride) {
  8082. stride = 3;
  8083. }
  8084. for (var index = start; index < start + count; index++) {
  8085. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8086. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8087. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8088. }
  8089. if (bias) {
  8090. minimum.x -= minimum.x * bias.x + bias.y;
  8091. minimum.y -= minimum.y * bias.x + bias.y;
  8092. minimum.z -= minimum.z * bias.x + bias.y;
  8093. maximum.x += maximum.x * bias.x + bias.y;
  8094. maximum.y += maximum.y * bias.x + bias.y;
  8095. maximum.z += maximum.z * bias.x + bias.y;
  8096. }
  8097. return {
  8098. minimum: minimum,
  8099. maximum: maximum
  8100. };
  8101. };
  8102. Tools.Vector2ArrayFeeder = function (array) {
  8103. return function (index) {
  8104. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8105. var length = isFloatArray ? array.length / 2 : array.length;
  8106. if (index >= length) {
  8107. return null;
  8108. }
  8109. if (isFloatArray) {
  8110. var fa = array;
  8111. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8112. }
  8113. var a = array;
  8114. return a[index];
  8115. };
  8116. };
  8117. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8118. if (bias === void 0) { bias = null; }
  8119. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8120. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8121. var i = 0;
  8122. var cur = feeder(i++);
  8123. while (cur) {
  8124. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8125. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8126. cur = feeder(i++);
  8127. }
  8128. if (bias) {
  8129. minimum.x -= minimum.x * bias.x + bias.y;
  8130. minimum.y -= minimum.y * bias.x + bias.y;
  8131. maximum.x += maximum.x * bias.x + bias.y;
  8132. maximum.y += maximum.y * bias.x + bias.y;
  8133. }
  8134. return {
  8135. minimum: minimum,
  8136. maximum: maximum
  8137. };
  8138. };
  8139. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8140. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8141. return null;
  8142. return Array.isArray(obj) ? obj : [obj];
  8143. };
  8144. // Misc.
  8145. Tools.GetPointerPrefix = function () {
  8146. var eventPrefix = "pointer";
  8147. // Check if pointer events are supported
  8148. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8149. eventPrefix = "mouse";
  8150. }
  8151. return eventPrefix;
  8152. };
  8153. /**
  8154. * @param func - the function to be called
  8155. * @param requester - the object that will request the next frame. Falls back to window.
  8156. */
  8157. Tools.QueueNewFrame = function (func, requester) {
  8158. if (!Tools.IsWindowObjectExist()) {
  8159. return setTimeout(func, 16);
  8160. }
  8161. if (!requester) {
  8162. requester = window;
  8163. }
  8164. if (requester.requestAnimationFrame) {
  8165. return requester.requestAnimationFrame(func);
  8166. }
  8167. else if (requester.msRequestAnimationFrame) {
  8168. return requester.msRequestAnimationFrame(func);
  8169. }
  8170. else if (requester.webkitRequestAnimationFrame) {
  8171. return requester.webkitRequestAnimationFrame(func);
  8172. }
  8173. else if (requester.mozRequestAnimationFrame) {
  8174. return requester.mozRequestAnimationFrame(func);
  8175. }
  8176. else if (requester.oRequestAnimationFrame) {
  8177. return requester.oRequestAnimationFrame(func);
  8178. }
  8179. else {
  8180. return window.setTimeout(func, 16);
  8181. }
  8182. };
  8183. Tools.RequestFullscreen = function (element) {
  8184. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8185. if (!requestFunction)
  8186. return;
  8187. requestFunction.call(element);
  8188. };
  8189. Tools.ExitFullscreen = function () {
  8190. if (document.exitFullscreen) {
  8191. document.exitFullscreen();
  8192. }
  8193. else if (document.mozCancelFullScreen) {
  8194. document.mozCancelFullScreen();
  8195. }
  8196. else if (document.webkitCancelFullScreen) {
  8197. document.webkitCancelFullScreen();
  8198. }
  8199. else if (document.msCancelFullScreen) {
  8200. document.msCancelFullScreen();
  8201. }
  8202. };
  8203. Tools.SetCorsBehavior = function (url, element) {
  8204. if (url && url.indexOf("data:") === 0) {
  8205. return;
  8206. }
  8207. if (Tools.CorsBehavior) {
  8208. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8209. element.crossOrigin = Tools.CorsBehavior;
  8210. }
  8211. else {
  8212. var result = Tools.CorsBehavior(url);
  8213. if (result) {
  8214. element.crossOrigin = result;
  8215. }
  8216. }
  8217. }
  8218. };
  8219. // External files
  8220. Tools.CleanUrl = function (url) {
  8221. url = url.replace(/#/mg, "%23");
  8222. return url;
  8223. };
  8224. Tools.LoadImage = function (url, onLoad, onError, database) {
  8225. if (url instanceof ArrayBuffer) {
  8226. url = Tools.EncodeArrayBufferTobase64(url);
  8227. }
  8228. url = Tools.CleanUrl(url);
  8229. url = Tools.PreprocessUrl(url);
  8230. var img = new Image();
  8231. Tools.SetCorsBehavior(url, img);
  8232. var loadHandler = function () {
  8233. img.removeEventListener("load", loadHandler);
  8234. img.removeEventListener("error", errorHandler);
  8235. onLoad(img);
  8236. };
  8237. var errorHandler = function (err) {
  8238. img.removeEventListener("load", loadHandler);
  8239. img.removeEventListener("error", errorHandler);
  8240. Tools.Error("Error while trying to load image: " + url);
  8241. if (onError) {
  8242. onError("Error while trying to load image: " + url, err);
  8243. }
  8244. };
  8245. img.addEventListener("load", loadHandler);
  8246. img.addEventListener("error", errorHandler);
  8247. var noIndexedDB = function () {
  8248. img.src = url;
  8249. };
  8250. var loadFromIndexedDB = function () {
  8251. if (database) {
  8252. database.loadImageFromDB(url, img);
  8253. }
  8254. };
  8255. //ANY database to do!
  8256. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8257. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8258. }
  8259. else {
  8260. if (url.indexOf("file:") !== -1) {
  8261. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8262. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8263. try {
  8264. var blobURL;
  8265. try {
  8266. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8267. }
  8268. catch (ex) {
  8269. // Chrome doesn't support oneTimeOnly parameter
  8270. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8271. }
  8272. img.src = blobURL;
  8273. }
  8274. catch (e) {
  8275. img.src = "";
  8276. }
  8277. return img;
  8278. }
  8279. }
  8280. noIndexedDB();
  8281. }
  8282. return img;
  8283. };
  8284. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8285. url = Tools.CleanUrl(url);
  8286. url = Tools.PreprocessUrl(url);
  8287. // If file and file input are set
  8288. if (url.indexOf("file:") !== -1) {
  8289. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8290. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8291. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8292. }
  8293. }
  8294. var loadUrl = Tools.BaseUrl + url;
  8295. var aborted = false;
  8296. var fileRequest = {
  8297. onCompleteObservable: new BABYLON.Observable(),
  8298. abort: function () { return aborted = true; },
  8299. };
  8300. var requestFile = function () {
  8301. var request = new XMLHttpRequest();
  8302. var retryHandle = null;
  8303. fileRequest.abort = function () {
  8304. aborted = true;
  8305. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8306. request.abort();
  8307. }
  8308. if (retryHandle !== null) {
  8309. clearTimeout(retryHandle);
  8310. retryHandle = null;
  8311. }
  8312. };
  8313. var retryLoop = function (retryIndex) {
  8314. request.open('GET', loadUrl, true);
  8315. if (useArrayBuffer) {
  8316. request.responseType = "arraybuffer";
  8317. }
  8318. if (onProgress) {
  8319. request.addEventListener("progress", onProgress);
  8320. }
  8321. var onLoadEnd = function () {
  8322. request.removeEventListener("loadend", onLoadEnd);
  8323. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8324. fileRequest.onCompleteObservable.clear();
  8325. };
  8326. request.addEventListener("loadend", onLoadEnd);
  8327. var onReadyStateChange = function () {
  8328. if (aborted) {
  8329. return;
  8330. }
  8331. // In case of undefined state in some browsers.
  8332. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8333. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8334. request.removeEventListener("readystatechange", onReadyStateChange);
  8335. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8336. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8337. return;
  8338. }
  8339. var retryStrategy = Tools.DefaultRetryStrategy;
  8340. if (retryStrategy) {
  8341. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8342. if (waitTime !== -1) {
  8343. // Prevent the request from completing for retry.
  8344. request.removeEventListener("loadend", onLoadEnd);
  8345. request = new XMLHttpRequest();
  8346. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8347. return;
  8348. }
  8349. }
  8350. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8351. if (onError) {
  8352. onError(request, e);
  8353. }
  8354. else {
  8355. throw e;
  8356. }
  8357. }
  8358. };
  8359. request.addEventListener("readystatechange", onReadyStateChange);
  8360. request.send();
  8361. };
  8362. retryLoop(0);
  8363. };
  8364. // Caching all files
  8365. if (database && database.enableSceneOffline) {
  8366. var noIndexedDB_1 = function () {
  8367. if (!aborted) {
  8368. requestFile();
  8369. }
  8370. };
  8371. var loadFromIndexedDB = function () {
  8372. // TODO: database needs to support aborting and should return a IFileRequest
  8373. if (aborted) {
  8374. return;
  8375. }
  8376. if (database) {
  8377. database.loadFileFromDB(url, function (data) {
  8378. if (!aborted) {
  8379. onSuccess(data);
  8380. }
  8381. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8382. }, onProgress ? function (event) {
  8383. if (!aborted) {
  8384. onProgress(event);
  8385. }
  8386. } : undefined, noIndexedDB_1, useArrayBuffer);
  8387. }
  8388. };
  8389. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8390. }
  8391. else {
  8392. requestFile();
  8393. }
  8394. return fileRequest;
  8395. };
  8396. /**
  8397. * Load a script (identified by an url). When the url returns, the
  8398. * content of this file is added into a new script element, attached to the DOM (body element)
  8399. */
  8400. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8401. var head = document.getElementsByTagName('head')[0];
  8402. var script = document.createElement('script');
  8403. script.type = 'text/javascript';
  8404. script.src = scriptUrl;
  8405. script.onload = function () {
  8406. if (onSuccess) {
  8407. onSuccess();
  8408. }
  8409. };
  8410. script.onerror = function (e) {
  8411. if (onError) {
  8412. onError("Unable to load script", e);
  8413. }
  8414. };
  8415. head.appendChild(script);
  8416. };
  8417. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8418. var reader = new FileReader();
  8419. var request = {
  8420. onCompleteObservable: new BABYLON.Observable(),
  8421. abort: function () { return reader.abort(); },
  8422. };
  8423. reader.onloadend = function (e) {
  8424. request.onCompleteObservable.notifyObservers(request);
  8425. };
  8426. reader.onload = function (e) {
  8427. //target doesn't have result from ts 1.3
  8428. callback(e.target['result']);
  8429. };
  8430. reader.onprogress = progressCallback;
  8431. reader.readAsDataURL(fileToLoad);
  8432. return request;
  8433. };
  8434. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8435. var reader = new FileReader();
  8436. var request = {
  8437. onCompleteObservable: new BABYLON.Observable(),
  8438. abort: function () { return reader.abort(); },
  8439. };
  8440. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8441. reader.onerror = function (e) {
  8442. Tools.Log("Error while reading file: " + fileToLoad.name);
  8443. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8444. };
  8445. reader.onload = function (e) {
  8446. //target doesn't have result from ts 1.3
  8447. callback(e.target['result']);
  8448. };
  8449. if (progressCallBack) {
  8450. reader.onprogress = progressCallBack;
  8451. }
  8452. if (!useArrayBuffer) {
  8453. // Asynchronous read
  8454. reader.readAsText(fileToLoad);
  8455. }
  8456. else {
  8457. reader.readAsArrayBuffer(fileToLoad);
  8458. }
  8459. return request;
  8460. };
  8461. //returns a downloadable url to a file content.
  8462. Tools.FileAsURL = function (content) {
  8463. var fileBlob = new Blob([content]);
  8464. var url = window.URL || window.webkitURL;
  8465. var link = url.createObjectURL(fileBlob);
  8466. return link;
  8467. };
  8468. // Misc.
  8469. Tools.Format = function (value, decimals) {
  8470. if (decimals === void 0) { decimals = 2; }
  8471. return value.toFixed(decimals);
  8472. };
  8473. Tools.CheckExtends = function (v, min, max) {
  8474. if (v.x < min.x)
  8475. min.x = v.x;
  8476. if (v.y < min.y)
  8477. min.y = v.y;
  8478. if (v.z < min.z)
  8479. min.z = v.z;
  8480. if (v.x > max.x)
  8481. max.x = v.x;
  8482. if (v.y > max.y)
  8483. max.y = v.y;
  8484. if (v.z > max.z)
  8485. max.z = v.z;
  8486. };
  8487. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8488. for (var prop in source) {
  8489. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8490. continue;
  8491. }
  8492. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8493. continue;
  8494. }
  8495. var sourceValue = source[prop];
  8496. var typeOfSourceValue = typeof sourceValue;
  8497. if (typeOfSourceValue === "function") {
  8498. continue;
  8499. }
  8500. try {
  8501. if (typeOfSourceValue === "object") {
  8502. if (sourceValue instanceof Array) {
  8503. destination[prop] = [];
  8504. if (sourceValue.length > 0) {
  8505. if (typeof sourceValue[0] == "object") {
  8506. for (var index = 0; index < sourceValue.length; index++) {
  8507. var clonedValue = cloneValue(sourceValue[index], destination);
  8508. if (destination[prop].indexOf(clonedValue) === -1) {
  8509. destination[prop].push(clonedValue);
  8510. }
  8511. }
  8512. }
  8513. else {
  8514. destination[prop] = sourceValue.slice(0);
  8515. }
  8516. }
  8517. }
  8518. else {
  8519. destination[prop] = cloneValue(sourceValue, destination);
  8520. }
  8521. }
  8522. else {
  8523. destination[prop] = sourceValue;
  8524. }
  8525. }
  8526. catch (e) {
  8527. // Just ignore error (it could be because of a read-only property)
  8528. }
  8529. }
  8530. };
  8531. Tools.IsEmpty = function (obj) {
  8532. for (var i in obj) {
  8533. if (obj.hasOwnProperty(i)) {
  8534. return false;
  8535. }
  8536. }
  8537. return true;
  8538. };
  8539. Tools.RegisterTopRootEvents = function (events) {
  8540. for (var index = 0; index < events.length; index++) {
  8541. var event = events[index];
  8542. window.addEventListener(event.name, event.handler, false);
  8543. try {
  8544. if (window.parent) {
  8545. window.parent.addEventListener(event.name, event.handler, false);
  8546. }
  8547. }
  8548. catch (e) {
  8549. // Silently fails...
  8550. }
  8551. }
  8552. };
  8553. Tools.UnregisterTopRootEvents = function (events) {
  8554. for (var index = 0; index < events.length; index++) {
  8555. var event = events[index];
  8556. window.removeEventListener(event.name, event.handler);
  8557. try {
  8558. if (window.parent) {
  8559. window.parent.removeEventListener(event.name, event.handler);
  8560. }
  8561. }
  8562. catch (e) {
  8563. // Silently fails...
  8564. }
  8565. }
  8566. };
  8567. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8568. if (mimeType === void 0) { mimeType = "image/png"; }
  8569. // Read the contents of the framebuffer
  8570. var numberOfChannelsByLine = width * 4;
  8571. var halfHeight = height / 2;
  8572. //Reading datas from WebGL
  8573. var data = engine.readPixels(0, 0, width, height);
  8574. //To flip image on Y axis.
  8575. for (var i = 0; i < halfHeight; i++) {
  8576. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8577. var currentCell = j + i * numberOfChannelsByLine;
  8578. var targetLine = height - i - 1;
  8579. var targetCell = j + targetLine * numberOfChannelsByLine;
  8580. var temp = data[currentCell];
  8581. data[currentCell] = data[targetCell];
  8582. data[targetCell] = temp;
  8583. }
  8584. }
  8585. // Create a 2D canvas to store the result
  8586. if (!screenshotCanvas) {
  8587. screenshotCanvas = document.createElement('canvas');
  8588. }
  8589. screenshotCanvas.width = width;
  8590. screenshotCanvas.height = height;
  8591. var context = screenshotCanvas.getContext('2d');
  8592. if (context) {
  8593. // Copy the pixels to a 2D canvas
  8594. var imageData = context.createImageData(width, height);
  8595. var castData = (imageData.data);
  8596. castData.set(data);
  8597. context.putImageData(imageData, 0, 0);
  8598. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8599. }
  8600. };
  8601. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8602. if (mimeType === void 0) { mimeType = "image/png"; }
  8603. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8604. if (successCallback) {
  8605. successCallback(base64Image);
  8606. }
  8607. else {
  8608. // We need HTMLCanvasElement.toBlob for HD screenshots
  8609. if (!screenshotCanvas.toBlob) {
  8610. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8611. screenshotCanvas.toBlob = function (callback, type, quality) {
  8612. var _this = this;
  8613. setTimeout(function () {
  8614. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8615. for (var i = 0; i < len; i++) {
  8616. arr[i] = binStr.charCodeAt(i);
  8617. }
  8618. callback(new Blob([arr], { type: type || 'image/png' }));
  8619. });
  8620. };
  8621. }
  8622. screenshotCanvas.toBlob(function (blob) {
  8623. var url = URL.createObjectURL(blob);
  8624. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8625. if (("download" in document.createElement("a"))) {
  8626. var a = window.document.createElement("a");
  8627. a.href = url;
  8628. if (fileName) {
  8629. a.setAttribute("download", fileName);
  8630. }
  8631. else {
  8632. var date = new Date();
  8633. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8634. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8635. }
  8636. window.document.body.appendChild(a);
  8637. a.addEventListener("click", function () {
  8638. if (a.parentElement) {
  8639. a.parentElement.removeChild(a);
  8640. }
  8641. });
  8642. a.click();
  8643. }
  8644. else {
  8645. var newWindow = window.open("");
  8646. if (!newWindow)
  8647. return;
  8648. var img = newWindow.document.createElement("img");
  8649. img.onload = function () {
  8650. // no longer need to read the blob so it's revoked
  8651. URL.revokeObjectURL(url);
  8652. };
  8653. img.src = url;
  8654. newWindow.document.body.appendChild(img);
  8655. }
  8656. });
  8657. }
  8658. };
  8659. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8660. if (mimeType === void 0) { mimeType = "image/png"; }
  8661. var width;
  8662. var height;
  8663. // If a precision value is specified
  8664. if (size.precision) {
  8665. width = Math.round(engine.getRenderWidth() * size.precision);
  8666. height = Math.round(width / engine.getAspectRatio(camera));
  8667. }
  8668. else if (size.width && size.height) {
  8669. width = size.width;
  8670. height = size.height;
  8671. }
  8672. else if (size.width && !size.height) {
  8673. width = size.width;
  8674. height = Math.round(width / engine.getAspectRatio(camera));
  8675. }
  8676. else if (size.height && !size.width) {
  8677. height = size.height;
  8678. width = Math.round(height * engine.getAspectRatio(camera));
  8679. }
  8680. else if (!isNaN(size)) {
  8681. height = size;
  8682. width = size;
  8683. }
  8684. else {
  8685. Tools.Error("Invalid 'size' parameter !");
  8686. return;
  8687. }
  8688. if (!screenshotCanvas) {
  8689. screenshotCanvas = document.createElement('canvas');
  8690. }
  8691. screenshotCanvas.width = width;
  8692. screenshotCanvas.height = height;
  8693. var renderContext = screenshotCanvas.getContext("2d");
  8694. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8695. var newWidth = width;
  8696. var newHeight = newWidth / ratio;
  8697. if (newHeight > height) {
  8698. newHeight = height;
  8699. newWidth = newHeight * ratio;
  8700. }
  8701. var offsetX = Math.max(0, width - newWidth) / 2;
  8702. var offsetY = Math.max(0, height - newHeight) / 2;
  8703. var renderingCanvas = engine.getRenderingCanvas();
  8704. if (renderContext && renderingCanvas) {
  8705. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8706. }
  8707. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8708. };
  8709. /**
  8710. * Generates an image screenshot from the specified camera.
  8711. *
  8712. * @param engine The engine to use for rendering
  8713. * @param camera The camera to use for rendering
  8714. * @param size This parameter can be set to a single number or to an object with the
  8715. * following (optional) properties: precision, width, height. If a single number is passed,
  8716. * it will be used for both width and height. If an object is passed, the screenshot size
  8717. * will be derived from the parameters. The precision property is a multiplier allowing
  8718. * rendering at a higher or lower resolution.
  8719. * @param successCallback The callback receives a single parameter which contains the
  8720. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8721. * src parameter of an <img> to display it.
  8722. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8723. * Check your browser for supported MIME types.
  8724. * @param samples Texture samples (default: 1)
  8725. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8726. * @param fileName A name for for the downloaded file.
  8727. * @constructor
  8728. */
  8729. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8730. if (mimeType === void 0) { mimeType = "image/png"; }
  8731. if (samples === void 0) { samples = 1; }
  8732. if (antialiasing === void 0) { antialiasing = false; }
  8733. var width;
  8734. var height;
  8735. //If a precision value is specified
  8736. if (size.precision) {
  8737. width = Math.round(engine.getRenderWidth() * size.precision);
  8738. height = Math.round(width / engine.getAspectRatio(camera));
  8739. size = { width: width, height: height };
  8740. }
  8741. else if (size.width && size.height) {
  8742. width = size.width;
  8743. height = size.height;
  8744. }
  8745. else if (size.width && !size.height) {
  8746. width = size.width;
  8747. height = Math.round(width / engine.getAspectRatio(camera));
  8748. size = { width: width, height: height };
  8749. }
  8750. else if (size.height && !size.width) {
  8751. height = size.height;
  8752. width = Math.round(height * engine.getAspectRatio(camera));
  8753. size = { width: width, height: height };
  8754. }
  8755. else if (!isNaN(size)) {
  8756. height = size;
  8757. width = size;
  8758. }
  8759. else {
  8760. Tools.Error("Invalid 'size' parameter !");
  8761. return;
  8762. }
  8763. var scene = camera.getScene();
  8764. var previousCamera = null;
  8765. if (scene.activeCamera !== camera) {
  8766. previousCamera = scene.activeCamera;
  8767. scene.activeCamera = camera;
  8768. }
  8769. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8770. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8771. texture.renderList = null;
  8772. texture.samples = samples;
  8773. if (antialiasing) {
  8774. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8775. }
  8776. texture.onAfterRenderObservable.add(function () {
  8777. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8778. });
  8779. scene.incrementRenderId();
  8780. scene.resetCachedMaterial();
  8781. texture.render(true);
  8782. texture.dispose();
  8783. if (previousCamera) {
  8784. scene.activeCamera = previousCamera;
  8785. }
  8786. camera.getProjectionMatrix(true); // Force cache refresh;
  8787. };
  8788. // XHR response validator for local file scenario
  8789. Tools.ValidateXHRData = function (xhr, dataType) {
  8790. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8791. if (dataType === void 0) { dataType = 7; }
  8792. try {
  8793. if (dataType & 1) {
  8794. if (xhr.responseText && xhr.responseText.length > 0) {
  8795. return true;
  8796. }
  8797. else if (dataType === 1) {
  8798. return false;
  8799. }
  8800. }
  8801. if (dataType & 2) {
  8802. // Check header width and height since there is no "TGA" magic number
  8803. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8804. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8805. return true;
  8806. }
  8807. else if (dataType === 2) {
  8808. return false;
  8809. }
  8810. }
  8811. if (dataType & 4) {
  8812. // Check for the "DDS" magic number
  8813. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8814. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8815. return true;
  8816. }
  8817. else {
  8818. return false;
  8819. }
  8820. }
  8821. }
  8822. catch (e) {
  8823. // Global protection
  8824. }
  8825. return false;
  8826. };
  8827. /**
  8828. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8829. * Be aware Math.random() could cause collisions, but:
  8830. * "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"
  8831. */
  8832. Tools.RandomId = function () {
  8833. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8834. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8835. return v.toString(16);
  8836. });
  8837. };
  8838. /**
  8839. * Test if the given uri is a base64 string.
  8840. * @param uri The uri to test
  8841. * @return True if the uri is a base64 string or false otherwise.
  8842. */
  8843. Tools.IsBase64 = function (uri) {
  8844. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8845. };
  8846. /**
  8847. * Decode the given base64 uri.
  8848. * @param uri The uri to decode
  8849. * @return The decoded base64 data.
  8850. */
  8851. Tools.DecodeBase64 = function (uri) {
  8852. var decodedString = atob(uri.split(",")[1]);
  8853. var bufferLength = decodedString.length;
  8854. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8855. for (var i = 0; i < bufferLength; i++) {
  8856. bufferView[i] = decodedString.charCodeAt(i);
  8857. }
  8858. return bufferView.buffer;
  8859. };
  8860. Object.defineProperty(Tools, "NoneLogLevel", {
  8861. get: function () {
  8862. return Tools._NoneLogLevel;
  8863. },
  8864. enumerable: true,
  8865. configurable: true
  8866. });
  8867. Object.defineProperty(Tools, "MessageLogLevel", {
  8868. get: function () {
  8869. return Tools._MessageLogLevel;
  8870. },
  8871. enumerable: true,
  8872. configurable: true
  8873. });
  8874. Object.defineProperty(Tools, "WarningLogLevel", {
  8875. get: function () {
  8876. return Tools._WarningLogLevel;
  8877. },
  8878. enumerable: true,
  8879. configurable: true
  8880. });
  8881. Object.defineProperty(Tools, "ErrorLogLevel", {
  8882. get: function () {
  8883. return Tools._ErrorLogLevel;
  8884. },
  8885. enumerable: true,
  8886. configurable: true
  8887. });
  8888. Object.defineProperty(Tools, "AllLogLevel", {
  8889. get: function () {
  8890. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8891. },
  8892. enumerable: true,
  8893. configurable: true
  8894. });
  8895. Tools._AddLogEntry = function (entry) {
  8896. Tools._LogCache = entry + Tools._LogCache;
  8897. if (Tools.OnNewCacheEntry) {
  8898. Tools.OnNewCacheEntry(entry);
  8899. }
  8900. };
  8901. Tools._FormatMessage = function (message) {
  8902. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8903. var date = new Date();
  8904. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8905. };
  8906. Tools._LogDisabled = function (message) {
  8907. // nothing to do
  8908. };
  8909. Tools._LogEnabled = function (message) {
  8910. var formattedMessage = Tools._FormatMessage(message);
  8911. console.log("BJS - " + formattedMessage);
  8912. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8913. Tools._AddLogEntry(entry);
  8914. };
  8915. Tools._WarnDisabled = function (message) {
  8916. // nothing to do
  8917. };
  8918. Tools._WarnEnabled = function (message) {
  8919. var formattedMessage = Tools._FormatMessage(message);
  8920. console.warn("BJS - " + formattedMessage);
  8921. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8922. Tools._AddLogEntry(entry);
  8923. };
  8924. Tools._ErrorDisabled = function (message) {
  8925. // nothing to do
  8926. };
  8927. Tools._ErrorEnabled = function (message) {
  8928. Tools.errorsCount++;
  8929. var formattedMessage = Tools._FormatMessage(message);
  8930. console.error("BJS - " + formattedMessage);
  8931. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8932. Tools._AddLogEntry(entry);
  8933. };
  8934. Object.defineProperty(Tools, "LogCache", {
  8935. get: function () {
  8936. return Tools._LogCache;
  8937. },
  8938. enumerable: true,
  8939. configurable: true
  8940. });
  8941. Tools.ClearLogCache = function () {
  8942. Tools._LogCache = "";
  8943. Tools.errorsCount = 0;
  8944. };
  8945. Object.defineProperty(Tools, "LogLevels", {
  8946. set: function (level) {
  8947. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8948. Tools.Log = Tools._LogEnabled;
  8949. }
  8950. else {
  8951. Tools.Log = Tools._LogDisabled;
  8952. }
  8953. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8954. Tools.Warn = Tools._WarnEnabled;
  8955. }
  8956. else {
  8957. Tools.Warn = Tools._WarnDisabled;
  8958. }
  8959. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8960. Tools.Error = Tools._ErrorEnabled;
  8961. }
  8962. else {
  8963. Tools.Error = Tools._ErrorDisabled;
  8964. }
  8965. },
  8966. enumerable: true,
  8967. configurable: true
  8968. });
  8969. Tools.IsWindowObjectExist = function () {
  8970. return (typeof window) !== "undefined";
  8971. };
  8972. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8973. get: function () {
  8974. return Tools._PerformanceNoneLogLevel;
  8975. },
  8976. enumerable: true,
  8977. configurable: true
  8978. });
  8979. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8980. get: function () {
  8981. return Tools._PerformanceUserMarkLogLevel;
  8982. },
  8983. enumerable: true,
  8984. configurable: true
  8985. });
  8986. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8987. get: function () {
  8988. return Tools._PerformanceConsoleLogLevel;
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8994. set: function (level) {
  8995. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8996. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8997. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8998. return;
  8999. }
  9000. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9001. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9002. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9003. return;
  9004. }
  9005. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9006. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9007. },
  9008. enumerable: true,
  9009. configurable: true
  9010. });
  9011. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9012. };
  9013. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9014. };
  9015. Tools._StartUserMark = function (counterName, condition) {
  9016. if (condition === void 0) { condition = true; }
  9017. if (!Tools._performance) {
  9018. if (!Tools.IsWindowObjectExist()) {
  9019. return;
  9020. }
  9021. Tools._performance = window.performance;
  9022. }
  9023. if (!condition || !Tools._performance.mark) {
  9024. return;
  9025. }
  9026. Tools._performance.mark(counterName + "-Begin");
  9027. };
  9028. Tools._EndUserMark = function (counterName, condition) {
  9029. if (condition === void 0) { condition = true; }
  9030. if (!condition || !Tools._performance.mark) {
  9031. return;
  9032. }
  9033. Tools._performance.mark(counterName + "-End");
  9034. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9035. };
  9036. Tools._StartPerformanceConsole = function (counterName, condition) {
  9037. if (condition === void 0) { condition = true; }
  9038. if (!condition) {
  9039. return;
  9040. }
  9041. Tools._StartUserMark(counterName, condition);
  9042. if (console.time) {
  9043. console.time(counterName);
  9044. }
  9045. };
  9046. Tools._EndPerformanceConsole = function (counterName, condition) {
  9047. if (condition === void 0) { condition = true; }
  9048. if (!condition) {
  9049. return;
  9050. }
  9051. Tools._EndUserMark(counterName, condition);
  9052. if (console.time) {
  9053. console.timeEnd(counterName);
  9054. }
  9055. };
  9056. Object.defineProperty(Tools, "Now", {
  9057. get: function () {
  9058. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9059. return window.performance.now();
  9060. }
  9061. return new Date().getTime();
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. /**
  9067. * This method will return the name of the class used to create the instance of the given object.
  9068. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9069. * @param object the object to get the class name from
  9070. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9071. */
  9072. Tools.GetClassName = function (object, isType) {
  9073. if (isType === void 0) { isType = false; }
  9074. var name = null;
  9075. if (!isType && object.getClassName) {
  9076. name = object.getClassName();
  9077. }
  9078. else {
  9079. if (object instanceof Object) {
  9080. var classObj = isType ? object : Object.getPrototypeOf(object);
  9081. name = classObj.constructor["__bjsclassName__"];
  9082. }
  9083. if (!name) {
  9084. name = typeof object;
  9085. }
  9086. }
  9087. return name;
  9088. };
  9089. Tools.First = function (array, predicate) {
  9090. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9091. var el = array_1[_i];
  9092. if (predicate(el)) {
  9093. return el;
  9094. }
  9095. }
  9096. return null;
  9097. };
  9098. /**
  9099. * This method will return the name of the full name of the class, including its owning module (if any).
  9100. * 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).
  9101. * @param object the object to get the class name from
  9102. * @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.
  9103. */
  9104. Tools.getFullClassName = function (object, isType) {
  9105. if (isType === void 0) { isType = false; }
  9106. var className = null;
  9107. var moduleName = null;
  9108. if (!isType && object.getClassName) {
  9109. className = object.getClassName();
  9110. }
  9111. else {
  9112. if (object instanceof Object) {
  9113. var classObj = isType ? object : Object.getPrototypeOf(object);
  9114. className = classObj.constructor["__bjsclassName__"];
  9115. moduleName = classObj.constructor["__bjsmoduleName__"];
  9116. }
  9117. if (!className) {
  9118. className = typeof object;
  9119. }
  9120. }
  9121. if (!className) {
  9122. return null;
  9123. }
  9124. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9125. };
  9126. /**
  9127. * 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.
  9128. * @param array
  9129. */
  9130. Tools.arrayOrStringFeeder = function (array) {
  9131. return function (index) {
  9132. if (index >= array.length) {
  9133. return null;
  9134. }
  9135. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9136. if (val && val.getHashCode) {
  9137. val = val.getHashCode();
  9138. }
  9139. if (typeof val === "string") {
  9140. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9141. }
  9142. return val;
  9143. };
  9144. };
  9145. /**
  9146. * Compute the hashCode of a stream of number
  9147. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9148. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9149. * @return the hash code computed
  9150. */
  9151. Tools.hashCodeFromStream = function (feeder) {
  9152. // Based from here: http://stackoverflow.com/a/7616484/802124
  9153. var hash = 0;
  9154. var index = 0;
  9155. var chr = feeder(index++);
  9156. while (chr != null) {
  9157. hash = ((hash << 5) - hash) + chr;
  9158. hash |= 0; // Convert to 32bit integer
  9159. chr = feeder(index++);
  9160. }
  9161. return hash;
  9162. };
  9163. /**
  9164. * Returns a promise that resolves after the given amount of time.
  9165. * @param delay Number of milliseconds to delay
  9166. * @returns Promise that resolves after the given amount of time
  9167. */
  9168. Tools.DelayAsync = function (delay) {
  9169. return new Promise(function (resolve) {
  9170. setTimeout(function () {
  9171. resolve();
  9172. }, delay);
  9173. });
  9174. };
  9175. Tools.BaseUrl = "";
  9176. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9177. /**
  9178. * Default behaviour for cors in the application.
  9179. * It can be a string if the expected behavior is identical in the entire app.
  9180. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9181. */
  9182. Tools.CorsBehavior = "anonymous";
  9183. Tools.UseFallbackTexture = true;
  9184. /**
  9185. * Use this object to register external classes like custom textures or material
  9186. * to allow the laoders to instantiate them
  9187. */
  9188. Tools.RegisteredExternalClasses = {};
  9189. // Used in case of a texture loading problem
  9190. 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";
  9191. Tools.PreprocessUrl = function (url) {
  9192. return url;
  9193. };
  9194. // Logs
  9195. Tools._NoneLogLevel = 0;
  9196. Tools._MessageLogLevel = 1;
  9197. Tools._WarningLogLevel = 2;
  9198. Tools._ErrorLogLevel = 4;
  9199. Tools._LogCache = "";
  9200. Tools.errorsCount = 0;
  9201. Tools.Log = Tools._LogEnabled;
  9202. Tools.Warn = Tools._WarnEnabled;
  9203. Tools.Error = Tools._ErrorEnabled;
  9204. // Performances
  9205. Tools._PerformanceNoneLogLevel = 0;
  9206. Tools._PerformanceUserMarkLogLevel = 1;
  9207. Tools._PerformanceConsoleLogLevel = 2;
  9208. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9209. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9210. return Tools;
  9211. }());
  9212. BABYLON.Tools = Tools;
  9213. /**
  9214. * This class is used to track a performance counter which is number based.
  9215. * The user has access to many properties which give statistics of different nature
  9216. *
  9217. * The implementer can track two kinds of Performance Counter: time and count
  9218. * 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.
  9219. * 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.
  9220. */
  9221. var PerfCounter = /** @class */ (function () {
  9222. function PerfCounter() {
  9223. this._startMonitoringTime = 0;
  9224. this._min = 0;
  9225. this._max = 0;
  9226. this._average = 0;
  9227. this._lastSecAverage = 0;
  9228. this._current = 0;
  9229. this._totalValueCount = 0;
  9230. this._totalAccumulated = 0;
  9231. this._lastSecAccumulated = 0;
  9232. this._lastSecTime = 0;
  9233. this._lastSecValueCount = 0;
  9234. }
  9235. Object.defineProperty(PerfCounter.prototype, "min", {
  9236. /**
  9237. * Returns the smallest value ever
  9238. */
  9239. get: function () {
  9240. return this._min;
  9241. },
  9242. enumerable: true,
  9243. configurable: true
  9244. });
  9245. Object.defineProperty(PerfCounter.prototype, "max", {
  9246. /**
  9247. * Returns the biggest value ever
  9248. */
  9249. get: function () {
  9250. return this._max;
  9251. },
  9252. enumerable: true,
  9253. configurable: true
  9254. });
  9255. Object.defineProperty(PerfCounter.prototype, "average", {
  9256. /**
  9257. * Returns the average value since the performance counter is running
  9258. */
  9259. get: function () {
  9260. return this._average;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9266. /**
  9267. * Returns the average value of the last second the counter was monitored
  9268. */
  9269. get: function () {
  9270. return this._lastSecAverage;
  9271. },
  9272. enumerable: true,
  9273. configurable: true
  9274. });
  9275. Object.defineProperty(PerfCounter.prototype, "current", {
  9276. /**
  9277. * Returns the current value
  9278. */
  9279. get: function () {
  9280. return this._current;
  9281. },
  9282. enumerable: true,
  9283. configurable: true
  9284. });
  9285. Object.defineProperty(PerfCounter.prototype, "total", {
  9286. get: function () {
  9287. return this._totalAccumulated;
  9288. },
  9289. enumerable: true,
  9290. configurable: true
  9291. });
  9292. Object.defineProperty(PerfCounter.prototype, "count", {
  9293. get: function () {
  9294. return this._totalValueCount;
  9295. },
  9296. enumerable: true,
  9297. configurable: true
  9298. });
  9299. /**
  9300. * Call this method to start monitoring a new frame.
  9301. * 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.
  9302. */
  9303. PerfCounter.prototype.fetchNewFrame = function () {
  9304. this._totalValueCount++;
  9305. this._current = 0;
  9306. this._lastSecValueCount++;
  9307. };
  9308. /**
  9309. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9310. * @param newCount the count value to add to the monitored count
  9311. * @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.
  9312. */
  9313. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9314. if (!PerfCounter.Enabled) {
  9315. return;
  9316. }
  9317. this._current += newCount;
  9318. if (fetchResult) {
  9319. this._fetchResult();
  9320. }
  9321. };
  9322. /**
  9323. * Start monitoring this performance counter
  9324. */
  9325. PerfCounter.prototype.beginMonitoring = function () {
  9326. if (!PerfCounter.Enabled) {
  9327. return;
  9328. }
  9329. this._startMonitoringTime = Tools.Now;
  9330. };
  9331. /**
  9332. * Compute the time lapsed since the previous beginMonitoring() call.
  9333. * @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
  9334. */
  9335. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9336. if (newFrame === void 0) { newFrame = true; }
  9337. if (!PerfCounter.Enabled) {
  9338. return;
  9339. }
  9340. if (newFrame) {
  9341. this.fetchNewFrame();
  9342. }
  9343. var currentTime = Tools.Now;
  9344. this._current = currentTime - this._startMonitoringTime;
  9345. if (newFrame) {
  9346. this._fetchResult();
  9347. }
  9348. };
  9349. PerfCounter.prototype._fetchResult = function () {
  9350. this._totalAccumulated += this._current;
  9351. this._lastSecAccumulated += this._current;
  9352. // Min/Max update
  9353. this._min = Math.min(this._min, this._current);
  9354. this._max = Math.max(this._max, this._current);
  9355. this._average = this._totalAccumulated / this._totalValueCount;
  9356. // Reset last sec?
  9357. var now = Tools.Now;
  9358. if ((now - this._lastSecTime) > 1000) {
  9359. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9360. this._lastSecTime = now;
  9361. this._lastSecAccumulated = 0;
  9362. this._lastSecValueCount = 0;
  9363. }
  9364. };
  9365. PerfCounter.Enabled = true;
  9366. return PerfCounter;
  9367. }());
  9368. BABYLON.PerfCounter = PerfCounter;
  9369. /**
  9370. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9371. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9372. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9373. * @param name The name of the class, case should be preserved
  9374. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9375. */
  9376. function className(name, module) {
  9377. return function (target) {
  9378. target["__bjsclassName__"] = name;
  9379. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9380. };
  9381. }
  9382. BABYLON.className = className;
  9383. /**
  9384. * An implementation of a loop for asynchronous functions.
  9385. */
  9386. var AsyncLoop = /** @class */ (function () {
  9387. /**
  9388. * Constroctor.
  9389. * @param iterations the number of iterations.
  9390. * @param _fn the function to run each iteration
  9391. * @param _successCallback the callback that will be called upon succesful execution
  9392. * @param offset starting offset.
  9393. */
  9394. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9395. if (offset === void 0) { offset = 0; }
  9396. this.iterations = iterations;
  9397. this._fn = _fn;
  9398. this._successCallback = _successCallback;
  9399. this.index = offset - 1;
  9400. this._done = false;
  9401. }
  9402. /**
  9403. * Execute the next iteration. Must be called after the last iteration was finished.
  9404. */
  9405. AsyncLoop.prototype.executeNext = function () {
  9406. if (!this._done) {
  9407. if (this.index + 1 < this.iterations) {
  9408. ++this.index;
  9409. this._fn(this);
  9410. }
  9411. else {
  9412. this.breakLoop();
  9413. }
  9414. }
  9415. };
  9416. /**
  9417. * Break the loop and run the success callback.
  9418. */
  9419. AsyncLoop.prototype.breakLoop = function () {
  9420. this._done = true;
  9421. this._successCallback();
  9422. };
  9423. /**
  9424. * Helper function
  9425. */
  9426. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9427. if (offset === void 0) { offset = 0; }
  9428. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9429. loop.executeNext();
  9430. return loop;
  9431. };
  9432. /**
  9433. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9434. * @param iterations total number of iterations
  9435. * @param syncedIterations number of synchronous iterations in each async iteration.
  9436. * @param fn the function to call each iteration.
  9437. * @param callback a success call back that will be called when iterating stops.
  9438. * @param breakFunction a break condition (optional)
  9439. * @param timeout timeout settings for the setTimeout function. default - 0.
  9440. * @constructor
  9441. */
  9442. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9443. if (timeout === void 0) { timeout = 0; }
  9444. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9445. if (breakFunction && breakFunction())
  9446. loop.breakLoop();
  9447. else {
  9448. setTimeout(function () {
  9449. for (var i = 0; i < syncedIterations; ++i) {
  9450. var iteration = (loop.index * syncedIterations) + i;
  9451. if (iteration >= iterations)
  9452. break;
  9453. fn(iteration);
  9454. if (breakFunction && breakFunction()) {
  9455. loop.breakLoop();
  9456. break;
  9457. }
  9458. }
  9459. loop.executeNext();
  9460. }, timeout);
  9461. }
  9462. }, callback);
  9463. };
  9464. return AsyncLoop;
  9465. }());
  9466. BABYLON.AsyncLoop = AsyncLoop;
  9467. })(BABYLON || (BABYLON = {}));
  9468. //# sourceMappingURL=babylon.tools.js.map
  9469. "use strict";
  9470. var BABYLON;
  9471. (function (BABYLON) {
  9472. var PromiseStates;
  9473. (function (PromiseStates) {
  9474. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9475. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9476. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9477. })(PromiseStates || (PromiseStates = {}));
  9478. var FulFillmentAgregator = /** @class */ (function () {
  9479. function FulFillmentAgregator() {
  9480. this.count = 0;
  9481. this.target = 0;
  9482. this.results = [];
  9483. }
  9484. return FulFillmentAgregator;
  9485. }());
  9486. var InternalPromise = /** @class */ (function () {
  9487. function InternalPromise(resolver) {
  9488. var _this = this;
  9489. this._state = PromiseStates.Pending;
  9490. this._children = new Array();
  9491. this._rejectWasConsumed = false;
  9492. if (!resolver) {
  9493. return;
  9494. }
  9495. try {
  9496. resolver(function (value) {
  9497. _this._resolve(value);
  9498. }, function (reason) {
  9499. _this._reject(reason);
  9500. });
  9501. }
  9502. catch (e) {
  9503. this._reject(e);
  9504. }
  9505. }
  9506. InternalPromise.prototype.catch = function (onRejected) {
  9507. return this.then(undefined, onRejected);
  9508. };
  9509. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9510. var _this = this;
  9511. var newPromise = new InternalPromise();
  9512. newPromise._onFulfilled = onFulfilled;
  9513. newPromise._onRejected = onRejected;
  9514. // Composition
  9515. this._children.push(newPromise);
  9516. if (this._state !== PromiseStates.Pending) {
  9517. BABYLON.Tools.SetImmediate(function () {
  9518. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9519. var returnedValue = newPromise._resolve(_this._result);
  9520. if (returnedValue !== undefined && returnedValue !== null) {
  9521. if (returnedValue._state !== undefined) {
  9522. var returnedPromise = returnedValue;
  9523. newPromise._children.push(returnedPromise);
  9524. newPromise = returnedPromise;
  9525. }
  9526. else {
  9527. newPromise._result = returnedValue;
  9528. }
  9529. }
  9530. }
  9531. else {
  9532. newPromise._reject(_this._reason);
  9533. }
  9534. });
  9535. }
  9536. return newPromise;
  9537. };
  9538. InternalPromise.prototype._moveChildren = function (children) {
  9539. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9540. if (this._state === PromiseStates.Fulfilled) {
  9541. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9542. var child = _b[_i];
  9543. child._resolve(this._result);
  9544. }
  9545. }
  9546. else if (this._state === PromiseStates.Rejected) {
  9547. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9548. var child = _d[_c];
  9549. child._reject(this._reason);
  9550. }
  9551. }
  9552. var _a;
  9553. };
  9554. InternalPromise.prototype._resolve = function (value) {
  9555. try {
  9556. this._state = PromiseStates.Fulfilled;
  9557. var returnedValue = null;
  9558. if (this._onFulfilled) {
  9559. returnedValue = this._onFulfilled(value);
  9560. }
  9561. if (returnedValue !== undefined && returnedValue !== null) {
  9562. if (returnedValue._state !== undefined) {
  9563. // Transmit children
  9564. var returnedPromise = returnedValue;
  9565. returnedPromise._moveChildren(this._children);
  9566. value = returnedPromise._result;
  9567. }
  9568. else {
  9569. value = returnedValue;
  9570. }
  9571. }
  9572. this._result = value;
  9573. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9574. var child = _a[_i];
  9575. child._resolve(value);
  9576. }
  9577. this._children.length = 0;
  9578. delete this._onFulfilled;
  9579. delete this._onRejected;
  9580. }
  9581. catch (e) {
  9582. this._reject(e, true);
  9583. }
  9584. };
  9585. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9586. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9587. this._state = PromiseStates.Rejected;
  9588. this._reason = reason;
  9589. if (this._onRejected && !onLocalThrow) {
  9590. try {
  9591. this._onRejected(reason);
  9592. this._rejectWasConsumed = true;
  9593. }
  9594. catch (e) {
  9595. reason = e;
  9596. }
  9597. }
  9598. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9599. var child = _a[_i];
  9600. if (this._rejectWasConsumed) {
  9601. child._resolve(null);
  9602. }
  9603. else {
  9604. child._reject(reason);
  9605. }
  9606. }
  9607. this._children.length = 0;
  9608. delete this._onFulfilled;
  9609. delete this._onRejected;
  9610. };
  9611. InternalPromise.resolve = function (value) {
  9612. var newPromise = new InternalPromise();
  9613. newPromise._resolve(value);
  9614. return newPromise;
  9615. };
  9616. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9617. promise.then(function (value) {
  9618. agregator.results[index] = value;
  9619. agregator.count++;
  9620. if (agregator.count === agregator.target) {
  9621. agregator.rootPromise._resolve(agregator.results);
  9622. }
  9623. return null;
  9624. }, function (reason) {
  9625. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9626. agregator.rootPromise._reject(reason);
  9627. }
  9628. });
  9629. };
  9630. InternalPromise.all = function (promises) {
  9631. var newPromise = new InternalPromise();
  9632. var agregator = new FulFillmentAgregator();
  9633. agregator.target = promises.length;
  9634. agregator.rootPromise = newPromise;
  9635. if (promises.length) {
  9636. for (var index = 0; index < promises.length; index++) {
  9637. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9638. }
  9639. }
  9640. else {
  9641. newPromise._resolve([]);
  9642. }
  9643. return newPromise;
  9644. };
  9645. InternalPromise.race = function (promises) {
  9646. var newPromise = new InternalPromise();
  9647. if (promises.length) {
  9648. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9649. var promise = promises_1[_i];
  9650. promise.then(function (value) {
  9651. if (newPromise) {
  9652. newPromise._resolve(value);
  9653. newPromise = null;
  9654. }
  9655. return null;
  9656. }, function (reason) {
  9657. if (newPromise) {
  9658. newPromise._reject(reason);
  9659. newPromise = null;
  9660. }
  9661. });
  9662. }
  9663. }
  9664. return newPromise;
  9665. };
  9666. return InternalPromise;
  9667. }());
  9668. /**
  9669. * Helper class that provides a small promise polyfill
  9670. */
  9671. var PromisePolyfill = /** @class */ (function () {
  9672. function PromisePolyfill() {
  9673. }
  9674. /**
  9675. * Static function used to check if the polyfill is required
  9676. * If this is the case then the function will inject the polyfill to window.Promise
  9677. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9678. */
  9679. PromisePolyfill.Apply = function (force) {
  9680. if (force === void 0) { force = false; }
  9681. if (force || typeof Promise === 'undefined') {
  9682. var root = window;
  9683. root.Promise = InternalPromise;
  9684. }
  9685. };
  9686. return PromisePolyfill;
  9687. }());
  9688. BABYLON.PromisePolyfill = PromisePolyfill;
  9689. })(BABYLON || (BABYLON = {}));
  9690. //# sourceMappingURL=babylon.promise.js.map
  9691. "use strict";
  9692. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9693. var BABYLON;
  9694. (function (BABYLON) {
  9695. /**
  9696. * Helper class to push actions to a pool of workers.
  9697. */
  9698. var WorkerPool = /** @class */ (function () {
  9699. /**
  9700. * Constructor
  9701. * @param workers Array of workers to use for actions
  9702. */
  9703. function WorkerPool(workers) {
  9704. this._pendingActions = new Array();
  9705. this._workerInfos = workers.map(function (worker) { return ({
  9706. worker: worker,
  9707. active: false
  9708. }); });
  9709. }
  9710. /**
  9711. * Terminates all workers and clears any pending actions.
  9712. */
  9713. WorkerPool.prototype.dispose = function () {
  9714. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9715. var workerInfo = _a[_i];
  9716. workerInfo.worker.terminate();
  9717. }
  9718. delete this._workerInfos;
  9719. delete this._pendingActions;
  9720. };
  9721. /**
  9722. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9723. * pended until a worker has completed its action.
  9724. * @param action The action to perform. Call onComplete when the action is complete.
  9725. */
  9726. WorkerPool.prototype.push = function (action) {
  9727. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9728. var workerInfo = _a[_i];
  9729. if (!workerInfo.active) {
  9730. this._execute(workerInfo, action);
  9731. return;
  9732. }
  9733. }
  9734. this._pendingActions.push(action);
  9735. };
  9736. WorkerPool.prototype._execute = function (workerInfo, action) {
  9737. var _this = this;
  9738. workerInfo.active = true;
  9739. action(workerInfo.worker, function () {
  9740. workerInfo.active = false;
  9741. var nextAction = _this._pendingActions.shift();
  9742. if (nextAction) {
  9743. _this._execute(workerInfo, nextAction);
  9744. }
  9745. });
  9746. };
  9747. return WorkerPool;
  9748. }());
  9749. BABYLON.WorkerPool = WorkerPool;
  9750. })(BABYLON || (BABYLON = {}));
  9751. //# sourceMappingURL=babylon.workerPool.js.map
  9752. "use strict";
  9753. var BABYLON;
  9754. (function (BABYLON) {
  9755. var _AlphaState = /** @class */ (function () {
  9756. /**
  9757. * Initializes the state.
  9758. */
  9759. function _AlphaState() {
  9760. this._isAlphaBlendDirty = false;
  9761. this._isBlendFunctionParametersDirty = false;
  9762. this._isBlendEquationParametersDirty = false;
  9763. this._isBlendConstantsDirty = false;
  9764. this._alphaBlend = false;
  9765. this._blendFunctionParameters = new Array(4);
  9766. this._blendEquationParameters = new Array(2);
  9767. this._blendConstants = new Array(4);
  9768. this.reset();
  9769. }
  9770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9771. get: function () {
  9772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9778. get: function () {
  9779. return this._alphaBlend;
  9780. },
  9781. set: function (value) {
  9782. if (this._alphaBlend === value) {
  9783. return;
  9784. }
  9785. this._alphaBlend = value;
  9786. this._isAlphaBlendDirty = true;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9792. if (this._blendConstants[0] === r &&
  9793. this._blendConstants[1] === g &&
  9794. this._blendConstants[2] === b &&
  9795. this._blendConstants[3] === a) {
  9796. return;
  9797. }
  9798. this._blendConstants[0] = r;
  9799. this._blendConstants[1] = g;
  9800. this._blendConstants[2] = b;
  9801. this._blendConstants[3] = a;
  9802. this._isBlendConstantsDirty = true;
  9803. };
  9804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9805. if (this._blendFunctionParameters[0] === value0 &&
  9806. this._blendFunctionParameters[1] === value1 &&
  9807. this._blendFunctionParameters[2] === value2 &&
  9808. this._blendFunctionParameters[3] === value3) {
  9809. return;
  9810. }
  9811. this._blendFunctionParameters[0] = value0;
  9812. this._blendFunctionParameters[1] = value1;
  9813. this._blendFunctionParameters[2] = value2;
  9814. this._blendFunctionParameters[3] = value3;
  9815. this._isBlendFunctionParametersDirty = true;
  9816. };
  9817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9818. if (this._blendEquationParameters[0] === rgb &&
  9819. this._blendEquationParameters[1] === alpha) {
  9820. return;
  9821. }
  9822. this._blendEquationParameters[0] = rgb;
  9823. this._blendEquationParameters[1] = alpha;
  9824. this._isBlendEquationParametersDirty = true;
  9825. };
  9826. _AlphaState.prototype.reset = function () {
  9827. this._alphaBlend = false;
  9828. this._blendFunctionParameters[0] = null;
  9829. this._blendFunctionParameters[1] = null;
  9830. this._blendFunctionParameters[2] = null;
  9831. this._blendFunctionParameters[3] = null;
  9832. this._blendEquationParameters[0] = null;
  9833. this._blendEquationParameters[1] = null;
  9834. this._blendConstants[0] = null;
  9835. this._blendConstants[1] = null;
  9836. this._blendConstants[2] = null;
  9837. this._blendConstants[3] = null;
  9838. this._isAlphaBlendDirty = true;
  9839. this._isBlendFunctionParametersDirty = false;
  9840. this._isBlendEquationParametersDirty = false;
  9841. this._isBlendConstantsDirty = false;
  9842. };
  9843. _AlphaState.prototype.apply = function (gl) {
  9844. if (!this.isDirty) {
  9845. return;
  9846. }
  9847. // Alpha blend
  9848. if (this._isAlphaBlendDirty) {
  9849. if (this._alphaBlend) {
  9850. gl.enable(gl.BLEND);
  9851. }
  9852. else {
  9853. gl.disable(gl.BLEND);
  9854. }
  9855. this._isAlphaBlendDirty = false;
  9856. }
  9857. // Alpha function
  9858. if (this._isBlendFunctionParametersDirty) {
  9859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9860. this._isBlendFunctionParametersDirty = false;
  9861. }
  9862. // Alpha equation
  9863. if (this._isBlendEquationParametersDirty) {
  9864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9865. this._isBlendEquationParametersDirty = false;
  9866. }
  9867. // Constants
  9868. if (this._isBlendConstantsDirty) {
  9869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9870. this._isBlendConstantsDirty = false;
  9871. }
  9872. };
  9873. return _AlphaState;
  9874. }());
  9875. BABYLON._AlphaState = _AlphaState;
  9876. })(BABYLON || (BABYLON = {}));
  9877. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9878. "use strict";
  9879. var BABYLON;
  9880. (function (BABYLON) {
  9881. var _DepthCullingState = /** @class */ (function () {
  9882. /**
  9883. * Initializes the state.
  9884. */
  9885. function _DepthCullingState() {
  9886. this._isDepthTestDirty = false;
  9887. this._isDepthMaskDirty = false;
  9888. this._isDepthFuncDirty = false;
  9889. this._isCullFaceDirty = false;
  9890. this._isCullDirty = false;
  9891. this._isZOffsetDirty = false;
  9892. this._isFrontFaceDirty = false;
  9893. this.reset();
  9894. }
  9895. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9896. get: function () {
  9897. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9898. },
  9899. enumerable: true,
  9900. configurable: true
  9901. });
  9902. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9903. get: function () {
  9904. return this._zOffset;
  9905. },
  9906. set: function (value) {
  9907. if (this._zOffset === value) {
  9908. return;
  9909. }
  9910. this._zOffset = value;
  9911. this._isZOffsetDirty = true;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9917. get: function () {
  9918. return this._cullFace;
  9919. },
  9920. set: function (value) {
  9921. if (this._cullFace === value) {
  9922. return;
  9923. }
  9924. this._cullFace = value;
  9925. this._isCullFaceDirty = true;
  9926. },
  9927. enumerable: true,
  9928. configurable: true
  9929. });
  9930. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9931. get: function () {
  9932. return this._cull;
  9933. },
  9934. set: function (value) {
  9935. if (this._cull === value) {
  9936. return;
  9937. }
  9938. this._cull = value;
  9939. this._isCullDirty = true;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9945. get: function () {
  9946. return this._depthFunc;
  9947. },
  9948. set: function (value) {
  9949. if (this._depthFunc === value) {
  9950. return;
  9951. }
  9952. this._depthFunc = value;
  9953. this._isDepthFuncDirty = true;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9959. get: function () {
  9960. return this._depthMask;
  9961. },
  9962. set: function (value) {
  9963. if (this._depthMask === value) {
  9964. return;
  9965. }
  9966. this._depthMask = value;
  9967. this._isDepthMaskDirty = true;
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9973. get: function () {
  9974. return this._depthTest;
  9975. },
  9976. set: function (value) {
  9977. if (this._depthTest === value) {
  9978. return;
  9979. }
  9980. this._depthTest = value;
  9981. this._isDepthTestDirty = true;
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9987. get: function () {
  9988. return this._frontFace;
  9989. },
  9990. set: function (value) {
  9991. if (this._frontFace === value) {
  9992. return;
  9993. }
  9994. this._frontFace = value;
  9995. this._isFrontFaceDirty = true;
  9996. },
  9997. enumerable: true,
  9998. configurable: true
  9999. });
  10000. _DepthCullingState.prototype.reset = function () {
  10001. this._depthMask = true;
  10002. this._depthTest = true;
  10003. this._depthFunc = null;
  10004. this._cullFace = null;
  10005. this._cull = null;
  10006. this._zOffset = 0;
  10007. this._frontFace = null;
  10008. this._isDepthTestDirty = true;
  10009. this._isDepthMaskDirty = true;
  10010. this._isDepthFuncDirty = false;
  10011. this._isCullFaceDirty = false;
  10012. this._isCullDirty = false;
  10013. this._isZOffsetDirty = false;
  10014. this._isFrontFaceDirty = false;
  10015. };
  10016. _DepthCullingState.prototype.apply = function (gl) {
  10017. if (!this.isDirty) {
  10018. return;
  10019. }
  10020. // Cull
  10021. if (this._isCullDirty) {
  10022. if (this.cull) {
  10023. gl.enable(gl.CULL_FACE);
  10024. }
  10025. else {
  10026. gl.disable(gl.CULL_FACE);
  10027. }
  10028. this._isCullDirty = false;
  10029. }
  10030. // Cull face
  10031. if (this._isCullFaceDirty) {
  10032. gl.cullFace(this.cullFace);
  10033. this._isCullFaceDirty = false;
  10034. }
  10035. // Depth mask
  10036. if (this._isDepthMaskDirty) {
  10037. gl.depthMask(this.depthMask);
  10038. this._isDepthMaskDirty = false;
  10039. }
  10040. // Depth test
  10041. if (this._isDepthTestDirty) {
  10042. if (this.depthTest) {
  10043. gl.enable(gl.DEPTH_TEST);
  10044. }
  10045. else {
  10046. gl.disable(gl.DEPTH_TEST);
  10047. }
  10048. this._isDepthTestDirty = false;
  10049. }
  10050. // Depth func
  10051. if (this._isDepthFuncDirty) {
  10052. gl.depthFunc(this.depthFunc);
  10053. this._isDepthFuncDirty = false;
  10054. }
  10055. // zOffset
  10056. if (this._isZOffsetDirty) {
  10057. if (this.zOffset) {
  10058. gl.enable(gl.POLYGON_OFFSET_FILL);
  10059. gl.polygonOffset(this.zOffset, 0);
  10060. }
  10061. else {
  10062. gl.disable(gl.POLYGON_OFFSET_FILL);
  10063. }
  10064. this._isZOffsetDirty = false;
  10065. }
  10066. // Front face
  10067. if (this._isFrontFaceDirty) {
  10068. gl.frontFace(this.frontFace);
  10069. this._isFrontFaceDirty = false;
  10070. }
  10071. };
  10072. return _DepthCullingState;
  10073. }());
  10074. BABYLON._DepthCullingState = _DepthCullingState;
  10075. })(BABYLON || (BABYLON = {}));
  10076. //# sourceMappingURL=babylon.depthCullingState.js.map
  10077. "use strict";
  10078. var BABYLON;
  10079. (function (BABYLON) {
  10080. var _StencilState = /** @class */ (function () {
  10081. function _StencilState() {
  10082. this._isStencilTestDirty = false;
  10083. this._isStencilMaskDirty = false;
  10084. this._isStencilFuncDirty = false;
  10085. this._isStencilOpDirty = false;
  10086. this.reset();
  10087. }
  10088. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10089. get: function () {
  10090. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10091. },
  10092. enumerable: true,
  10093. configurable: true
  10094. });
  10095. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10096. get: function () {
  10097. return this._stencilFunc;
  10098. },
  10099. set: function (value) {
  10100. if (this._stencilFunc === value) {
  10101. return;
  10102. }
  10103. this._stencilFunc = value;
  10104. this._isStencilFuncDirty = true;
  10105. },
  10106. enumerable: true,
  10107. configurable: true
  10108. });
  10109. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10110. get: function () {
  10111. return this._stencilFuncRef;
  10112. },
  10113. set: function (value) {
  10114. if (this._stencilFuncRef === value) {
  10115. return;
  10116. }
  10117. this._stencilFuncRef = value;
  10118. this._isStencilFuncDirty = true;
  10119. },
  10120. enumerable: true,
  10121. configurable: true
  10122. });
  10123. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10124. get: function () {
  10125. return this._stencilFuncMask;
  10126. },
  10127. set: function (value) {
  10128. if (this._stencilFuncMask === value) {
  10129. return;
  10130. }
  10131. this._stencilFuncMask = value;
  10132. this._isStencilFuncDirty = true;
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10138. get: function () {
  10139. return this._stencilOpStencilFail;
  10140. },
  10141. set: function (value) {
  10142. if (this._stencilOpStencilFail === value) {
  10143. return;
  10144. }
  10145. this._stencilOpStencilFail = value;
  10146. this._isStencilOpDirty = true;
  10147. },
  10148. enumerable: true,
  10149. configurable: true
  10150. });
  10151. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10152. get: function () {
  10153. return this._stencilOpDepthFail;
  10154. },
  10155. set: function (value) {
  10156. if (this._stencilOpDepthFail === value) {
  10157. return;
  10158. }
  10159. this._stencilOpDepthFail = value;
  10160. this._isStencilOpDirty = true;
  10161. },
  10162. enumerable: true,
  10163. configurable: true
  10164. });
  10165. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10166. get: function () {
  10167. return this._stencilOpStencilDepthPass;
  10168. },
  10169. set: function (value) {
  10170. if (this._stencilOpStencilDepthPass === value) {
  10171. return;
  10172. }
  10173. this._stencilOpStencilDepthPass = value;
  10174. this._isStencilOpDirty = true;
  10175. },
  10176. enumerable: true,
  10177. configurable: true
  10178. });
  10179. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10180. get: function () {
  10181. return this._stencilMask;
  10182. },
  10183. set: function (value) {
  10184. if (this._stencilMask === value) {
  10185. return;
  10186. }
  10187. this._stencilMask = value;
  10188. this._isStencilMaskDirty = true;
  10189. },
  10190. enumerable: true,
  10191. configurable: true
  10192. });
  10193. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10194. get: function () {
  10195. return this._stencilTest;
  10196. },
  10197. set: function (value) {
  10198. if (this._stencilTest === value) {
  10199. return;
  10200. }
  10201. this._stencilTest = value;
  10202. this._isStencilTestDirty = true;
  10203. },
  10204. enumerable: true,
  10205. configurable: true
  10206. });
  10207. _StencilState.prototype.reset = function () {
  10208. this._stencilTest = false;
  10209. this._stencilMask = 0xFF;
  10210. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10211. this._stencilFuncRef = 1;
  10212. this._stencilFuncMask = 0xFF;
  10213. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10214. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10215. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10216. this._isStencilTestDirty = true;
  10217. this._isStencilMaskDirty = true;
  10218. this._isStencilFuncDirty = true;
  10219. this._isStencilOpDirty = true;
  10220. };
  10221. _StencilState.prototype.apply = function (gl) {
  10222. if (!this.isDirty) {
  10223. return;
  10224. }
  10225. // Stencil test
  10226. if (this._isStencilTestDirty) {
  10227. if (this.stencilTest) {
  10228. gl.enable(gl.STENCIL_TEST);
  10229. }
  10230. else {
  10231. gl.disable(gl.STENCIL_TEST);
  10232. }
  10233. this._isStencilTestDirty = false;
  10234. }
  10235. // Stencil mask
  10236. if (this._isStencilMaskDirty) {
  10237. gl.stencilMask(this.stencilMask);
  10238. this._isStencilMaskDirty = false;
  10239. }
  10240. // Stencil func
  10241. if (this._isStencilFuncDirty) {
  10242. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10243. this._isStencilFuncDirty = false;
  10244. }
  10245. // Stencil op
  10246. if (this._isStencilOpDirty) {
  10247. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10248. this._isStencilOpDirty = false;
  10249. }
  10250. };
  10251. return _StencilState;
  10252. }());
  10253. BABYLON._StencilState = _StencilState;
  10254. })(BABYLON || (BABYLON = {}));
  10255. //# sourceMappingURL=babylon.stencilState.js.map
  10256. "use strict";
  10257. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10258. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10259. s = arguments[i];
  10260. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10261. t[p] = s[p];
  10262. }
  10263. return t;
  10264. };
  10265. var BABYLON;
  10266. (function (BABYLON) {
  10267. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10268. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10269. };
  10270. var compileRawShader = function (gl, source, type) {
  10271. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10272. gl.shaderSource(shader, source);
  10273. gl.compileShader(shader);
  10274. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10275. var log = gl.getShaderInfoLog(shader);
  10276. if (log) {
  10277. throw new Error(log);
  10278. }
  10279. }
  10280. if (!shader) {
  10281. throw new Error("Something went wrong while compile the shader.");
  10282. }
  10283. return shader;
  10284. };
  10285. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10286. var magFilter = gl.NEAREST;
  10287. var minFilter = gl.NEAREST;
  10288. switch (samplingMode) {
  10289. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10290. magFilter = gl.LINEAR;
  10291. if (generateMipMaps) {
  10292. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10293. }
  10294. else {
  10295. minFilter = gl.LINEAR;
  10296. }
  10297. break;
  10298. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10299. magFilter = gl.LINEAR;
  10300. if (generateMipMaps) {
  10301. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10302. }
  10303. else {
  10304. minFilter = gl.LINEAR;
  10305. }
  10306. break;
  10307. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10308. magFilter = gl.NEAREST;
  10309. if (generateMipMaps) {
  10310. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10311. }
  10312. else {
  10313. minFilter = gl.NEAREST;
  10314. }
  10315. break;
  10316. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10317. magFilter = gl.NEAREST;
  10318. if (generateMipMaps) {
  10319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10320. }
  10321. else {
  10322. minFilter = gl.NEAREST;
  10323. }
  10324. break;
  10325. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10326. magFilter = gl.NEAREST;
  10327. if (generateMipMaps) {
  10328. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10329. }
  10330. else {
  10331. minFilter = gl.LINEAR;
  10332. }
  10333. break;
  10334. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10335. magFilter = gl.NEAREST;
  10336. if (generateMipMaps) {
  10337. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10338. }
  10339. else {
  10340. minFilter = gl.LINEAR;
  10341. }
  10342. break;
  10343. case BABYLON.Texture.NEAREST_LINEAR:
  10344. magFilter = gl.NEAREST;
  10345. minFilter = gl.LINEAR;
  10346. break;
  10347. case BABYLON.Texture.NEAREST_NEAREST:
  10348. magFilter = gl.NEAREST;
  10349. minFilter = gl.NEAREST;
  10350. break;
  10351. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10352. magFilter = gl.LINEAR;
  10353. if (generateMipMaps) {
  10354. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10355. }
  10356. else {
  10357. minFilter = gl.NEAREST;
  10358. }
  10359. break;
  10360. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10361. magFilter = gl.LINEAR;
  10362. if (generateMipMaps) {
  10363. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10364. }
  10365. else {
  10366. minFilter = gl.NEAREST;
  10367. }
  10368. break;
  10369. case BABYLON.Texture.LINEAR_LINEAR:
  10370. magFilter = gl.LINEAR;
  10371. minFilter = gl.LINEAR;
  10372. break;
  10373. case BABYLON.Texture.LINEAR_NEAREST:
  10374. magFilter = gl.LINEAR;
  10375. minFilter = gl.NEAREST;
  10376. break;
  10377. }
  10378. return {
  10379. min: minFilter,
  10380. mag: magFilter
  10381. };
  10382. };
  10383. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10384. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10385. var img;
  10386. var onload = function () {
  10387. loadedImages[index] = img;
  10388. loadedImages._internalCount++;
  10389. if (scene) {
  10390. scene._removePendingData(img);
  10391. }
  10392. if (loadedImages._internalCount === 6) {
  10393. onfinish(loadedImages);
  10394. }
  10395. };
  10396. var onerror = function (message, exception) {
  10397. if (scene) {
  10398. scene._removePendingData(img);
  10399. }
  10400. if (onErrorCallBack) {
  10401. onErrorCallBack(message, exception);
  10402. }
  10403. };
  10404. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10405. if (scene) {
  10406. scene._addPendingData(img);
  10407. }
  10408. };
  10409. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10410. if (onError === void 0) { onError = null; }
  10411. var loadedImages = [];
  10412. loadedImages._internalCount = 0;
  10413. for (var index = 0; index < 6; index++) {
  10414. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10415. }
  10416. };
  10417. var BufferPointer = /** @class */ (function () {
  10418. function BufferPointer() {
  10419. }
  10420. return BufferPointer;
  10421. }());
  10422. var InstancingAttributeInfo = /** @class */ (function () {
  10423. function InstancingAttributeInfo() {
  10424. }
  10425. return InstancingAttributeInfo;
  10426. }());
  10427. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10428. /**
  10429. * Define options used to create a render target texture
  10430. */
  10431. var RenderTargetCreationOptions = /** @class */ (function () {
  10432. function RenderTargetCreationOptions() {
  10433. }
  10434. return RenderTargetCreationOptions;
  10435. }());
  10436. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10437. /**
  10438. * Define options used to create a depth texture
  10439. */
  10440. var DepthTextureCreationOptions = /** @class */ (function () {
  10441. function DepthTextureCreationOptions() {
  10442. }
  10443. return DepthTextureCreationOptions;
  10444. }());
  10445. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10446. /**
  10447. * Regroup several parameters relative to the browser in use
  10448. */
  10449. var EngineCapabilities = /** @class */ (function () {
  10450. function EngineCapabilities() {
  10451. }
  10452. return EngineCapabilities;
  10453. }());
  10454. BABYLON.EngineCapabilities = EngineCapabilities;
  10455. /**
  10456. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10457. */
  10458. var Engine = /** @class */ (function () {
  10459. /**
  10460. * @constructor
  10461. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10462. * @param antialias defines enable antialiasing (default: false)
  10463. * @param options defines further options to be sent to the getContext() function
  10464. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10465. */
  10466. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10467. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10468. var _this = this;
  10469. // Public members
  10470. this.forcePOTTextures = false;
  10471. this.isFullscreen = false;
  10472. this.isPointerLock = false;
  10473. this.cullBackFaces = true;
  10474. this.renderEvenInBackground = true;
  10475. this.preventCacheWipeBetweenFrames = false;
  10476. /**
  10477. * To enable/disable IDB support and avoid XHR on .manifest
  10478. **/
  10479. this.enableOfflineSupport = false;
  10480. this.scenes = new Array();
  10481. this.postProcesses = new Array();
  10482. // Observables
  10483. /**
  10484. * Observable event triggered each time the rendering canvas is resized
  10485. */
  10486. this.onResizeObservable = new BABYLON.Observable();
  10487. /**
  10488. * Observable event triggered each time the canvas loses focus
  10489. */
  10490. this.onCanvasBlurObservable = new BABYLON.Observable();
  10491. /**
  10492. * Observable event triggered each time the canvas gains focus
  10493. */
  10494. this.onCanvasFocusObservable = new BABYLON.Observable();
  10495. /**
  10496. * Observable event triggered each time the canvas receives pointerout event
  10497. */
  10498. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10499. /**
  10500. * Observable event triggered before each texture is initialized
  10501. */
  10502. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10503. //WebVR
  10504. this._vrDisplay = undefined;
  10505. this._vrSupported = false;
  10506. this._vrExclusivePointerMode = false;
  10507. // Uniform buffers list
  10508. this.disableUniformBuffers = false;
  10509. this._uniformBuffers = new Array();
  10510. // Observables
  10511. /**
  10512. * Observable raised when the engine begins a new frame
  10513. */
  10514. this.onBeginFrameObservable = new BABYLON.Observable();
  10515. /**
  10516. * Observable raised when the engine ends the current frame
  10517. */
  10518. this.onEndFrameObservable = new BABYLON.Observable();
  10519. /**
  10520. * Observable raised when the engine is about to compile a shader
  10521. */
  10522. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10523. /**
  10524. * Observable raised when the engine has jsut compiled a shader
  10525. */
  10526. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10527. this._windowIsBackground = false;
  10528. this._webGLVersion = 1.0;
  10529. this._badOS = false;
  10530. this._badDesktopOS = false;
  10531. /**
  10532. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10533. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10534. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10535. */
  10536. this.disableTextureBindingOptimization = false;
  10537. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10538. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10539. this.onVRRequestPresentStart = new BABYLON.Observable();
  10540. this._colorWrite = true;
  10541. this._drawCalls = new BABYLON.PerfCounter();
  10542. this._textureCollisions = new BABYLON.PerfCounter();
  10543. this._renderingQueueLaunched = false;
  10544. this._activeRenderLoops = new Array();
  10545. // Deterministic lockstepMaxSteps
  10546. this._deterministicLockstep = false;
  10547. this._lockstepMaxSteps = 4;
  10548. // Lost context
  10549. this.onContextLostObservable = new BABYLON.Observable();
  10550. this.onContextRestoredObservable = new BABYLON.Observable();
  10551. this._contextWasLost = false;
  10552. this._doNotHandleContextLost = false;
  10553. // FPS
  10554. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10555. this._fps = 60;
  10556. this._deltaTime = 0;
  10557. /**
  10558. * Turn this value on if you want to pause FPS computation when in background
  10559. */
  10560. this.disablePerformanceMonitorInBackground = false;
  10561. // States
  10562. this._depthCullingState = new BABYLON._DepthCullingState();
  10563. this._stencilState = new BABYLON._StencilState();
  10564. this._alphaState = new BABYLON._AlphaState();
  10565. this._alphaMode = Engine.ALPHA_DISABLE;
  10566. // Cache
  10567. this._internalTexturesCache = new Array();
  10568. this._activeChannel = 0;
  10569. this._currentTextureChannel = -1;
  10570. this._boundTexturesCache = {};
  10571. this._compiledEffects = {};
  10572. this._vertexAttribArraysEnabled = [];
  10573. this._uintIndicesCurrentlySet = false;
  10574. this._currentBoundBuffer = new Array();
  10575. this._currentBufferPointers = new Array();
  10576. this._currentInstanceLocations = new Array();
  10577. this._currentInstanceBuffers = new Array();
  10578. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10579. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10580. this._vaoRecordInProgress = false;
  10581. this._mustWipeVertexAttributes = false;
  10582. this._nextFreeTextureSlots = new Array();
  10583. this._maxSimultaneousTextures = 0;
  10584. this._activeRequests = new Array();
  10585. // Hardware supported Compressed Textures
  10586. this._texturesSupported = new Array();
  10587. this._onVRFullScreenTriggered = function () {
  10588. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10589. //get the old size before we change
  10590. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10591. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10592. //get the width and height, change the render size
  10593. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10594. _this.setHardwareScalingLevel(1);
  10595. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10596. }
  10597. else {
  10598. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10599. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10600. }
  10601. };
  10602. this._boundUniforms = {};
  10603. // Register promises
  10604. BABYLON.PromisePolyfill.Apply();
  10605. var canvas = null;
  10606. Engine.Instances.push(this);
  10607. if (!canvasOrContext) {
  10608. return;
  10609. }
  10610. options = options || {};
  10611. if (canvasOrContext.getContext) {
  10612. canvas = canvasOrContext;
  10613. this._renderingCanvas = canvas;
  10614. if (antialias != null) {
  10615. options.antialias = antialias;
  10616. }
  10617. if (options.deterministicLockstep === undefined) {
  10618. options.deterministicLockstep = false;
  10619. }
  10620. if (options.lockstepMaxSteps === undefined) {
  10621. options.lockstepMaxSteps = 4;
  10622. }
  10623. if (options.preserveDrawingBuffer === undefined) {
  10624. options.preserveDrawingBuffer = false;
  10625. }
  10626. if (options.audioEngine === undefined) {
  10627. options.audioEngine = true;
  10628. }
  10629. if (options.stencil === undefined) {
  10630. options.stencil = true;
  10631. }
  10632. this._deterministicLockstep = options.deterministicLockstep;
  10633. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10634. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10635. // Exceptions
  10636. if (navigator && navigator.userAgent) {
  10637. var ua = navigator.userAgent;
  10638. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10639. var exception = _a[_i];
  10640. var key = exception.key;
  10641. var targets = exception.targets;
  10642. if (ua.indexOf(key) > -1) {
  10643. if (exception.capture && exception.captureConstraint) {
  10644. var capture = exception.capture;
  10645. var constraint = exception.captureConstraint;
  10646. var regex = new RegExp(capture);
  10647. var matches = regex.exec(ua);
  10648. if (matches && matches.length > 0) {
  10649. var capturedValue = parseInt(matches[matches.length - 1]);
  10650. if (capturedValue >= constraint) {
  10651. continue;
  10652. }
  10653. }
  10654. }
  10655. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10656. var target = targets_1[_b];
  10657. switch (target) {
  10658. case "uniformBuffer":
  10659. this.disableUniformBuffers = true;
  10660. break;
  10661. case "textureBindingOptimization":
  10662. this.disableTextureBindingOptimization = true;
  10663. break;
  10664. }
  10665. }
  10666. }
  10667. }
  10668. }
  10669. // GL
  10670. if (!options.disableWebGL2Support) {
  10671. try {
  10672. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10673. if (this._gl) {
  10674. this._webGLVersion = 2.0;
  10675. }
  10676. }
  10677. catch (e) {
  10678. // Do nothing
  10679. }
  10680. }
  10681. if (!this._gl) {
  10682. if (!canvas) {
  10683. throw new Error("The provided canvas is null or undefined.");
  10684. }
  10685. try {
  10686. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10687. }
  10688. catch (e) {
  10689. throw new Error("WebGL not supported");
  10690. }
  10691. }
  10692. if (!this._gl) {
  10693. throw new Error("WebGL not supported");
  10694. }
  10695. this._onCanvasFocus = function () {
  10696. _this.onCanvasFocusObservable.notifyObservers(_this);
  10697. };
  10698. this._onCanvasBlur = function () {
  10699. _this.onCanvasBlurObservable.notifyObservers(_this);
  10700. };
  10701. canvas.addEventListener("focus", this._onCanvasFocus);
  10702. canvas.addEventListener("blur", this._onCanvasBlur);
  10703. this._onBlur = function () {
  10704. if (_this.disablePerformanceMonitorInBackground) {
  10705. _this._performanceMonitor.disable();
  10706. }
  10707. _this._windowIsBackground = true;
  10708. };
  10709. this._onFocus = function () {
  10710. if (_this.disablePerformanceMonitorInBackground) {
  10711. _this._performanceMonitor.enable();
  10712. }
  10713. _this._windowIsBackground = false;
  10714. };
  10715. this._onCanvasPointerOut = function (ev) {
  10716. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10717. };
  10718. window.addEventListener("blur", this._onBlur);
  10719. window.addEventListener("focus", this._onFocus);
  10720. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10721. // Context lost
  10722. if (!this._doNotHandleContextLost) {
  10723. this._onContextLost = function (evt) {
  10724. evt.preventDefault();
  10725. _this._contextWasLost = true;
  10726. BABYLON.Tools.Warn("WebGL context lost.");
  10727. _this.onContextLostObservable.notifyObservers(_this);
  10728. };
  10729. this._onContextRestored = function (evt) {
  10730. // Adding a timeout to avoid race condition at browser level
  10731. setTimeout(function () {
  10732. // Rebuild gl context
  10733. _this._initGLContext();
  10734. // Rebuild effects
  10735. _this._rebuildEffects();
  10736. // Rebuild textures
  10737. _this._rebuildInternalTextures();
  10738. // Rebuild buffers
  10739. _this._rebuildBuffers();
  10740. // Cache
  10741. _this.wipeCaches(true);
  10742. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10743. _this.onContextRestoredObservable.notifyObservers(_this);
  10744. _this._contextWasLost = false;
  10745. }, 0);
  10746. };
  10747. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10748. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10749. }
  10750. }
  10751. else {
  10752. this._gl = canvasOrContext;
  10753. this._renderingCanvas = this._gl.canvas;
  10754. if (this._gl.renderbufferStorageMultisample) {
  10755. this._webGLVersion = 2.0;
  10756. }
  10757. options.stencil = this._gl.getContextAttributes().stencil;
  10758. }
  10759. // Viewport
  10760. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10761. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10762. this.resize();
  10763. this._isStencilEnable = options.stencil ? true : false;
  10764. this._initGLContext();
  10765. if (canvas) {
  10766. // Fullscreen
  10767. this._onFullscreenChange = function () {
  10768. if (document.fullscreen !== undefined) {
  10769. _this.isFullscreen = document.fullscreen;
  10770. }
  10771. else if (document.mozFullScreen !== undefined) {
  10772. _this.isFullscreen = document.mozFullScreen;
  10773. }
  10774. else if (document.webkitIsFullScreen !== undefined) {
  10775. _this.isFullscreen = document.webkitIsFullScreen;
  10776. }
  10777. else if (document.msIsFullScreen !== undefined) {
  10778. _this.isFullscreen = document.msIsFullScreen;
  10779. }
  10780. // Pointer lock
  10781. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10782. canvas.requestPointerLock = canvas.requestPointerLock ||
  10783. canvas.msRequestPointerLock ||
  10784. canvas.mozRequestPointerLock ||
  10785. canvas.webkitRequestPointerLock;
  10786. if (canvas.requestPointerLock) {
  10787. canvas.requestPointerLock();
  10788. }
  10789. }
  10790. };
  10791. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10792. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10793. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10794. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10795. // Pointer lock
  10796. this._onPointerLockChange = function () {
  10797. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10798. document.webkitPointerLockElement === canvas ||
  10799. document.msPointerLockElement === canvas ||
  10800. document.pointerLockElement === canvas);
  10801. };
  10802. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10803. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10804. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10805. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10806. this._onVRDisplayPointerRestricted = function () {
  10807. if (canvas) {
  10808. canvas.requestPointerLock();
  10809. }
  10810. };
  10811. this._onVRDisplayPointerUnrestricted = function () {
  10812. document.exitPointerLock();
  10813. };
  10814. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10815. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10816. }
  10817. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10818. Engine.audioEngine = new BABYLON.AudioEngine();
  10819. }
  10820. // Prepare buffer pointers
  10821. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10822. this._currentBufferPointers[i] = new BufferPointer();
  10823. }
  10824. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10825. // Load WebVR Devices
  10826. if (options.autoEnableWebVR) {
  10827. this.initWebVR();
  10828. }
  10829. // Detect if we are running on a faulty buggy OS.
  10830. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10831. // Detect if we are running on a faulty buggy desktop OS.
  10832. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10833. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10834. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10835. }
  10836. Object.defineProperty(Engine, "LastCreatedEngine", {
  10837. get: function () {
  10838. if (Engine.Instances.length === 0) {
  10839. return null;
  10840. }
  10841. return Engine.Instances[Engine.Instances.length - 1];
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(Engine, "LastCreatedScene", {
  10847. get: function () {
  10848. var lastCreatedEngine = Engine.LastCreatedEngine;
  10849. if (!lastCreatedEngine) {
  10850. return null;
  10851. }
  10852. if (lastCreatedEngine.scenes.length === 0) {
  10853. return null;
  10854. }
  10855. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. /**
  10861. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10862. */
  10863. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10864. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10865. var engine = Engine.Instances[engineIndex];
  10866. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10867. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10868. }
  10869. }
  10870. };
  10871. Object.defineProperty(Engine, "NEVER", {
  10872. get: function () {
  10873. return Engine._NEVER;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine, "ALWAYS", {
  10879. get: function () {
  10880. return Engine._ALWAYS;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Engine, "LESS", {
  10886. get: function () {
  10887. return Engine._LESS;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(Engine, "EQUAL", {
  10893. get: function () {
  10894. return Engine._EQUAL;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "LEQUAL", {
  10900. get: function () {
  10901. return Engine._LEQUAL;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine, "GREATER", {
  10907. get: function () {
  10908. return Engine._GREATER;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "GEQUAL", {
  10914. get: function () {
  10915. return Engine._GEQUAL;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "NOTEQUAL", {
  10921. get: function () {
  10922. return Engine._NOTEQUAL;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine, "KEEP", {
  10928. get: function () {
  10929. return Engine._KEEP;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "REPLACE", {
  10935. get: function () {
  10936. return Engine._REPLACE;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine, "INCR", {
  10942. get: function () {
  10943. return Engine._INCR;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine, "DECR", {
  10949. get: function () {
  10950. return Engine._DECR;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine, "INVERT", {
  10956. get: function () {
  10957. return Engine._INVERT;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine, "INCR_WRAP", {
  10963. get: function () {
  10964. return Engine._INCR_WRAP;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine, "DECR_WRAP", {
  10970. get: function () {
  10971. return Engine._DECR_WRAP;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10977. get: function () {
  10978. return Engine._ALPHA_DISABLE;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10984. get: function () {
  10985. return Engine._ALPHA_ONEONE;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine, "ALPHA_ADD", {
  10991. get: function () {
  10992. return Engine._ALPHA_ADD;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10998. get: function () {
  10999. return Engine._ALPHA_COMBINE;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11005. get: function () {
  11006. return Engine._ALPHA_SUBTRACT;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11012. get: function () {
  11013. return Engine._ALPHA_MULTIPLY;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11019. get: function () {
  11020. return Engine._ALPHA_MAXIMIZED;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11026. get: function () {
  11027. return Engine._ALPHA_PREMULTIPLIED;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11033. get: function () {
  11034. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11040. get: function () {
  11041. return Engine._ALPHA_INTERPOLATE;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11047. get: function () {
  11048. return Engine._ALPHA_SCREENMODE;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11054. get: function () {
  11055. return Engine._DELAYLOADSTATE_NONE;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11061. get: function () {
  11062. return Engine._DELAYLOADSTATE_LOADED;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11068. get: function () {
  11069. return Engine._DELAYLOADSTATE_LOADING;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11075. get: function () {
  11076. return Engine._DELAYLOADSTATE_NOTLOADED;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11082. get: function () {
  11083. return Engine._TEXTUREFORMAT_ALPHA;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11089. get: function () {
  11090. return Engine._TEXTUREFORMAT_LUMINANCE;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11096. /**
  11097. * R32F
  11098. */
  11099. get: function () {
  11100. return Engine._TEXTUREFORMAT_R32F;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11106. /**
  11107. * RG32F
  11108. */
  11109. get: function () {
  11110. return Engine._TEXTUREFORMAT_RG32F;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11116. /**
  11117. * RGB32F
  11118. */
  11119. get: function () {
  11120. return Engine._TEXTUREFORMAT_RGB32F;
  11121. },
  11122. enumerable: true,
  11123. configurable: true
  11124. });
  11125. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11126. /**
  11127. * RGBA32F
  11128. */
  11129. get: function () {
  11130. return Engine._TEXTUREFORMAT_RGBA32F;
  11131. },
  11132. enumerable: true,
  11133. configurable: true
  11134. });
  11135. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11136. get: function () {
  11137. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11138. },
  11139. enumerable: true,
  11140. configurable: true
  11141. });
  11142. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11143. get: function () {
  11144. return Engine._TEXTUREFORMAT_RGB;
  11145. },
  11146. enumerable: true,
  11147. configurable: true
  11148. });
  11149. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11150. get: function () {
  11151. return Engine._TEXTUREFORMAT_RGBA;
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11157. get: function () {
  11158. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11159. },
  11160. enumerable: true,
  11161. configurable: true
  11162. });
  11163. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11164. get: function () {
  11165. return Engine._TEXTURETYPE_FLOAT;
  11166. },
  11167. enumerable: true,
  11168. configurable: true
  11169. });
  11170. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11171. get: function () {
  11172. return Engine._TEXTURETYPE_HALF_FLOAT;
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11178. get: function () {
  11179. return Engine._SCALEMODE_FLOOR;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11185. get: function () {
  11186. return Engine._SCALEMODE_NEAREST;
  11187. },
  11188. enumerable: true,
  11189. configurable: true
  11190. });
  11191. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11192. get: function () {
  11193. return Engine._SCALEMODE_CEILING;
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(Engine, "Version", {
  11199. get: function () {
  11200. return "3.2.0-beta.3";
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11206. get: function () {
  11207. return this._vrExclusivePointerMode;
  11208. },
  11209. enumerable: true,
  11210. configurable: true
  11211. });
  11212. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11213. get: function () {
  11214. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11215. },
  11216. enumerable: true,
  11217. configurable: true
  11218. });
  11219. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11220. get: function () {
  11221. return this._webGLVersion < 2 || this.forcePOTTextures;
  11222. },
  11223. enumerable: true,
  11224. configurable: true
  11225. });
  11226. Object.defineProperty(Engine.prototype, "badOS", {
  11227. get: function () {
  11228. return this._badOS;
  11229. },
  11230. enumerable: true,
  11231. configurable: true
  11232. });
  11233. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11234. get: function () {
  11235. return this._badDesktopOS;
  11236. },
  11237. enumerable: true,
  11238. configurable: true
  11239. });
  11240. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11241. get: function () {
  11242. return this._performanceMonitor;
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11248. get: function () {
  11249. return this._texturesSupported;
  11250. },
  11251. enumerable: true,
  11252. configurable: true
  11253. });
  11254. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11255. get: function () {
  11256. return this._textureFormatInUse;
  11257. },
  11258. enumerable: true,
  11259. configurable: true
  11260. });
  11261. Object.defineProperty(Engine.prototype, "currentViewport", {
  11262. get: function () {
  11263. return this._cachedViewport;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11269. // Empty texture
  11270. get: function () {
  11271. if (!this._emptyTexture) {
  11272. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11273. }
  11274. return this._emptyTexture;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11280. get: function () {
  11281. if (!this._emptyTexture3D) {
  11282. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11283. }
  11284. return this._emptyTexture3D;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11290. get: function () {
  11291. if (!this._emptyCubeTexture) {
  11292. var faceData = new Uint8Array(4);
  11293. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11294. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11295. }
  11296. return this._emptyCubeTexture;
  11297. },
  11298. enumerable: true,
  11299. configurable: true
  11300. });
  11301. Engine.prototype._rebuildInternalTextures = function () {
  11302. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11303. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11304. var internalTexture = currentState_1[_i];
  11305. internalTexture._rebuild();
  11306. }
  11307. };
  11308. Engine.prototype._rebuildEffects = function () {
  11309. for (var key in this._compiledEffects) {
  11310. var effect = this._compiledEffects[key];
  11311. effect._prepareEffect();
  11312. }
  11313. BABYLON.Effect.ResetCache();
  11314. };
  11315. Engine.prototype._rebuildBuffers = function () {
  11316. // Index / Vertex
  11317. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11318. var scene = _a[_i];
  11319. scene.resetCachedMaterial();
  11320. scene._rebuildGeometries();
  11321. scene._rebuildTextures();
  11322. }
  11323. // Uniforms
  11324. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11325. var uniformBuffer = _c[_b];
  11326. uniformBuffer._rebuild();
  11327. }
  11328. };
  11329. Engine.prototype._initGLContext = function () {
  11330. // Caps
  11331. this._caps = new EngineCapabilities();
  11332. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11333. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11334. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11335. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11336. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11337. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11338. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11339. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11340. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11341. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11342. // Infos
  11343. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11344. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11345. if (rendererInfo != null) {
  11346. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11347. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11348. }
  11349. if (!this._glVendor) {
  11350. this._glVendor = "Unknown vendor";
  11351. }
  11352. if (!this._glRenderer) {
  11353. this._glRenderer = "Unknown renderer";
  11354. }
  11355. // Constants
  11356. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11357. if (this._gl.RGBA16F !== 0x881A) {
  11358. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11359. }
  11360. if (this._gl.RGBA32F !== 0x8814) {
  11361. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11362. }
  11363. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11364. this._gl.DEPTH24_STENCIL8 = 35056;
  11365. }
  11366. // Extensions
  11367. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11368. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11369. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11370. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11371. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11372. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11373. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11374. 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');
  11375. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11376. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11377. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11378. this._caps.highPrecisionShaderSupported = true;
  11379. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11380. if (this._caps.timerQuery) {
  11381. if (this._webGLVersion === 1) {
  11382. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11383. }
  11384. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11385. }
  11386. // Checks if some of the format renders first to allow the use of webgl inspector.
  11387. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11388. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11389. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11390. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11391. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11392. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11393. if (this._webGLVersion > 1) {
  11394. this._gl.HALF_FLOAT_OES = 0x140B;
  11395. }
  11396. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11397. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11398. // Draw buffers
  11399. if (this._webGLVersion > 1) {
  11400. this._caps.drawBuffersExtension = true;
  11401. }
  11402. else {
  11403. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11404. if (drawBuffersExtension !== null) {
  11405. this._caps.drawBuffersExtension = true;
  11406. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11407. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11408. for (var i = 0; i < 16; i++) {
  11409. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11410. }
  11411. }
  11412. else {
  11413. this._caps.drawBuffersExtension = false;
  11414. }
  11415. }
  11416. // Depth Texture
  11417. if (this._webGLVersion > 1) {
  11418. this._caps.depthTextureExtension = true;
  11419. }
  11420. else {
  11421. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11422. if (depthTextureExtension != null) {
  11423. this._caps.depthTextureExtension = true;
  11424. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11425. }
  11426. }
  11427. // Vertex array object
  11428. if (this._webGLVersion > 1) {
  11429. this._caps.vertexArrayObject = true;
  11430. }
  11431. else {
  11432. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11433. if (vertexArrayObjectExtension != null) {
  11434. this._caps.vertexArrayObject = true;
  11435. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11436. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11437. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11438. }
  11439. else {
  11440. this._caps.vertexArrayObject = false;
  11441. }
  11442. }
  11443. // Instances count
  11444. if (this._webGLVersion > 1) {
  11445. this._caps.instancedArrays = true;
  11446. }
  11447. else {
  11448. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11449. if (instanceExtension != null) {
  11450. this._caps.instancedArrays = true;
  11451. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11452. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11453. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11454. }
  11455. else {
  11456. this._caps.instancedArrays = false;
  11457. }
  11458. }
  11459. // Intelligently add supported compressed formats in order to check for.
  11460. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11461. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11462. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11463. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11464. if (this._caps.astc)
  11465. this.texturesSupported.push('-astc.ktx');
  11466. if (this._caps.s3tc)
  11467. this.texturesSupported.push('-dxt.ktx');
  11468. if (this._caps.pvrtc)
  11469. this.texturesSupported.push('-pvrtc.ktx');
  11470. if (this._caps.etc2)
  11471. this.texturesSupported.push('-etc2.ktx');
  11472. if (this._caps.etc1)
  11473. this.texturesSupported.push('-etc1.ktx');
  11474. if (this._gl.getShaderPrecisionFormat) {
  11475. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11476. if (highp) {
  11477. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11478. }
  11479. }
  11480. // Depth buffer
  11481. this.setDepthBuffer(true);
  11482. this.setDepthFunctionToLessOrEqual();
  11483. this.setDepthWrite(true);
  11484. // Texture maps
  11485. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11486. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11487. this._nextFreeTextureSlots.push(slot);
  11488. }
  11489. };
  11490. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11491. get: function () {
  11492. return this._webGLVersion;
  11493. },
  11494. enumerable: true,
  11495. configurable: true
  11496. });
  11497. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11498. /**
  11499. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11500. */
  11501. get: function () {
  11502. return this._isStencilEnable;
  11503. },
  11504. enumerable: true,
  11505. configurable: true
  11506. });
  11507. Engine.prototype._prepareWorkingCanvas = function () {
  11508. if (this._workingCanvas) {
  11509. return;
  11510. }
  11511. this._workingCanvas = document.createElement("canvas");
  11512. var context = this._workingCanvas.getContext("2d");
  11513. if (context) {
  11514. this._workingContext = context;
  11515. }
  11516. };
  11517. Engine.prototype.resetTextureCache = function () {
  11518. for (var key in this._boundTexturesCache) {
  11519. var boundTexture = this._boundTexturesCache[key];
  11520. if (boundTexture) {
  11521. this._removeDesignatedSlot(boundTexture);
  11522. }
  11523. this._boundTexturesCache[key] = null;
  11524. }
  11525. if (!this.disableTextureBindingOptimization) {
  11526. this._nextFreeTextureSlots = [];
  11527. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11528. this._nextFreeTextureSlots.push(slot);
  11529. }
  11530. }
  11531. this._currentTextureChannel = -1;
  11532. };
  11533. Engine.prototype.isDeterministicLockStep = function () {
  11534. return this._deterministicLockstep;
  11535. };
  11536. Engine.prototype.getLockstepMaxSteps = function () {
  11537. return this._lockstepMaxSteps;
  11538. };
  11539. Engine.prototype.getGlInfo = function () {
  11540. return {
  11541. vendor: this._glVendor,
  11542. renderer: this._glRenderer,
  11543. version: this._glVersion
  11544. };
  11545. };
  11546. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11547. if (useScreen === void 0) { useScreen = false; }
  11548. var viewport = camera.viewport;
  11549. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11550. };
  11551. Engine.prototype.getRenderWidth = function (useScreen) {
  11552. if (useScreen === void 0) { useScreen = false; }
  11553. if (!useScreen && this._currentRenderTarget) {
  11554. return this._currentRenderTarget.width;
  11555. }
  11556. return this._gl.drawingBufferWidth;
  11557. };
  11558. Engine.prototype.getRenderHeight = function (useScreen) {
  11559. if (useScreen === void 0) { useScreen = false; }
  11560. if (!useScreen && this._currentRenderTarget) {
  11561. return this._currentRenderTarget.height;
  11562. }
  11563. return this._gl.drawingBufferHeight;
  11564. };
  11565. Engine.prototype.getRenderingCanvas = function () {
  11566. return this._renderingCanvas;
  11567. };
  11568. Engine.prototype.getRenderingCanvasClientRect = function () {
  11569. if (!this._renderingCanvas) {
  11570. return null;
  11571. }
  11572. return this._renderingCanvas.getBoundingClientRect();
  11573. };
  11574. Engine.prototype.setHardwareScalingLevel = function (level) {
  11575. this._hardwareScalingLevel = level;
  11576. this.resize();
  11577. };
  11578. Engine.prototype.getHardwareScalingLevel = function () {
  11579. return this._hardwareScalingLevel;
  11580. };
  11581. Engine.prototype.getLoadedTexturesCache = function () {
  11582. return this._internalTexturesCache;
  11583. };
  11584. Engine.prototype.getCaps = function () {
  11585. return this._caps;
  11586. };
  11587. Object.defineProperty(Engine.prototype, "drawCalls", {
  11588. /** The number of draw calls submitted last frame */
  11589. get: function () {
  11590. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11591. return 0;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11597. get: function () {
  11598. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11599. return null;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Engine.prototype.getDepthFunction = function () {
  11605. return this._depthCullingState.depthFunc;
  11606. };
  11607. Engine.prototype.setDepthFunction = function (depthFunc) {
  11608. this._depthCullingState.depthFunc = depthFunc;
  11609. };
  11610. Engine.prototype.setDepthFunctionToGreater = function () {
  11611. this._depthCullingState.depthFunc = this._gl.GREATER;
  11612. };
  11613. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11614. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11615. };
  11616. Engine.prototype.setDepthFunctionToLess = function () {
  11617. this._depthCullingState.depthFunc = this._gl.LESS;
  11618. };
  11619. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11620. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11621. };
  11622. Engine.prototype.getStencilBuffer = function () {
  11623. return this._stencilState.stencilTest;
  11624. };
  11625. Engine.prototype.setStencilBuffer = function (enable) {
  11626. this._stencilState.stencilTest = enable;
  11627. };
  11628. Engine.prototype.getStencilMask = function () {
  11629. return this._stencilState.stencilMask;
  11630. };
  11631. Engine.prototype.setStencilMask = function (mask) {
  11632. this._stencilState.stencilMask = mask;
  11633. };
  11634. Engine.prototype.getStencilFunction = function () {
  11635. return this._stencilState.stencilFunc;
  11636. };
  11637. Engine.prototype.getStencilFunctionReference = function () {
  11638. return this._stencilState.stencilFuncRef;
  11639. };
  11640. Engine.prototype.getStencilFunctionMask = function () {
  11641. return this._stencilState.stencilFuncMask;
  11642. };
  11643. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11644. this._stencilState.stencilFunc = stencilFunc;
  11645. };
  11646. Engine.prototype.setStencilFunctionReference = function (reference) {
  11647. this._stencilState.stencilFuncRef = reference;
  11648. };
  11649. Engine.prototype.setStencilFunctionMask = function (mask) {
  11650. this._stencilState.stencilFuncMask = mask;
  11651. };
  11652. Engine.prototype.getStencilOperationFail = function () {
  11653. return this._stencilState.stencilOpStencilFail;
  11654. };
  11655. Engine.prototype.getStencilOperationDepthFail = function () {
  11656. return this._stencilState.stencilOpDepthFail;
  11657. };
  11658. Engine.prototype.getStencilOperationPass = function () {
  11659. return this._stencilState.stencilOpStencilDepthPass;
  11660. };
  11661. Engine.prototype.setStencilOperationFail = function (operation) {
  11662. this._stencilState.stencilOpStencilFail = operation;
  11663. };
  11664. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11665. this._stencilState.stencilOpDepthFail = operation;
  11666. };
  11667. Engine.prototype.setStencilOperationPass = function (operation) {
  11668. this._stencilState.stencilOpStencilDepthPass = operation;
  11669. };
  11670. Engine.prototype.setDitheringState = function (value) {
  11671. if (value) {
  11672. this._gl.enable(this._gl.DITHER);
  11673. }
  11674. else {
  11675. this._gl.disable(this._gl.DITHER);
  11676. }
  11677. };
  11678. Engine.prototype.setRasterizerState = function (value) {
  11679. if (value) {
  11680. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11681. }
  11682. else {
  11683. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11684. }
  11685. };
  11686. /**
  11687. * stop executing a render loop function and remove it from the execution array
  11688. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11689. */
  11690. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11691. if (!renderFunction) {
  11692. this._activeRenderLoops = [];
  11693. return;
  11694. }
  11695. var index = this._activeRenderLoops.indexOf(renderFunction);
  11696. if (index >= 0) {
  11697. this._activeRenderLoops.splice(index, 1);
  11698. }
  11699. };
  11700. Engine.prototype._renderLoop = function () {
  11701. if (!this._contextWasLost) {
  11702. var shouldRender = true;
  11703. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11704. shouldRender = false;
  11705. }
  11706. if (shouldRender) {
  11707. // Start new frame
  11708. this.beginFrame();
  11709. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11710. var renderFunction = this._activeRenderLoops[index];
  11711. renderFunction();
  11712. }
  11713. // Present
  11714. this.endFrame();
  11715. }
  11716. }
  11717. if (this._activeRenderLoops.length > 0) {
  11718. // Register new frame
  11719. var requester = null;
  11720. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11721. requester = this._vrDisplay;
  11722. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11723. }
  11724. else {
  11725. this._renderingQueueLaunched = false;
  11726. }
  11727. };
  11728. /**
  11729. * Register and execute a render loop. The engine can have more than one render function.
  11730. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11731. * @example
  11732. * engine.runRenderLoop(function () {
  11733. * scene.render()
  11734. * })
  11735. */
  11736. Engine.prototype.runRenderLoop = function (renderFunction) {
  11737. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11738. return;
  11739. }
  11740. this._activeRenderLoops.push(renderFunction);
  11741. if (!this._renderingQueueLaunched) {
  11742. this._renderingQueueLaunched = true;
  11743. this._bindedRenderFunction = this._renderLoop.bind(this);
  11744. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11745. }
  11746. };
  11747. /**
  11748. * Toggle full screen mode.
  11749. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11750. * @param {any} options - an options object to be sent to the requestFullscreen function
  11751. */
  11752. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11753. if (this.isFullscreen) {
  11754. BABYLON.Tools.ExitFullscreen();
  11755. }
  11756. else {
  11757. this._pointerLockRequested = requestPointerLock;
  11758. if (this._renderingCanvas) {
  11759. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11760. }
  11761. }
  11762. };
  11763. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11764. if (stencil === void 0) { stencil = false; }
  11765. this.applyStates();
  11766. var mode = 0;
  11767. if (backBuffer && color) {
  11768. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11769. mode |= this._gl.COLOR_BUFFER_BIT;
  11770. }
  11771. if (depth) {
  11772. this._gl.clearDepth(1.0);
  11773. mode |= this._gl.DEPTH_BUFFER_BIT;
  11774. }
  11775. if (stencil) {
  11776. this._gl.clearStencil(0);
  11777. mode |= this._gl.STENCIL_BUFFER_BIT;
  11778. }
  11779. this._gl.clear(mode);
  11780. };
  11781. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11782. var gl = this._gl;
  11783. // Save state
  11784. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11785. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11786. // Change state
  11787. gl.enable(gl.SCISSOR_TEST);
  11788. gl.scissor(x, y, width, height);
  11789. // Clear
  11790. this.clear(clearColor, true, true, true);
  11791. // Restore state
  11792. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11793. if (curScissor === true) {
  11794. gl.enable(gl.SCISSOR_TEST);
  11795. }
  11796. else {
  11797. gl.disable(gl.SCISSOR_TEST);
  11798. }
  11799. };
  11800. /**
  11801. * Set the WebGL's viewport
  11802. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11803. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11804. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11805. */
  11806. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11807. var width = requiredWidth || this.getRenderWidth();
  11808. var height = requiredHeight || this.getRenderHeight();
  11809. var x = viewport.x || 0;
  11810. var y = viewport.y || 0;
  11811. this._cachedViewport = viewport;
  11812. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11813. };
  11814. /**
  11815. * Directly set the WebGL Viewport
  11816. * The x, y, width & height are directly passed to the WebGL call
  11817. * @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.
  11818. */
  11819. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11820. var currentViewport = this._cachedViewport;
  11821. this._cachedViewport = null;
  11822. this._gl.viewport(x, y, width, height);
  11823. return currentViewport;
  11824. };
  11825. Engine.prototype.beginFrame = function () {
  11826. this.onBeginFrameObservable.notifyObservers(this);
  11827. this._measureFps();
  11828. };
  11829. Engine.prototype.endFrame = function () {
  11830. //force a flush in case we are using a bad OS.
  11831. if (this._badOS) {
  11832. this.flushFramebuffer();
  11833. }
  11834. //submit frame to the vr device, if enabled
  11835. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11836. // TODO: We should only submit the frame if we read frameData successfully.
  11837. this._vrDisplay.submitFrame();
  11838. }
  11839. this.onEndFrameObservable.notifyObservers(this);
  11840. };
  11841. /**
  11842. * resize the view according to the canvas' size.
  11843. * @example
  11844. * window.addEventListener("resize", function () {
  11845. * engine.resize();
  11846. * });
  11847. */
  11848. Engine.prototype.resize = function () {
  11849. // We're not resizing the size of the canvas while in VR mode & presenting
  11850. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11851. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11852. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11853. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11854. }
  11855. };
  11856. /**
  11857. * force a specific size of the canvas
  11858. * @param {number} width - the new canvas' width
  11859. * @param {number} height - the new canvas' height
  11860. */
  11861. Engine.prototype.setSize = function (width, height) {
  11862. if (!this._renderingCanvas) {
  11863. return;
  11864. }
  11865. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11866. return;
  11867. }
  11868. this._renderingCanvas.width = width;
  11869. this._renderingCanvas.height = height;
  11870. for (var index = 0; index < this.scenes.length; index++) {
  11871. var scene = this.scenes[index];
  11872. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11873. var cam = scene.cameras[camIndex];
  11874. cam._currentRenderId = 0;
  11875. }
  11876. }
  11877. if (this.onResizeObservable.hasObservers) {
  11878. this.onResizeObservable.notifyObservers(this);
  11879. }
  11880. };
  11881. // WebVR functions
  11882. Engine.prototype.isVRDevicePresent = function () {
  11883. return !!this._vrDisplay;
  11884. };
  11885. Engine.prototype.getVRDevice = function () {
  11886. return this._vrDisplay;
  11887. };
  11888. /**
  11889. * Initializes a webVR display and starts listening to display change events.
  11890. * The onVRDisplayChangedObservable will be notified upon these changes.
  11891. * @returns The onVRDisplayChangedObservable.
  11892. */
  11893. Engine.prototype.initWebVR = function () {
  11894. this.initWebVRAsync();
  11895. return this.onVRDisplayChangedObservable;
  11896. };
  11897. /**
  11898. * Initializes a webVR display and starts listening to display change events.
  11899. * The onVRDisplayChangedObservable will be notified upon these changes.
  11900. * @returns A promise containing a VRDisplay and if vr is supported.
  11901. */
  11902. Engine.prototype.initWebVRAsync = function () {
  11903. var _this = this;
  11904. var notifyObservers = function () {
  11905. var eventArgs = {
  11906. vrDisplay: _this._vrDisplay,
  11907. vrSupported: _this._vrSupported
  11908. };
  11909. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11910. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11911. };
  11912. if (!this._onVrDisplayConnect) {
  11913. this._onVrDisplayConnect = function (event) {
  11914. _this._vrDisplay = event.display;
  11915. notifyObservers();
  11916. };
  11917. this._onVrDisplayDisconnect = function () {
  11918. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11919. _this._vrDisplay = undefined;
  11920. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11921. notifyObservers();
  11922. };
  11923. this._onVrDisplayPresentChange = function () {
  11924. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11925. };
  11926. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11927. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11928. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11929. }
  11930. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11931. this._webVRInitPromise.then(notifyObservers);
  11932. return this._webVRInitPromise;
  11933. };
  11934. Engine.prototype.enableVR = function () {
  11935. var _this = this;
  11936. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11937. var onResolved = function () {
  11938. _this.onVRRequestPresentComplete.notifyObservers(true);
  11939. _this._onVRFullScreenTriggered();
  11940. };
  11941. var onRejected = function () {
  11942. _this.onVRRequestPresentComplete.notifyObservers(false);
  11943. };
  11944. this.onVRRequestPresentStart.notifyObservers(this);
  11945. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11946. }
  11947. };
  11948. Engine.prototype.disableVR = function () {
  11949. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11950. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11951. }
  11952. };
  11953. Engine.prototype._getVRDisplaysAsync = function () {
  11954. var _this = this;
  11955. return new Promise(function (res, rej) {
  11956. if (navigator.getVRDisplays) {
  11957. navigator.getVRDisplays().then(function (devices) {
  11958. _this._vrSupported = true;
  11959. // note that devices may actually be an empty array. This is fine;
  11960. // we expect this._vrDisplay to be undefined in this case.
  11961. _this._vrDisplay = devices[0];
  11962. res({
  11963. vrDisplay: _this._vrDisplay,
  11964. vrSupported: _this._vrSupported
  11965. });
  11966. });
  11967. }
  11968. else {
  11969. _this._vrDisplay = undefined;
  11970. _this._vrSupported = false;
  11971. res({
  11972. vrDisplay: _this._vrDisplay,
  11973. vrSupported: _this._vrSupported
  11974. });
  11975. }
  11976. });
  11977. };
  11978. /**
  11979. * Binds the frame buffer to the specified texture.
  11980. * @param texture The texture to render to or null for the default canvas
  11981. * @param faceIndex The face of the texture to render to in case of cube texture
  11982. * @param requiredWidth The width of the target to render to
  11983. * @param requiredHeight The height of the target to render to
  11984. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11985. * @param depthStencilTexture The depth stencil texture to use to render
  11986. */
  11987. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11988. if (this._currentRenderTarget) {
  11989. this.unBindFramebuffer(this._currentRenderTarget);
  11990. }
  11991. this._currentRenderTarget = texture;
  11992. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11993. var gl = this._gl;
  11994. if (texture.isCube) {
  11995. if (faceIndex === undefined) {
  11996. faceIndex = 0;
  11997. }
  11998. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11999. if (depthStencilTexture) {
  12000. if (depthStencilTexture._generateStencilBuffer) {
  12001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12002. }
  12003. else {
  12004. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12005. }
  12006. }
  12007. }
  12008. if (this._cachedViewport && !forceFullscreenViewport) {
  12009. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12010. }
  12011. else {
  12012. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12013. }
  12014. this.wipeCaches();
  12015. };
  12016. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12017. if (this._currentFramebuffer !== framebuffer) {
  12018. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12019. this._currentFramebuffer = framebuffer;
  12020. }
  12021. };
  12022. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12023. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12024. this._currentRenderTarget = null;
  12025. // If MSAA, we need to bitblt back to main texture
  12026. var gl = this._gl;
  12027. if (texture._MSAAFramebuffer) {
  12028. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12029. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12030. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12031. }
  12032. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12033. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12034. gl.generateMipmap(gl.TEXTURE_2D);
  12035. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12036. }
  12037. if (onBeforeUnbind) {
  12038. if (texture._MSAAFramebuffer) {
  12039. // Bind the correct framebuffer
  12040. this.bindUnboundFramebuffer(texture._framebuffer);
  12041. }
  12042. onBeforeUnbind();
  12043. }
  12044. this.bindUnboundFramebuffer(null);
  12045. };
  12046. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12047. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12048. this._currentRenderTarget = null;
  12049. // If MSAA, we need to bitblt back to main texture
  12050. var gl = this._gl;
  12051. if (textures[0]._MSAAFramebuffer) {
  12052. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12053. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12054. var attachments = textures[0]._attachments;
  12055. if (!attachments) {
  12056. attachments = new Array(textures.length);
  12057. textures[0]._attachments = attachments;
  12058. }
  12059. for (var i = 0; i < textures.length; i++) {
  12060. var texture = textures[i];
  12061. for (var j = 0; j < attachments.length; j++) {
  12062. attachments[j] = gl.NONE;
  12063. }
  12064. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12065. gl.readBuffer(attachments[i]);
  12066. gl.drawBuffers(attachments);
  12067. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12068. }
  12069. for (var i = 0; i < attachments.length; i++) {
  12070. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12071. }
  12072. gl.drawBuffers(attachments);
  12073. }
  12074. for (var i = 0; i < textures.length; i++) {
  12075. var texture = textures[i];
  12076. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12077. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12078. gl.generateMipmap(gl.TEXTURE_2D);
  12079. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12080. }
  12081. }
  12082. if (onBeforeUnbind) {
  12083. if (textures[0]._MSAAFramebuffer) {
  12084. // Bind the correct framebuffer
  12085. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12086. }
  12087. onBeforeUnbind();
  12088. }
  12089. this.bindUnboundFramebuffer(null);
  12090. };
  12091. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12092. if (texture.generateMipMaps) {
  12093. var gl = this._gl;
  12094. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12095. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12096. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12097. }
  12098. };
  12099. Engine.prototype.flushFramebuffer = function () {
  12100. this._gl.flush();
  12101. };
  12102. Engine.prototype.restoreDefaultFramebuffer = function () {
  12103. if (this._currentRenderTarget) {
  12104. this.unBindFramebuffer(this._currentRenderTarget);
  12105. }
  12106. else {
  12107. this.bindUnboundFramebuffer(null);
  12108. }
  12109. if (this._cachedViewport) {
  12110. this.setViewport(this._cachedViewport);
  12111. }
  12112. this.wipeCaches();
  12113. };
  12114. // UBOs
  12115. Engine.prototype.createUniformBuffer = function (elements) {
  12116. var ubo = this._gl.createBuffer();
  12117. if (!ubo) {
  12118. throw new Error("Unable to create uniform buffer");
  12119. }
  12120. this.bindUniformBuffer(ubo);
  12121. if (elements instanceof Float32Array) {
  12122. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12123. }
  12124. else {
  12125. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12126. }
  12127. this.bindUniformBuffer(null);
  12128. ubo.references = 1;
  12129. return ubo;
  12130. };
  12131. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12132. var ubo = this._gl.createBuffer();
  12133. if (!ubo) {
  12134. throw new Error("Unable to create dynamic uniform buffer");
  12135. }
  12136. this.bindUniformBuffer(ubo);
  12137. if (elements instanceof Float32Array) {
  12138. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12139. }
  12140. else {
  12141. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12142. }
  12143. this.bindUniformBuffer(null);
  12144. ubo.references = 1;
  12145. return ubo;
  12146. };
  12147. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12148. this.bindUniformBuffer(uniformBuffer);
  12149. if (offset === undefined) {
  12150. offset = 0;
  12151. }
  12152. if (count === undefined) {
  12153. if (elements instanceof Float32Array) {
  12154. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12155. }
  12156. else {
  12157. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12158. }
  12159. }
  12160. else {
  12161. if (elements instanceof Float32Array) {
  12162. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12163. }
  12164. else {
  12165. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12166. }
  12167. }
  12168. this.bindUniformBuffer(null);
  12169. };
  12170. // VBOs
  12171. Engine.prototype._resetVertexBufferBinding = function () {
  12172. this.bindArrayBuffer(null);
  12173. this._cachedVertexBuffers = null;
  12174. };
  12175. Engine.prototype.createVertexBuffer = function (vertices) {
  12176. var vbo = this._gl.createBuffer();
  12177. if (!vbo) {
  12178. throw new Error("Unable to create vertex buffer");
  12179. }
  12180. this.bindArrayBuffer(vbo);
  12181. if (vertices instanceof Float32Array) {
  12182. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12183. }
  12184. else {
  12185. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12186. }
  12187. this._resetVertexBufferBinding();
  12188. vbo.references = 1;
  12189. return vbo;
  12190. };
  12191. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12192. var vbo = this._gl.createBuffer();
  12193. if (!vbo) {
  12194. throw new Error("Unable to create dynamic vertex buffer");
  12195. }
  12196. this.bindArrayBuffer(vbo);
  12197. if (vertices instanceof Float32Array) {
  12198. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12199. }
  12200. else {
  12201. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12202. }
  12203. this._resetVertexBufferBinding();
  12204. vbo.references = 1;
  12205. return vbo;
  12206. };
  12207. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12208. if (offset === void 0) { offset = 0; }
  12209. // Force cache update
  12210. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12211. this.bindIndexBuffer(indexBuffer);
  12212. var arrayBuffer;
  12213. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12214. arrayBuffer = indices;
  12215. }
  12216. else {
  12217. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12218. }
  12219. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12220. this._resetIndexBufferBinding();
  12221. };
  12222. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12223. this.bindArrayBuffer(vertexBuffer);
  12224. if (offset === undefined) {
  12225. offset = 0;
  12226. }
  12227. if (count === undefined) {
  12228. if (vertices instanceof Float32Array) {
  12229. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12230. }
  12231. else {
  12232. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12233. }
  12234. }
  12235. else {
  12236. if (vertices instanceof Float32Array) {
  12237. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12238. }
  12239. else {
  12240. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12241. }
  12242. }
  12243. this._resetVertexBufferBinding();
  12244. };
  12245. Engine.prototype._resetIndexBufferBinding = function () {
  12246. this.bindIndexBuffer(null);
  12247. this._cachedIndexBuffer = null;
  12248. };
  12249. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12250. var vbo = this._gl.createBuffer();
  12251. if (!vbo) {
  12252. throw new Error("Unable to create index buffer");
  12253. }
  12254. this.bindIndexBuffer(vbo);
  12255. // Check for 32 bits indices
  12256. var arrayBuffer;
  12257. var need32Bits = false;
  12258. if (indices instanceof Uint16Array) {
  12259. arrayBuffer = indices;
  12260. }
  12261. else {
  12262. //check 32 bit support
  12263. if (this._caps.uintIndices) {
  12264. if (indices instanceof Uint32Array) {
  12265. arrayBuffer = indices;
  12266. need32Bits = true;
  12267. }
  12268. else {
  12269. //number[] or Int32Array, check if 32 bit is necessary
  12270. for (var index = 0; index < indices.length; index++) {
  12271. if (indices[index] > 65535) {
  12272. need32Bits = true;
  12273. break;
  12274. }
  12275. }
  12276. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12277. }
  12278. }
  12279. else {
  12280. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12281. arrayBuffer = new Uint16Array(indices);
  12282. }
  12283. }
  12284. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12285. this._resetIndexBufferBinding();
  12286. vbo.references = 1;
  12287. vbo.is32Bits = need32Bits;
  12288. return vbo;
  12289. };
  12290. Engine.prototype.bindArrayBuffer = function (buffer) {
  12291. if (!this._vaoRecordInProgress) {
  12292. this._unbindVertexArrayObject();
  12293. }
  12294. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12295. };
  12296. Engine.prototype.bindUniformBuffer = function (buffer) {
  12297. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12298. };
  12299. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12300. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12301. };
  12302. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12303. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12304. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12305. };
  12306. ;
  12307. Engine.prototype.bindIndexBuffer = function (buffer) {
  12308. if (!this._vaoRecordInProgress) {
  12309. this._unbindVertexArrayObject();
  12310. }
  12311. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12312. };
  12313. Engine.prototype.bindBuffer = function (buffer, target) {
  12314. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12315. this._gl.bindBuffer(target, buffer);
  12316. this._currentBoundBuffer[target] = buffer;
  12317. }
  12318. };
  12319. Engine.prototype.updateArrayBuffer = function (data) {
  12320. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12321. };
  12322. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12323. var pointer = this._currentBufferPointers[indx];
  12324. var changed = false;
  12325. if (!pointer.active) {
  12326. changed = true;
  12327. pointer.active = true;
  12328. pointer.index = indx;
  12329. pointer.size = size;
  12330. pointer.type = type;
  12331. pointer.normalized = normalized;
  12332. pointer.stride = stride;
  12333. pointer.offset = offset;
  12334. pointer.buffer = buffer;
  12335. }
  12336. else {
  12337. if (pointer.buffer !== buffer) {
  12338. pointer.buffer = buffer;
  12339. changed = true;
  12340. }
  12341. if (pointer.size !== size) {
  12342. pointer.size = size;
  12343. changed = true;
  12344. }
  12345. if (pointer.type !== type) {
  12346. pointer.type = type;
  12347. changed = true;
  12348. }
  12349. if (pointer.normalized !== normalized) {
  12350. pointer.normalized = normalized;
  12351. changed = true;
  12352. }
  12353. if (pointer.stride !== stride) {
  12354. pointer.stride = stride;
  12355. changed = true;
  12356. }
  12357. if (pointer.offset !== offset) {
  12358. pointer.offset = offset;
  12359. changed = true;
  12360. }
  12361. }
  12362. if (changed || this._vaoRecordInProgress) {
  12363. this.bindArrayBuffer(buffer);
  12364. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12365. }
  12366. };
  12367. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12368. if (indexBuffer == null) {
  12369. return;
  12370. }
  12371. if (this._cachedIndexBuffer !== indexBuffer) {
  12372. this._cachedIndexBuffer = indexBuffer;
  12373. this.bindIndexBuffer(indexBuffer);
  12374. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12375. }
  12376. };
  12377. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12378. var attributes = effect.getAttributesNames();
  12379. if (!this._vaoRecordInProgress) {
  12380. this._unbindVertexArrayObject();
  12381. }
  12382. this.unbindAllAttributes();
  12383. for (var index = 0; index < attributes.length; index++) {
  12384. var order = effect.getAttributeLocation(index);
  12385. if (order >= 0) {
  12386. var vertexBuffer = vertexBuffers[attributes[index]];
  12387. if (!vertexBuffer) {
  12388. continue;
  12389. }
  12390. this._gl.enableVertexAttribArray(order);
  12391. if (!this._vaoRecordInProgress) {
  12392. this._vertexAttribArraysEnabled[order] = true;
  12393. }
  12394. var buffer = vertexBuffer.getBuffer();
  12395. if (buffer) {
  12396. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12397. if (vertexBuffer.getIsInstanced()) {
  12398. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12399. if (!this._vaoRecordInProgress) {
  12400. this._currentInstanceLocations.push(order);
  12401. this._currentInstanceBuffers.push(buffer);
  12402. }
  12403. }
  12404. }
  12405. }
  12406. }
  12407. };
  12408. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12409. var vao = this._gl.createVertexArray();
  12410. this._vaoRecordInProgress = true;
  12411. this._gl.bindVertexArray(vao);
  12412. this._mustWipeVertexAttributes = true;
  12413. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12414. this.bindIndexBuffer(indexBuffer);
  12415. this._vaoRecordInProgress = false;
  12416. this._gl.bindVertexArray(null);
  12417. return vao;
  12418. };
  12419. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12420. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12421. this._cachedVertexArrayObject = vertexArrayObject;
  12422. this._gl.bindVertexArray(vertexArrayObject);
  12423. this._cachedVertexBuffers = null;
  12424. this._cachedIndexBuffer = null;
  12425. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12426. this._mustWipeVertexAttributes = true;
  12427. }
  12428. };
  12429. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12430. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12431. this._cachedVertexBuffers = vertexBuffer;
  12432. this._cachedEffectForVertexBuffers = effect;
  12433. var attributesCount = effect.getAttributesCount();
  12434. this._unbindVertexArrayObject();
  12435. this.unbindAllAttributes();
  12436. var offset = 0;
  12437. for (var index = 0; index < attributesCount; index++) {
  12438. if (index < vertexDeclaration.length) {
  12439. var order = effect.getAttributeLocation(index);
  12440. if (order >= 0) {
  12441. this._gl.enableVertexAttribArray(order);
  12442. this._vertexAttribArraysEnabled[order] = true;
  12443. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12444. }
  12445. offset += vertexDeclaration[index] * 4;
  12446. }
  12447. }
  12448. }
  12449. this._bindIndexBufferWithCache(indexBuffer);
  12450. };
  12451. Engine.prototype._unbindVertexArrayObject = function () {
  12452. if (!this._cachedVertexArrayObject) {
  12453. return;
  12454. }
  12455. this._cachedVertexArrayObject = null;
  12456. this._gl.bindVertexArray(null);
  12457. };
  12458. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12459. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12460. this._cachedVertexBuffers = vertexBuffers;
  12461. this._cachedEffectForVertexBuffers = effect;
  12462. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12463. }
  12464. this._bindIndexBufferWithCache(indexBuffer);
  12465. };
  12466. Engine.prototype.unbindInstanceAttributes = function () {
  12467. var boundBuffer;
  12468. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12469. var instancesBuffer = this._currentInstanceBuffers[i];
  12470. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12471. boundBuffer = instancesBuffer;
  12472. this.bindArrayBuffer(instancesBuffer);
  12473. }
  12474. var offsetLocation = this._currentInstanceLocations[i];
  12475. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12476. }
  12477. this._currentInstanceBuffers.length = 0;
  12478. this._currentInstanceLocations.length = 0;
  12479. };
  12480. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12481. this._gl.deleteVertexArray(vao);
  12482. };
  12483. Engine.prototype._releaseBuffer = function (buffer) {
  12484. buffer.references--;
  12485. if (buffer.references === 0) {
  12486. this._gl.deleteBuffer(buffer);
  12487. return true;
  12488. }
  12489. return false;
  12490. };
  12491. Engine.prototype.createInstancesBuffer = function (capacity) {
  12492. var buffer = this._gl.createBuffer();
  12493. if (!buffer) {
  12494. throw new Error("Unable to create instance buffer");
  12495. }
  12496. buffer.capacity = capacity;
  12497. this.bindArrayBuffer(buffer);
  12498. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12499. return buffer;
  12500. };
  12501. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12502. this._gl.deleteBuffer(buffer);
  12503. };
  12504. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12505. this.bindArrayBuffer(instancesBuffer);
  12506. if (data) {
  12507. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12508. }
  12509. if (offsetLocations[0].index !== undefined) {
  12510. var stride = 0;
  12511. for (var i = 0; i < offsetLocations.length; i++) {
  12512. var ai = offsetLocations[i];
  12513. stride += ai.attributeSize * 4;
  12514. }
  12515. for (var i = 0; i < offsetLocations.length; i++) {
  12516. var ai = offsetLocations[i];
  12517. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12518. this._gl.enableVertexAttribArray(ai.index);
  12519. this._vertexAttribArraysEnabled[ai.index] = true;
  12520. }
  12521. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12522. this._gl.vertexAttribDivisor(ai.index, 1);
  12523. this._currentInstanceLocations.push(ai.index);
  12524. this._currentInstanceBuffers.push(instancesBuffer);
  12525. }
  12526. }
  12527. else {
  12528. for (var index = 0; index < 4; index++) {
  12529. var offsetLocation = offsetLocations[index];
  12530. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12531. this._gl.enableVertexAttribArray(offsetLocation);
  12532. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12533. }
  12534. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12535. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12536. this._currentInstanceLocations.push(offsetLocation);
  12537. this._currentInstanceBuffers.push(instancesBuffer);
  12538. }
  12539. }
  12540. };
  12541. Engine.prototype.applyStates = function () {
  12542. this._depthCullingState.apply(this._gl);
  12543. this._stencilState.apply(this._gl);
  12544. this._alphaState.apply(this._gl);
  12545. };
  12546. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12547. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12548. };
  12549. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12550. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12551. };
  12552. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12553. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12554. };
  12555. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12556. // Apply states
  12557. this.applyStates();
  12558. this._drawCalls.addCount(1, false);
  12559. // Render
  12560. var drawMode = this._drawMode(fillMode);
  12561. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12562. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12563. if (instancesCount) {
  12564. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12565. }
  12566. else {
  12567. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12568. }
  12569. };
  12570. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12571. // Apply states
  12572. this.applyStates();
  12573. this._drawCalls.addCount(1, false);
  12574. var drawMode = this._drawMode(fillMode);
  12575. if (instancesCount) {
  12576. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12577. }
  12578. else {
  12579. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12580. }
  12581. };
  12582. Engine.prototype._drawMode = function (fillMode) {
  12583. switch (fillMode) {
  12584. // Triangle views
  12585. case BABYLON.Material.TriangleFillMode:
  12586. return this._gl.TRIANGLES;
  12587. case BABYLON.Material.PointFillMode:
  12588. return this._gl.POINTS;
  12589. case BABYLON.Material.WireFrameFillMode:
  12590. return this._gl.LINES;
  12591. // Draw modes
  12592. case BABYLON.Material.PointListDrawMode:
  12593. return this._gl.POINTS;
  12594. case BABYLON.Material.LineListDrawMode:
  12595. return this._gl.LINES;
  12596. case BABYLON.Material.LineLoopDrawMode:
  12597. return this._gl.LINE_LOOP;
  12598. case BABYLON.Material.LineStripDrawMode:
  12599. return this._gl.LINE_STRIP;
  12600. case BABYLON.Material.TriangleStripDrawMode:
  12601. return this._gl.TRIANGLE_STRIP;
  12602. case BABYLON.Material.TriangleFanDrawMode:
  12603. return this._gl.TRIANGLE_FAN;
  12604. default:
  12605. return this._gl.TRIANGLES;
  12606. }
  12607. };
  12608. // Shaders
  12609. Engine.prototype._releaseEffect = function (effect) {
  12610. if (this._compiledEffects[effect._key]) {
  12611. delete this._compiledEffects[effect._key];
  12612. this._deleteProgram(effect.getProgram());
  12613. }
  12614. };
  12615. Engine.prototype._deleteProgram = function (program) {
  12616. if (program) {
  12617. program.__SPECTOR_rebuildProgram = null;
  12618. if (program.transformFeedback) {
  12619. this.deleteTransformFeedback(program.transformFeedback);
  12620. program.transformFeedback = null;
  12621. }
  12622. this._gl.deleteProgram(program);
  12623. }
  12624. };
  12625. /**
  12626. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12627. * @param samplers An array of string used to represent textures
  12628. */
  12629. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12630. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12631. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12632. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12633. if (this._compiledEffects[name]) {
  12634. var compiledEffect = this._compiledEffects[name];
  12635. if (onCompiled && compiledEffect.isReady()) {
  12636. onCompiled(compiledEffect);
  12637. }
  12638. return compiledEffect;
  12639. }
  12640. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12641. effect._key = name;
  12642. this._compiledEffects[name] = effect;
  12643. return effect;
  12644. };
  12645. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12646. if (uniformsNames === void 0) { uniformsNames = []; }
  12647. if (samplers === void 0) { samplers = []; }
  12648. if (defines === void 0) { defines = ""; }
  12649. return this.createEffect({
  12650. vertex: "particles",
  12651. fragmentElement: fragmentName
  12652. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12653. };
  12654. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12655. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12656. context = context || this._gl;
  12657. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12658. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12659. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12660. };
  12661. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12662. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12663. context = context || this._gl;
  12664. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12665. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12666. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12667. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12668. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12669. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12670. return program;
  12671. };
  12672. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12673. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12674. var shaderProgram = context.createProgram();
  12675. if (!shaderProgram) {
  12676. throw new Error("Unable to create program");
  12677. }
  12678. context.attachShader(shaderProgram, vertexShader);
  12679. context.attachShader(shaderProgram, fragmentShader);
  12680. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12681. var transformFeedback = this.createTransformFeedback();
  12682. this.bindTransformFeedback(transformFeedback);
  12683. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12684. shaderProgram.transformFeedback = transformFeedback;
  12685. }
  12686. context.linkProgram(shaderProgram);
  12687. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12688. this.bindTransformFeedback(null);
  12689. }
  12690. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12691. if (!linked) {
  12692. context.validateProgram(shaderProgram);
  12693. var error = context.getProgramInfoLog(shaderProgram);
  12694. if (error) {
  12695. throw new Error(error);
  12696. }
  12697. }
  12698. context.deleteShader(vertexShader);
  12699. context.deleteShader(fragmentShader);
  12700. return shaderProgram;
  12701. };
  12702. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12703. var results = new Array();
  12704. for (var index = 0; index < uniformsNames.length; index++) {
  12705. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12706. }
  12707. return results;
  12708. };
  12709. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12710. var results = [];
  12711. for (var index = 0; index < attributesNames.length; index++) {
  12712. try {
  12713. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12714. }
  12715. catch (e) {
  12716. results.push(-1);
  12717. }
  12718. }
  12719. return results;
  12720. };
  12721. Engine.prototype.enableEffect = function (effect) {
  12722. if (!effect) {
  12723. return;
  12724. }
  12725. // Use program
  12726. this.bindSamplers(effect);
  12727. this._currentEffect = effect;
  12728. if (effect.onBind) {
  12729. effect.onBind(effect);
  12730. }
  12731. effect.onBindObservable.notifyObservers(effect);
  12732. };
  12733. Engine.prototype.setIntArray = function (uniform, array) {
  12734. if (!uniform)
  12735. return;
  12736. this._gl.uniform1iv(uniform, array);
  12737. };
  12738. Engine.prototype.setIntArray2 = function (uniform, array) {
  12739. if (!uniform || array.length % 2 !== 0)
  12740. return;
  12741. this._gl.uniform2iv(uniform, array);
  12742. };
  12743. Engine.prototype.setIntArray3 = function (uniform, array) {
  12744. if (!uniform || array.length % 3 !== 0)
  12745. return;
  12746. this._gl.uniform3iv(uniform, array);
  12747. };
  12748. Engine.prototype.setIntArray4 = function (uniform, array) {
  12749. if (!uniform || array.length % 4 !== 0)
  12750. return;
  12751. this._gl.uniform4iv(uniform, array);
  12752. };
  12753. Engine.prototype.setFloatArray = function (uniform, array) {
  12754. if (!uniform)
  12755. return;
  12756. this._gl.uniform1fv(uniform, array);
  12757. };
  12758. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12759. if (!uniform || array.length % 2 !== 0)
  12760. return;
  12761. this._gl.uniform2fv(uniform, array);
  12762. };
  12763. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12764. if (!uniform || array.length % 3 !== 0)
  12765. return;
  12766. this._gl.uniform3fv(uniform, array);
  12767. };
  12768. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12769. if (!uniform || array.length % 4 !== 0)
  12770. return;
  12771. this._gl.uniform4fv(uniform, array);
  12772. };
  12773. Engine.prototype.setArray = function (uniform, array) {
  12774. if (!uniform)
  12775. return;
  12776. this._gl.uniform1fv(uniform, array);
  12777. };
  12778. Engine.prototype.setArray2 = function (uniform, array) {
  12779. if (!uniform || array.length % 2 !== 0)
  12780. return;
  12781. this._gl.uniform2fv(uniform, array);
  12782. };
  12783. Engine.prototype.setArray3 = function (uniform, array) {
  12784. if (!uniform || array.length % 3 !== 0)
  12785. return;
  12786. this._gl.uniform3fv(uniform, array);
  12787. };
  12788. Engine.prototype.setArray4 = function (uniform, array) {
  12789. if (!uniform || array.length % 4 !== 0)
  12790. return;
  12791. this._gl.uniform4fv(uniform, array);
  12792. };
  12793. Engine.prototype.setMatrices = function (uniform, matrices) {
  12794. if (!uniform)
  12795. return;
  12796. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12797. };
  12798. Engine.prototype.setMatrix = function (uniform, matrix) {
  12799. if (!uniform)
  12800. return;
  12801. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12802. };
  12803. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12804. if (!uniform)
  12805. return;
  12806. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12807. };
  12808. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12809. if (!uniform)
  12810. return;
  12811. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12812. };
  12813. Engine.prototype.setInt = function (uniform, value) {
  12814. if (!uniform)
  12815. return;
  12816. this._gl.uniform1i(uniform, value);
  12817. };
  12818. Engine.prototype.setFloat = function (uniform, value) {
  12819. if (!uniform)
  12820. return;
  12821. this._gl.uniform1f(uniform, value);
  12822. };
  12823. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12824. if (!uniform)
  12825. return;
  12826. this._gl.uniform2f(uniform, x, y);
  12827. };
  12828. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12829. if (!uniform)
  12830. return;
  12831. this._gl.uniform3f(uniform, x, y, z);
  12832. };
  12833. Engine.prototype.setBool = function (uniform, bool) {
  12834. if (!uniform)
  12835. return;
  12836. this._gl.uniform1i(uniform, bool);
  12837. };
  12838. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12839. if (!uniform)
  12840. return;
  12841. this._gl.uniform4f(uniform, x, y, z, w);
  12842. };
  12843. Engine.prototype.setColor3 = function (uniform, color3) {
  12844. if (!uniform)
  12845. return;
  12846. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12847. };
  12848. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12849. if (!uniform)
  12850. return;
  12851. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12852. };
  12853. /**
  12854. * Sets a Color4 on a uniform variable
  12855. * @param uniform defines the uniform location
  12856. * @param color4 defines the value to be set
  12857. */
  12858. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12859. if (!uniform)
  12860. return;
  12861. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12862. };
  12863. // States
  12864. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12865. if (zOffset === void 0) { zOffset = 0; }
  12866. if (reverseSide === void 0) { reverseSide = false; }
  12867. // Culling
  12868. if (this._depthCullingState.cull !== culling || force) {
  12869. this._depthCullingState.cull = culling;
  12870. }
  12871. // Cull face
  12872. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12873. if (this._depthCullingState.cullFace !== cullFace || force) {
  12874. this._depthCullingState.cullFace = cullFace;
  12875. }
  12876. // Z offset
  12877. this.setZOffset(zOffset);
  12878. // Front face
  12879. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12880. if (this._depthCullingState.frontFace !== frontFace || force) {
  12881. this._depthCullingState.frontFace = frontFace;
  12882. }
  12883. };
  12884. Engine.prototype.setZOffset = function (value) {
  12885. this._depthCullingState.zOffset = value;
  12886. };
  12887. Engine.prototype.getZOffset = function () {
  12888. return this._depthCullingState.zOffset;
  12889. };
  12890. Engine.prototype.setDepthBuffer = function (enable) {
  12891. this._depthCullingState.depthTest = enable;
  12892. };
  12893. Engine.prototype.getDepthWrite = function () {
  12894. return this._depthCullingState.depthMask;
  12895. };
  12896. Engine.prototype.setDepthWrite = function (enable) {
  12897. this._depthCullingState.depthMask = enable;
  12898. };
  12899. Engine.prototype.setColorWrite = function (enable) {
  12900. this._gl.colorMask(enable, enable, enable, enable);
  12901. this._colorWrite = enable;
  12902. };
  12903. Engine.prototype.getColorWrite = function () {
  12904. return this._colorWrite;
  12905. };
  12906. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12907. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12908. };
  12909. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12910. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12911. if (this._alphaMode === mode) {
  12912. return;
  12913. }
  12914. switch (mode) {
  12915. case Engine.ALPHA_DISABLE:
  12916. this._alphaState.alphaBlend = false;
  12917. break;
  12918. case Engine.ALPHA_PREMULTIPLIED:
  12919. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12920. this._alphaState.alphaBlend = true;
  12921. break;
  12922. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12923. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12924. this._alphaState.alphaBlend = true;
  12925. break;
  12926. case Engine.ALPHA_COMBINE:
  12927. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12928. this._alphaState.alphaBlend = true;
  12929. break;
  12930. case Engine.ALPHA_ONEONE:
  12931. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12932. this._alphaState.alphaBlend = true;
  12933. break;
  12934. case Engine.ALPHA_ADD:
  12935. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12936. this._alphaState.alphaBlend = true;
  12937. break;
  12938. case Engine.ALPHA_SUBTRACT:
  12939. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12940. this._alphaState.alphaBlend = true;
  12941. break;
  12942. case Engine.ALPHA_MULTIPLY:
  12943. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12944. this._alphaState.alphaBlend = true;
  12945. break;
  12946. case Engine.ALPHA_MAXIMIZED:
  12947. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12948. this._alphaState.alphaBlend = true;
  12949. break;
  12950. case Engine.ALPHA_INTERPOLATE:
  12951. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12952. this._alphaState.alphaBlend = true;
  12953. break;
  12954. case Engine.ALPHA_SCREENMODE:
  12955. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12956. this._alphaState.alphaBlend = true;
  12957. break;
  12958. }
  12959. if (!noDepthWriteChange) {
  12960. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12961. }
  12962. this._alphaMode = mode;
  12963. };
  12964. Engine.prototype.getAlphaMode = function () {
  12965. return this._alphaMode;
  12966. };
  12967. // Textures
  12968. Engine.prototype.wipeCaches = function (bruteForce) {
  12969. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12970. return;
  12971. }
  12972. this._currentEffect = null;
  12973. // 6/8/2017: deltakosh: Should not be required anymore.
  12974. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12975. if (bruteForce) {
  12976. this.resetTextureCache();
  12977. this._currentProgram = null;
  12978. this._stencilState.reset();
  12979. this._depthCullingState.reset();
  12980. this.setDepthFunctionToLessOrEqual();
  12981. this._alphaState.reset();
  12982. }
  12983. this._resetVertexBufferBinding();
  12984. this._cachedIndexBuffer = null;
  12985. this._cachedEffectForVertexBuffers = null;
  12986. this._unbindVertexArrayObject();
  12987. this.bindIndexBuffer(null);
  12988. };
  12989. /**
  12990. * Set the compressed texture format to use, based on the formats you have, and the formats
  12991. * supported by the hardware / browser.
  12992. *
  12993. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12994. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12995. * to API arguments needed to compressed textures. This puts the burden on the container
  12996. * generator to house the arcane code for determining these for current & future formats.
  12997. *
  12998. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12999. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13000. *
  13001. * Note: The result of this call is not taken into account when a texture is base64.
  13002. *
  13003. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13004. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13005. *
  13006. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13007. * @returns The extension selected.
  13008. */
  13009. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13010. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13011. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13012. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13013. return this._textureFormatInUse = this._texturesSupported[i];
  13014. }
  13015. }
  13016. }
  13017. // actively set format to nothing, to allow this to be called more than once
  13018. // and possibly fail the 2nd time
  13019. this._textureFormatInUse = null;
  13020. return null;
  13021. };
  13022. Engine.prototype._createTexture = function () {
  13023. var texture = this._gl.createTexture();
  13024. if (!texture) {
  13025. throw new Error("Unable to create texture");
  13026. }
  13027. return texture;
  13028. };
  13029. /**
  13030. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13031. * @param {string} urlArg- This contains one of the following:
  13032. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13033. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13034. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13035. *
  13036. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13037. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13038. * @param {Scene} scene- Needed for loading to the correct scene.
  13039. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13040. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13041. * @param {callback} onError- Optional callback to be called upon failure.
  13042. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13043. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13044. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13045. *
  13046. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13047. */
  13048. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13049. var _this = this;
  13050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13051. if (onLoad === void 0) { onLoad = null; }
  13052. if (onError === void 0) { onError = null; }
  13053. if (buffer === void 0) { buffer = null; }
  13054. if (fallBack === void 0) { fallBack = null; }
  13055. if (format === void 0) { format = null; }
  13056. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13057. var fromData = url.substr(0, 5) === "data:";
  13058. var fromBlob = url.substr(0, 5) === "blob:";
  13059. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13060. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13061. // establish the file extension, if possible
  13062. var lastDot = url.lastIndexOf('.');
  13063. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13064. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13065. var isTGA = (extension.indexOf(".tga") === 0);
  13066. // determine if a ktx file should be substituted
  13067. var isKTX = false;
  13068. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13069. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13070. isKTX = true;
  13071. }
  13072. if (scene) {
  13073. scene._addPendingData(texture);
  13074. }
  13075. texture.url = url;
  13076. texture.generateMipMaps = !noMipmap;
  13077. texture.samplingMode = samplingMode;
  13078. texture.invertY = invertY;
  13079. if (!this._doNotHandleContextLost) {
  13080. // Keep a link to the buffer only if we plan to handle context lost
  13081. texture._buffer = buffer;
  13082. }
  13083. var onLoadObserver = null;
  13084. if (onLoad && !fallBack) {
  13085. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13086. }
  13087. if (!fallBack)
  13088. this._internalTexturesCache.push(texture);
  13089. var onerror = function (message, exception) {
  13090. if (scene) {
  13091. scene._removePendingData(texture);
  13092. }
  13093. if (onLoadObserver) {
  13094. texture.onLoadedObservable.remove(onLoadObserver);
  13095. }
  13096. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13097. if (isKTX) {
  13098. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13099. }
  13100. else if (BABYLON.Tools.UseFallbackTexture) {
  13101. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13102. }
  13103. if (onError) {
  13104. onError(message || "Unknown error", exception);
  13105. }
  13106. };
  13107. var callback = null;
  13108. // processing for non-image formats
  13109. if (isKTX || isTGA || isDDS) {
  13110. if (isKTX) {
  13111. callback = function (data) {
  13112. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13113. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13114. ktx.uploadLevels(_this._gl, !noMipmap);
  13115. return false;
  13116. }, samplingMode);
  13117. };
  13118. }
  13119. else if (isTGA) {
  13120. callback = function (arrayBuffer) {
  13121. var data = new Uint8Array(arrayBuffer);
  13122. var header = BABYLON.TGATools.GetTGAHeader(data);
  13123. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13124. BABYLON.TGATools.UploadContent(_this._gl, data);
  13125. return false;
  13126. }, samplingMode);
  13127. };
  13128. }
  13129. else if (isDDS) {
  13130. callback = function (data) {
  13131. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13132. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13133. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13134. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13135. return false;
  13136. }, samplingMode);
  13137. };
  13138. }
  13139. if (!buffer) {
  13140. this._loadFile(url, function (data) {
  13141. if (callback) {
  13142. callback(data);
  13143. }
  13144. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13145. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13146. });
  13147. }
  13148. else {
  13149. if (callback) {
  13150. callback(buffer);
  13151. }
  13152. }
  13153. // image format processing
  13154. }
  13155. else {
  13156. var onload = function (img) {
  13157. if (fromBlob && !_this._doNotHandleContextLost) {
  13158. // We need to store the image if we need to rebuild the texture
  13159. // in case of a webgl context lost
  13160. texture._buffer = img;
  13161. }
  13162. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13163. var gl = _this._gl;
  13164. var isPot = (img.width === potWidth && img.height === potHeight);
  13165. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13166. if (isPot) {
  13167. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13168. return false;
  13169. }
  13170. // Using shaders to rescale because canvas.drawImage is lossy
  13171. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13172. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13173. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13178. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13179. _this._releaseTexture(source);
  13180. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13181. continuationCallback();
  13182. });
  13183. return true;
  13184. }, samplingMode);
  13185. };
  13186. if (!fromData || isBase64)
  13187. if (buffer instanceof HTMLImageElement) {
  13188. onload(buffer);
  13189. }
  13190. else {
  13191. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13192. }
  13193. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13194. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13195. else
  13196. onload(buffer);
  13197. }
  13198. return texture;
  13199. };
  13200. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13201. var _this = this;
  13202. var rtt = this.createRenderTargetTexture({
  13203. width: destination.width,
  13204. height: destination.height,
  13205. }, {
  13206. generateMipMaps: false,
  13207. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13208. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13209. generateDepthBuffer: false,
  13210. generateStencilBuffer: false
  13211. });
  13212. if (!this._rescalePostProcess) {
  13213. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13214. }
  13215. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13216. _this._rescalePostProcess.onApply = function (effect) {
  13217. effect._bindTexture("textureSampler", source);
  13218. };
  13219. var hostingScene = scene;
  13220. if (!hostingScene) {
  13221. hostingScene = _this.scenes[_this.scenes.length - 1];
  13222. }
  13223. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13224. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13225. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13226. _this.unBindFramebuffer(rtt);
  13227. _this._releaseTexture(rtt);
  13228. if (onComplete) {
  13229. onComplete();
  13230. }
  13231. });
  13232. };
  13233. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13234. if (compression === void 0) { compression = null; }
  13235. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13236. if (!texture) {
  13237. return;
  13238. }
  13239. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13240. var internalFormat = this._getInternalFormat(format);
  13241. var textureType = this._getWebGLTextureType(type);
  13242. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13243. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13244. if (!this._doNotHandleContextLost) {
  13245. texture._bufferView = data;
  13246. texture.format = format;
  13247. texture.type = type;
  13248. texture.invertY = invertY;
  13249. texture._compression = compression;
  13250. }
  13251. if (texture.width % 4 !== 0) {
  13252. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13253. }
  13254. if (compression && data) {
  13255. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13256. }
  13257. else {
  13258. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13259. }
  13260. if (texture.generateMipMaps) {
  13261. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13262. }
  13263. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13264. // this.resetTextureCache();
  13265. texture.isReady = true;
  13266. };
  13267. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13268. if (compression === void 0) { compression = null; }
  13269. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13270. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13271. texture.baseWidth = width;
  13272. texture.baseHeight = height;
  13273. texture.width = width;
  13274. texture.height = height;
  13275. texture.format = format;
  13276. texture.generateMipMaps = generateMipMaps;
  13277. texture.samplingMode = samplingMode;
  13278. texture.invertY = invertY;
  13279. texture._compression = compression;
  13280. texture.type = type;
  13281. if (!this._doNotHandleContextLost) {
  13282. texture._bufferView = data;
  13283. }
  13284. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13285. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13286. // Filters
  13287. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13288. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13289. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13290. if (generateMipMaps) {
  13291. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13292. }
  13293. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13294. this._internalTexturesCache.push(texture);
  13295. return texture;
  13296. };
  13297. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13298. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13299. texture.baseWidth = width;
  13300. texture.baseHeight = height;
  13301. if (generateMipMaps) {
  13302. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13303. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13304. }
  13305. // this.resetTextureCache();
  13306. texture.width = width;
  13307. texture.height = height;
  13308. texture.isReady = false;
  13309. texture.generateMipMaps = generateMipMaps;
  13310. texture.samplingMode = samplingMode;
  13311. this.updateTextureSamplingMode(samplingMode, texture);
  13312. this._internalTexturesCache.push(texture);
  13313. return texture;
  13314. };
  13315. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13316. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13317. if (texture.isCube) {
  13318. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13319. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13320. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13321. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13322. }
  13323. else if (texture.is3D) {
  13324. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13325. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13326. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13327. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13328. }
  13329. else {
  13330. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13333. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13334. }
  13335. texture.samplingMode = samplingMode;
  13336. };
  13337. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13338. if (premulAlpha === void 0) { premulAlpha = false; }
  13339. if (!texture) {
  13340. return;
  13341. }
  13342. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13343. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13344. if (premulAlpha) {
  13345. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13346. }
  13347. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13348. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13349. if (texture.generateMipMaps) {
  13350. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13351. }
  13352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13353. if (premulAlpha) {
  13354. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13355. }
  13356. texture.isReady = true;
  13357. };
  13358. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13359. if (!texture || texture._isDisabled) {
  13360. return;
  13361. }
  13362. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13363. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13364. try {
  13365. // Testing video texture support
  13366. if (this._videoTextureSupported === undefined) {
  13367. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13368. if (this._gl.getError() !== 0) {
  13369. this._videoTextureSupported = false;
  13370. }
  13371. else {
  13372. this._videoTextureSupported = true;
  13373. }
  13374. }
  13375. // Copy video through the current working canvas if video texture is not supported
  13376. if (!this._videoTextureSupported) {
  13377. if (!texture._workingCanvas) {
  13378. texture._workingCanvas = document.createElement("canvas");
  13379. var context = texture._workingCanvas.getContext("2d");
  13380. if (!context) {
  13381. throw new Error("Unable to get 2d context");
  13382. }
  13383. texture._workingContext = context;
  13384. texture._workingCanvas.width = texture.width;
  13385. texture._workingCanvas.height = texture.height;
  13386. }
  13387. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13388. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13389. }
  13390. else {
  13391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13392. }
  13393. if (texture.generateMipMaps) {
  13394. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13395. }
  13396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13397. // this.resetTextureCache();
  13398. texture.isReady = true;
  13399. }
  13400. catch (ex) {
  13401. // Something unexpected
  13402. // Let's disable the texture
  13403. texture._isDisabled = true;
  13404. }
  13405. };
  13406. /**
  13407. * Updates a depth texture Comparison Mode and Function.
  13408. * If the comparison Function is equal to 0, the mode will be set to none.
  13409. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13410. * @param texture The texture to set the comparison function for
  13411. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13412. */
  13413. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13414. if (this.webGLVersion === 1) {
  13415. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13416. return;
  13417. }
  13418. var gl = this._gl;
  13419. if (texture.isCube) {
  13420. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13421. if (comparisonFunction === 0) {
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13424. }
  13425. else {
  13426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13428. }
  13429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13430. }
  13431. else {
  13432. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13433. if (comparisonFunction === 0) {
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13436. }
  13437. else {
  13438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13440. }
  13441. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13442. }
  13443. texture._comparisonFunction = comparisonFunction;
  13444. };
  13445. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13446. var width = size.width || size;
  13447. var height = size.height || size;
  13448. internalTexture.baseWidth = width;
  13449. internalTexture.baseHeight = height;
  13450. internalTexture.width = width;
  13451. internalTexture.height = height;
  13452. internalTexture.isReady = true;
  13453. internalTexture.samples = 1;
  13454. internalTexture.generateMipMaps = false;
  13455. internalTexture._generateDepthBuffer = true;
  13456. internalTexture._generateStencilBuffer = generateStencil;
  13457. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13458. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13459. internalTexture._comparisonFunction = comparisonFunction;
  13460. var gl = this._gl;
  13461. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13462. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13463. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13464. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13465. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13466. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13467. if (comparisonFunction === 0) {
  13468. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13469. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13470. }
  13471. else {
  13472. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13473. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13474. }
  13475. };
  13476. /**
  13477. * Creates a depth stencil texture.
  13478. * This is only available in WebGL 2 or with the depth texture extension available.
  13479. * @param size The size of face edge in the texture.
  13480. * @param options The options defining the texture.
  13481. * @returns The texture
  13482. */
  13483. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13484. if (options.isCube) {
  13485. var width = size.width || size;
  13486. return this._createDepthStencilCubeTexture(width, options);
  13487. }
  13488. else {
  13489. return this._createDepthStencilTexture(size, options);
  13490. }
  13491. };
  13492. /**
  13493. * Creates a depth stencil texture.
  13494. * This is only available in WebGL 2 or with the depth texture extension available.
  13495. * @param size The size of face edge in the texture.
  13496. * @param options The options defining the texture.
  13497. * @returns The texture
  13498. */
  13499. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13500. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13501. if (!this._caps.depthTextureExtension) {
  13502. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13503. return internalTexture;
  13504. }
  13505. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13506. var gl = this._gl;
  13507. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13508. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13509. if (this.webGLVersion > 1) {
  13510. if (internalOptions.generateStencil) {
  13511. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13512. }
  13513. else {
  13514. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13515. }
  13516. }
  13517. else {
  13518. if (internalOptions.generateStencil) {
  13519. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13520. }
  13521. else {
  13522. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13523. }
  13524. }
  13525. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13526. return internalTexture;
  13527. };
  13528. /**
  13529. * Creates a depth stencil cube texture.
  13530. * This is only available in WebGL 2.
  13531. * @param size The size of face edge in the cube texture.
  13532. * @param options The options defining the cube texture.
  13533. * @returns The cube texture
  13534. */
  13535. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13536. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13537. internalTexture.isCube = true;
  13538. if (this.webGLVersion === 1) {
  13539. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13540. return internalTexture;
  13541. }
  13542. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13543. var gl = this._gl;
  13544. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13545. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13546. // Create the depth/stencil buffer
  13547. for (var face = 0; face < 6; face++) {
  13548. if (internalOptions.generateStencil) {
  13549. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13550. }
  13551. else {
  13552. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13553. }
  13554. }
  13555. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13556. return internalTexture;
  13557. };
  13558. /**
  13559. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13560. * @param renderTarget The render target to set the frame buffer for
  13561. */
  13562. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13563. // Create the framebuffer
  13564. var internalTexture = renderTarget.getInternalTexture();
  13565. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13566. return;
  13567. }
  13568. var gl = this._gl;
  13569. var depthStencilTexture = renderTarget.depthStencilTexture;
  13570. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13571. if (depthStencilTexture.isCube) {
  13572. if (depthStencilTexture._generateStencilBuffer) {
  13573. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13574. }
  13575. else {
  13576. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13577. }
  13578. }
  13579. else {
  13580. if (depthStencilTexture._generateStencilBuffer) {
  13581. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13582. }
  13583. else {
  13584. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13585. }
  13586. }
  13587. this.bindUnboundFramebuffer(null);
  13588. };
  13589. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13590. var fullOptions = new RenderTargetCreationOptions();
  13591. if (options !== undefined && typeof options === "object") {
  13592. fullOptions.generateMipMaps = options.generateMipMaps;
  13593. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13594. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13595. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13596. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13597. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13598. }
  13599. else {
  13600. fullOptions.generateMipMaps = options;
  13601. fullOptions.generateDepthBuffer = true;
  13602. fullOptions.generateStencilBuffer = false;
  13603. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13604. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13605. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13606. }
  13607. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13608. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13609. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13610. }
  13611. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13612. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13613. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13614. }
  13615. var gl = this._gl;
  13616. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13617. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13618. var width = size.width || size;
  13619. var height = size.height || size;
  13620. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13621. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13622. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13623. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13624. }
  13625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13629. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13630. // Create the framebuffer
  13631. var framebuffer = gl.createFramebuffer();
  13632. this.bindUnboundFramebuffer(framebuffer);
  13633. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13634. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13635. if (fullOptions.generateMipMaps) {
  13636. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13637. }
  13638. // Unbind
  13639. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13640. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13641. this.bindUnboundFramebuffer(null);
  13642. texture._framebuffer = framebuffer;
  13643. texture.baseWidth = width;
  13644. texture.baseHeight = height;
  13645. texture.width = width;
  13646. texture.height = height;
  13647. texture.isReady = true;
  13648. texture.samples = 1;
  13649. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13650. texture.samplingMode = fullOptions.samplingMode;
  13651. texture.type = fullOptions.type;
  13652. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13653. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13654. // this.resetTextureCache();
  13655. this._internalTexturesCache.push(texture);
  13656. return texture;
  13657. };
  13658. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13659. var generateMipMaps = false;
  13660. var generateDepthBuffer = true;
  13661. var generateStencilBuffer = false;
  13662. var generateDepthTexture = false;
  13663. var textureCount = 1;
  13664. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13665. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13666. var types = [], samplingModes = [];
  13667. if (options !== undefined) {
  13668. generateMipMaps = options.generateMipMaps;
  13669. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13670. generateStencilBuffer = options.generateStencilBuffer;
  13671. generateDepthTexture = options.generateDepthTexture;
  13672. textureCount = options.textureCount || 1;
  13673. if (options.types) {
  13674. types = options.types;
  13675. }
  13676. if (options.samplingModes) {
  13677. samplingModes = options.samplingModes;
  13678. }
  13679. }
  13680. var gl = this._gl;
  13681. // Create the framebuffer
  13682. var framebuffer = gl.createFramebuffer();
  13683. this.bindUnboundFramebuffer(framebuffer);
  13684. var width = size.width || size;
  13685. var height = size.height || size;
  13686. var textures = [];
  13687. var attachments = [];
  13688. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13689. for (var i = 0; i < textureCount; i++) {
  13690. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13691. var type = types[i] || defaultType;
  13692. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13693. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13694. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13695. }
  13696. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13697. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13698. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13699. }
  13700. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13701. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13702. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13703. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13704. }
  13705. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13706. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13707. textures.push(texture);
  13708. attachments.push(attachment);
  13709. gl.activeTexture(gl["TEXTURE" + i]);
  13710. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13715. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13716. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13717. if (generateMipMaps) {
  13718. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13719. }
  13720. // Unbind
  13721. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13722. texture._framebuffer = framebuffer;
  13723. texture._depthStencilBuffer = depthStencilBuffer;
  13724. texture.baseWidth = width;
  13725. texture.baseHeight = height;
  13726. texture.width = width;
  13727. texture.height = height;
  13728. texture.isReady = true;
  13729. texture.samples = 1;
  13730. texture.generateMipMaps = generateMipMaps;
  13731. texture.samplingMode = samplingMode;
  13732. texture.type = type;
  13733. texture._generateDepthBuffer = generateDepthBuffer;
  13734. texture._generateStencilBuffer = generateStencilBuffer;
  13735. texture._attachments = attachments;
  13736. this._internalTexturesCache.push(texture);
  13737. }
  13738. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13739. // Depth texture
  13740. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13741. gl.activeTexture(gl.TEXTURE0);
  13742. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13746. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13747. 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);
  13748. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13749. depthTexture._framebuffer = framebuffer;
  13750. depthTexture.baseWidth = width;
  13751. depthTexture.baseHeight = height;
  13752. depthTexture.width = width;
  13753. depthTexture.height = height;
  13754. depthTexture.isReady = true;
  13755. depthTexture.samples = 1;
  13756. depthTexture.generateMipMaps = generateMipMaps;
  13757. depthTexture.samplingMode = gl.NEAREST;
  13758. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13759. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13760. textures.push(depthTexture);
  13761. this._internalTexturesCache.push(depthTexture);
  13762. }
  13763. gl.drawBuffers(attachments);
  13764. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13765. this.bindUnboundFramebuffer(null);
  13766. this.resetTextureCache();
  13767. return textures;
  13768. };
  13769. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13770. if (samples === void 0) { samples = 1; }
  13771. var depthStencilBuffer = null;
  13772. var gl = this._gl;
  13773. // Create the depth/stencil buffer
  13774. if (generateStencilBuffer) {
  13775. depthStencilBuffer = gl.createRenderbuffer();
  13776. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13777. if (samples > 1) {
  13778. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13779. }
  13780. else {
  13781. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13782. }
  13783. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13784. }
  13785. else if (generateDepthBuffer) {
  13786. depthStencilBuffer = gl.createRenderbuffer();
  13787. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13788. if (samples > 1) {
  13789. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13790. }
  13791. else {
  13792. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13793. }
  13794. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13795. }
  13796. return depthStencilBuffer;
  13797. };
  13798. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13799. if (this.webGLVersion < 2 || !texture) {
  13800. return 1;
  13801. }
  13802. if (texture.samples === samples) {
  13803. return samples;
  13804. }
  13805. var gl = this._gl;
  13806. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13807. // Dispose previous render buffers
  13808. if (texture._depthStencilBuffer) {
  13809. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13810. texture._depthStencilBuffer = null;
  13811. }
  13812. if (texture._MSAAFramebuffer) {
  13813. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13814. texture._MSAAFramebuffer = null;
  13815. }
  13816. if (texture._MSAARenderBuffer) {
  13817. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13818. texture._MSAARenderBuffer = null;
  13819. }
  13820. if (samples > 1) {
  13821. var framebuffer = gl.createFramebuffer();
  13822. if (!framebuffer) {
  13823. throw new Error("Unable to create multi sampled framebuffer");
  13824. }
  13825. texture._MSAAFramebuffer = framebuffer;
  13826. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13827. var colorRenderbuffer = gl.createRenderbuffer();
  13828. if (!colorRenderbuffer) {
  13829. throw new Error("Unable to create multi sampled framebuffer");
  13830. }
  13831. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13832. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13833. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13834. texture._MSAARenderBuffer = colorRenderbuffer;
  13835. }
  13836. else {
  13837. this.bindUnboundFramebuffer(texture._framebuffer);
  13838. }
  13839. texture.samples = samples;
  13840. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13841. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13842. this.bindUnboundFramebuffer(null);
  13843. return samples;
  13844. };
  13845. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13846. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13847. return 1;
  13848. }
  13849. if (textures[0].samples === samples) {
  13850. return samples;
  13851. }
  13852. var gl = this._gl;
  13853. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13854. // Dispose previous render buffers
  13855. if (textures[0]._depthStencilBuffer) {
  13856. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13857. textures[0]._depthStencilBuffer = null;
  13858. }
  13859. if (textures[0]._MSAAFramebuffer) {
  13860. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13861. textures[0]._MSAAFramebuffer = null;
  13862. }
  13863. for (var i = 0; i < textures.length; i++) {
  13864. if (textures[i]._MSAARenderBuffer) {
  13865. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13866. textures[i]._MSAARenderBuffer = null;
  13867. }
  13868. }
  13869. if (samples > 1) {
  13870. var framebuffer = gl.createFramebuffer();
  13871. if (!framebuffer) {
  13872. throw new Error("Unable to create multi sampled framebuffer");
  13873. }
  13874. this.bindUnboundFramebuffer(framebuffer);
  13875. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13876. var attachments = [];
  13877. for (var i = 0; i < textures.length; i++) {
  13878. var texture = textures[i];
  13879. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13880. var colorRenderbuffer = gl.createRenderbuffer();
  13881. if (!colorRenderbuffer) {
  13882. throw new Error("Unable to create multi sampled framebuffer");
  13883. }
  13884. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13885. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13886. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13887. texture._MSAAFramebuffer = framebuffer;
  13888. texture._MSAARenderBuffer = colorRenderbuffer;
  13889. texture.samples = samples;
  13890. texture._depthStencilBuffer = depthStencilBuffer;
  13891. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13892. attachments.push(attachment);
  13893. }
  13894. gl.drawBuffers(attachments);
  13895. }
  13896. else {
  13897. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13898. }
  13899. this.bindUnboundFramebuffer(null);
  13900. return samples;
  13901. };
  13902. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13903. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13904. };
  13905. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13906. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13907. };
  13908. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13909. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13910. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13911. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13912. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13913. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13914. }
  13915. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13916. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13917. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13918. }
  13919. var gl = this._gl;
  13920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13922. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13923. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13924. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13925. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13926. }
  13927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13931. for (var face = 0; face < 6; face++) {
  13932. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13933. }
  13934. // Create the framebuffer
  13935. var framebuffer = gl.createFramebuffer();
  13936. this.bindUnboundFramebuffer(framebuffer);
  13937. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13938. // MipMaps
  13939. if (fullOptions.generateMipMaps) {
  13940. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13941. }
  13942. // Unbind
  13943. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13944. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13945. this.bindUnboundFramebuffer(null);
  13946. texture._framebuffer = framebuffer;
  13947. texture.width = size;
  13948. texture.height = size;
  13949. texture.isReady = true;
  13950. texture.isCube = true;
  13951. texture.samples = 1;
  13952. texture.generateMipMaps = fullOptions.generateMipMaps;
  13953. texture.samplingMode = fullOptions.samplingMode;
  13954. texture.type = fullOptions.type;
  13955. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13956. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13957. this._internalTexturesCache.push(texture);
  13958. return texture;
  13959. };
  13960. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13961. var _this = this;
  13962. if (onLoad === void 0) { onLoad = null; }
  13963. if (onError === void 0) { onError = null; }
  13964. if (forcedExtension === void 0) { forcedExtension = null; }
  13965. var callback = function (loadData) {
  13966. if (!loadData) {
  13967. if (onLoad) {
  13968. onLoad(null);
  13969. }
  13970. return;
  13971. }
  13972. var texture = loadData.texture;
  13973. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13974. texture._lodGenerationScale = scale;
  13975. texture._lodGenerationOffset = offset;
  13976. if (_this._caps.textureLOD) {
  13977. // Do not add extra process if texture lod is supported.
  13978. if (onLoad) {
  13979. onLoad(texture);
  13980. }
  13981. return;
  13982. }
  13983. var mipSlices = 3;
  13984. var gl = _this._gl;
  13985. var width = loadData.width;
  13986. if (!width) {
  13987. return;
  13988. }
  13989. var textures = [];
  13990. for (var i = 0; i < mipSlices; i++) {
  13991. //compute LOD from even spacing in smoothness (matching shader calculation)
  13992. var smoothness = i / (mipSlices - 1);
  13993. var roughness = 1 - smoothness;
  13994. var minLODIndex = offset; // roughness = 0
  13995. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13996. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13997. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13998. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13999. glTextureFromLod.isCube = true;
  14000. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14004. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14005. if (loadData.isDDS) {
  14006. var info = loadData.info;
  14007. var data = loadData.data;
  14008. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14009. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14010. }
  14011. else {
  14012. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14013. }
  14014. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14015. // Wrap in a base texture for easy binding.
  14016. var lodTexture = new BABYLON.BaseTexture(scene);
  14017. lodTexture.isCube = true;
  14018. lodTexture._texture = glTextureFromLod;
  14019. glTextureFromLod.isReady = true;
  14020. textures.push(lodTexture);
  14021. }
  14022. texture._lodTextureHigh = textures[2];
  14023. texture._lodTextureMid = textures[1];
  14024. texture._lodTextureLow = textures[0];
  14025. if (onLoad) {
  14026. onLoad(texture);
  14027. }
  14028. };
  14029. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14030. };
  14031. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14032. var _this = this;
  14033. if (onLoad === void 0) { onLoad = null; }
  14034. if (onError === void 0) { onError = null; }
  14035. if (forcedExtension === void 0) { forcedExtension = null; }
  14036. var gl = this._gl;
  14037. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14038. texture.isCube = true;
  14039. texture.url = rootUrl;
  14040. texture.generateMipMaps = !noMipmap;
  14041. if (!this._doNotHandleContextLost) {
  14042. texture._extension = forcedExtension;
  14043. texture._files = files;
  14044. }
  14045. var isKTX = false;
  14046. var isDDS = false;
  14047. var lastDot = rootUrl.lastIndexOf('.');
  14048. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14049. if (this._textureFormatInUse) {
  14050. extension = this._textureFormatInUse;
  14051. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14052. isKTX = true;
  14053. }
  14054. else {
  14055. isDDS = (extension === ".dds");
  14056. }
  14057. var onerror = function (request, exception) {
  14058. if (onError && request) {
  14059. onError(request.status + " " + request.statusText, exception);
  14060. }
  14061. };
  14062. if (isKTX) {
  14063. this._loadFile(rootUrl, function (data) {
  14064. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14065. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14066. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14068. ktx.uploadLevels(_this._gl, !noMipmap);
  14069. _this.setCubeMapTextureParams(gl, loadMipmap);
  14070. texture.width = ktx.pixelWidth;
  14071. texture.height = ktx.pixelHeight;
  14072. texture.isReady = true;
  14073. }, undefined, undefined, true, onerror);
  14074. }
  14075. else if (isDDS) {
  14076. if (files && files.length === 6) {
  14077. this._cascadeLoadFiles(scene, function (imgs) {
  14078. var info;
  14079. var loadMipmap = false;
  14080. var width = 0;
  14081. for (var index = 0; index < imgs.length; index++) {
  14082. var data = imgs[index];
  14083. info = BABYLON.DDSTools.GetDDSInfo(data);
  14084. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14087. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14088. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14089. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14090. }
  14091. texture.width = info.width;
  14092. texture.height = info.height;
  14093. texture.type = info.textureType;
  14094. width = info.width;
  14095. }
  14096. _this.setCubeMapTextureParams(gl, loadMipmap);
  14097. texture.isReady = true;
  14098. if (onLoad) {
  14099. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14100. }
  14101. }, files, onError);
  14102. }
  14103. else {
  14104. this._loadFile(rootUrl, function (data) {
  14105. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14106. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14107. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14108. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14109. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14110. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14111. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14112. }
  14113. _this.setCubeMapTextureParams(gl, loadMipmap);
  14114. texture.width = info.width;
  14115. texture.height = info.height;
  14116. texture.isReady = true;
  14117. texture.type = info.textureType;
  14118. if (onLoad) {
  14119. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14120. }
  14121. }, undefined, undefined, true, onerror);
  14122. }
  14123. }
  14124. else {
  14125. if (!files) {
  14126. throw new Error("Cannot load cubemap because files were not defined");
  14127. }
  14128. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14129. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14130. var height = width;
  14131. _this._prepareWorkingCanvas();
  14132. if (!_this._workingCanvas || !_this._workingContext) {
  14133. return;
  14134. }
  14135. _this._workingCanvas.width = width;
  14136. _this._workingCanvas.height = height;
  14137. var faces = [
  14138. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14139. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14140. ];
  14141. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14142. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14143. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14144. for (var index = 0; index < faces.length; index++) {
  14145. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14146. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14147. }
  14148. if (!noMipmap) {
  14149. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14150. }
  14151. _this.setCubeMapTextureParams(gl, !noMipmap);
  14152. texture.width = width;
  14153. texture.height = height;
  14154. texture.isReady = true;
  14155. if (format) {
  14156. texture.format = format;
  14157. }
  14158. texture.onLoadedObservable.notifyObservers(texture);
  14159. texture.onLoadedObservable.clear();
  14160. if (onLoad) {
  14161. onLoad();
  14162. }
  14163. }, files, onError);
  14164. }
  14165. this._internalTexturesCache.push(texture);
  14166. return texture;
  14167. };
  14168. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14172. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14173. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14174. // this.resetTextureCache();
  14175. };
  14176. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14177. if (compression === void 0) { compression = null; }
  14178. if (level === void 0) { level = 0; }
  14179. texture._bufferViewArray = data;
  14180. texture.format = format;
  14181. texture.type = type;
  14182. texture.invertY = invertY;
  14183. texture._compression = compression;
  14184. var gl = this._gl;
  14185. var textureType = this._getWebGLTextureType(type);
  14186. var internalFormat = this._getInternalFormat(format);
  14187. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14188. var needConversion = false;
  14189. if (internalFormat === gl.RGB) {
  14190. internalFormat = gl.RGBA;
  14191. needConversion = true;
  14192. }
  14193. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14194. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14195. if (texture.width % 4 !== 0) {
  14196. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14197. }
  14198. // Data are known to be in +X +Y +Z -X -Y -Z
  14199. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14200. var faceData = data[faceIndex];
  14201. if (compression) {
  14202. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14203. }
  14204. else {
  14205. if (needConversion) {
  14206. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14207. }
  14208. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14209. }
  14210. }
  14211. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14212. if (isPot && texture.generateMipMaps && level === 0) {
  14213. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14214. }
  14215. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14216. // this.resetTextureCache();
  14217. texture.isReady = true;
  14218. };
  14219. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14220. if (compression === void 0) { compression = null; }
  14221. var gl = this._gl;
  14222. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14223. texture.isCube = true;
  14224. texture.generateMipMaps = generateMipMaps;
  14225. texture.format = format;
  14226. texture.type = type;
  14227. if (!this._doNotHandleContextLost) {
  14228. texture._bufferViewArray = data;
  14229. }
  14230. var textureType = this._getWebGLTextureType(type);
  14231. var internalFormat = this._getInternalFormat(format);
  14232. if (internalFormat === gl.RGB) {
  14233. internalFormat = gl.RGBA;
  14234. }
  14235. var width = size;
  14236. var height = width;
  14237. texture.width = width;
  14238. texture.height = height;
  14239. // Double check on POT to generate Mips.
  14240. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14241. if (!isPot) {
  14242. generateMipMaps = false;
  14243. }
  14244. // Upload data if needed. The texture won't be ready until then.
  14245. if (data) {
  14246. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14247. }
  14248. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14249. // Filters
  14250. if (data && generateMipMaps) {
  14251. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14252. }
  14253. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14256. }
  14257. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14260. }
  14261. else {
  14262. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14265. }
  14266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14268. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14269. return texture;
  14270. };
  14271. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14272. var _this = this;
  14273. if (onLoad === void 0) { onLoad = null; }
  14274. if (onError === void 0) { onError = null; }
  14275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14276. if (invertY === void 0) { invertY = false; }
  14277. var gl = this._gl;
  14278. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14279. scene._addPendingData(texture);
  14280. texture.url = url;
  14281. this._internalTexturesCache.push(texture);
  14282. var onerror = function (request, exception) {
  14283. scene._removePendingData(texture);
  14284. if (onError && request) {
  14285. onError(request.status + " " + request.statusText, exception);
  14286. }
  14287. };
  14288. var internalCallback = function (data) {
  14289. var width = texture.width;
  14290. var faceDataArrays = callback(data);
  14291. if (!faceDataArrays) {
  14292. return;
  14293. }
  14294. if (mipmmapGenerator) {
  14295. var textureType = _this._getWebGLTextureType(type);
  14296. var internalFormat = _this._getInternalFormat(format);
  14297. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14298. var needConversion = false;
  14299. if (internalFormat === gl.RGB) {
  14300. internalFormat = gl.RGBA;
  14301. needConversion = true;
  14302. }
  14303. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14304. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14305. var mipData = mipmmapGenerator(faceDataArrays);
  14306. for (var level = 0; level < mipData.length; level++) {
  14307. var mipSize = width >> level;
  14308. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14309. var mipFaceData = mipData[level][faceIndex];
  14310. if (needConversion) {
  14311. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14312. }
  14313. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14314. }
  14315. }
  14316. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14317. }
  14318. else {
  14319. texture.generateMipMaps = !noMipmap;
  14320. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14321. }
  14322. texture.isReady = true;
  14323. // this.resetTextureCache();
  14324. scene._removePendingData(texture);
  14325. if (onLoad) {
  14326. onLoad();
  14327. }
  14328. };
  14329. this._loadFile(url, function (data) {
  14330. internalCallback(data);
  14331. }, undefined, scene.database, true, onerror);
  14332. return texture;
  14333. };
  14334. ;
  14335. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14336. if (compression === void 0) { compression = null; }
  14337. var internalFormat = this._getInternalFormat(format);
  14338. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14339. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14340. if (!this._doNotHandleContextLost) {
  14341. texture._bufferView = data;
  14342. texture.format = format;
  14343. texture.invertY = invertY;
  14344. texture._compression = compression;
  14345. }
  14346. if (texture.width % 4 !== 0) {
  14347. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14348. }
  14349. if (compression && data) {
  14350. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14351. }
  14352. else {
  14353. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14354. }
  14355. if (texture.generateMipMaps) {
  14356. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14357. }
  14358. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14359. // this.resetTextureCache();
  14360. texture.isReady = true;
  14361. };
  14362. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14363. if (compression === void 0) { compression = null; }
  14364. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14365. texture.baseWidth = width;
  14366. texture.baseHeight = height;
  14367. texture.baseDepth = depth;
  14368. texture.width = width;
  14369. texture.height = height;
  14370. texture.depth = depth;
  14371. texture.format = format;
  14372. texture.generateMipMaps = generateMipMaps;
  14373. texture.samplingMode = samplingMode;
  14374. texture.is3D = true;
  14375. if (!this._doNotHandleContextLost) {
  14376. texture._bufferView = data;
  14377. }
  14378. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14379. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14380. // Filters
  14381. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14382. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14383. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14384. if (generateMipMaps) {
  14385. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14386. }
  14387. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14388. this._internalTexturesCache.push(texture);
  14389. return texture;
  14390. };
  14391. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14392. var gl = this._gl;
  14393. if (!gl) {
  14394. return;
  14395. }
  14396. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14399. if (!noMipmap && !isCompressed) {
  14400. gl.generateMipmap(gl.TEXTURE_2D);
  14401. }
  14402. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14403. // this.resetTextureCache();
  14404. if (scene) {
  14405. scene._removePendingData(texture);
  14406. }
  14407. texture.onLoadedObservable.notifyObservers(texture);
  14408. texture.onLoadedObservable.clear();
  14409. };
  14410. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14411. var _this = this;
  14412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14413. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14414. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14415. var gl = this._gl;
  14416. if (!gl) {
  14417. return;
  14418. }
  14419. if (!texture._webGLTexture) {
  14420. // this.resetTextureCache();
  14421. if (scene) {
  14422. scene._removePendingData(texture);
  14423. }
  14424. return;
  14425. }
  14426. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14427. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14428. texture.baseWidth = width;
  14429. texture.baseHeight = height;
  14430. texture.width = potWidth;
  14431. texture.height = potHeight;
  14432. texture.isReady = true;
  14433. if (processFunction(potWidth, potHeight, function () {
  14434. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14435. })) {
  14436. // Returning as texture needs extra async steps
  14437. return;
  14438. }
  14439. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14440. };
  14441. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14442. // Create new RGBA data container.
  14443. var rgbaData;
  14444. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14445. rgbaData = new Float32Array(width * height * 4);
  14446. }
  14447. else {
  14448. rgbaData = new Uint32Array(width * height * 4);
  14449. }
  14450. // Convert each pixel.
  14451. for (var x = 0; x < width; x++) {
  14452. for (var y = 0; y < height; y++) {
  14453. var index = (y * width + x) * 3;
  14454. var newIndex = (y * width + x) * 4;
  14455. // Map Old Value to new value.
  14456. rgbaData[newIndex + 0] = rgbData[index + 0];
  14457. rgbaData[newIndex + 1] = rgbData[index + 1];
  14458. rgbaData[newIndex + 2] = rgbData[index + 2];
  14459. // Add fully opaque alpha channel.
  14460. rgbaData[newIndex + 3] = 1;
  14461. }
  14462. }
  14463. return rgbaData;
  14464. };
  14465. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14466. var gl = this._gl;
  14467. if (texture._framebuffer) {
  14468. gl.deleteFramebuffer(texture._framebuffer);
  14469. texture._framebuffer = null;
  14470. }
  14471. if (texture._depthStencilBuffer) {
  14472. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14473. texture._depthStencilBuffer = null;
  14474. }
  14475. if (texture._MSAAFramebuffer) {
  14476. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14477. texture._MSAAFramebuffer = null;
  14478. }
  14479. if (texture._MSAARenderBuffer) {
  14480. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14481. texture._MSAARenderBuffer = null;
  14482. }
  14483. };
  14484. Engine.prototype._releaseTexture = function (texture) {
  14485. var gl = this._gl;
  14486. this._releaseFramebufferObjects(texture);
  14487. gl.deleteTexture(texture._webGLTexture);
  14488. // Unbind channels
  14489. this.unbindAllTextures();
  14490. var index = this._internalTexturesCache.indexOf(texture);
  14491. if (index !== -1) {
  14492. this._internalTexturesCache.splice(index, 1);
  14493. }
  14494. // Integrated fixed lod samplers.
  14495. if (texture._lodTextureHigh) {
  14496. texture._lodTextureHigh.dispose();
  14497. }
  14498. if (texture._lodTextureMid) {
  14499. texture._lodTextureMid.dispose();
  14500. }
  14501. if (texture._lodTextureLow) {
  14502. texture._lodTextureLow.dispose();
  14503. }
  14504. // Set output texture of post process to null if the texture has been released/disposed
  14505. this.scenes.forEach(function (scene) {
  14506. scene.postProcesses.forEach(function (postProcess) {
  14507. if (postProcess._outputTexture == texture) {
  14508. postProcess._outputTexture = null;
  14509. }
  14510. });
  14511. scene.cameras.forEach(function (camera) {
  14512. camera._postProcesses.forEach(function (postProcess) {
  14513. if (postProcess) {
  14514. if (postProcess._outputTexture == texture) {
  14515. postProcess._outputTexture = null;
  14516. }
  14517. }
  14518. });
  14519. });
  14520. });
  14521. };
  14522. Engine.prototype.setProgram = function (program) {
  14523. if (this._currentProgram !== program) {
  14524. this._gl.useProgram(program);
  14525. this._currentProgram = program;
  14526. }
  14527. };
  14528. Engine.prototype.bindSamplers = function (effect) {
  14529. this.setProgram(effect.getProgram());
  14530. var samplers = effect.getSamplers();
  14531. for (var index = 0; index < samplers.length; index++) {
  14532. var uniform = effect.getUniform(samplers[index]);
  14533. if (uniform) {
  14534. this._boundUniforms[index] = uniform;
  14535. }
  14536. }
  14537. this._currentEffect = null;
  14538. };
  14539. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14540. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14541. return;
  14542. }
  14543. // Remove
  14544. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14545. // Bind last to it
  14546. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14547. // Bind to dummy
  14548. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14549. };
  14550. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14551. if (!internalTexture) {
  14552. return -1;
  14553. }
  14554. internalTexture._initialSlot = channel;
  14555. if (this.disableTextureBindingOptimization) {
  14556. if (channel !== internalTexture._designatedSlot) {
  14557. this._textureCollisions.addCount(1, false);
  14558. }
  14559. }
  14560. else {
  14561. if (channel !== internalTexture._designatedSlot) {
  14562. if (internalTexture._designatedSlot > -1) {
  14563. return internalTexture._designatedSlot;
  14564. }
  14565. else {
  14566. // No slot for this texture, let's pick a new one (if we find a free slot)
  14567. if (this._nextFreeTextureSlots.length) {
  14568. return this._nextFreeTextureSlots[0];
  14569. }
  14570. // We need to recycle the oldest bound texture, sorry.
  14571. this._textureCollisions.addCount(1, false);
  14572. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14573. }
  14574. }
  14575. }
  14576. return channel;
  14577. };
  14578. Engine.prototype._linkTrackers = function (previous, next) {
  14579. previous.next = next;
  14580. next.previous = previous;
  14581. };
  14582. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14583. var currentSlot = internalTexture._designatedSlot;
  14584. if (currentSlot === -1) {
  14585. return -1;
  14586. }
  14587. internalTexture._designatedSlot = -1;
  14588. if (this.disableTextureBindingOptimization) {
  14589. return -1;
  14590. }
  14591. // Remove from bound list
  14592. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14593. // Free the slot
  14594. this._boundTexturesCache[currentSlot] = null;
  14595. this._nextFreeTextureSlots.push(currentSlot);
  14596. return currentSlot;
  14597. };
  14598. Engine.prototype._activateCurrentTexture = function () {
  14599. if (this._currentTextureChannel !== this._activeChannel) {
  14600. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14601. this._currentTextureChannel = this._activeChannel;
  14602. }
  14603. };
  14604. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14605. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14606. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14607. this._activeChannel = texture._designatedSlot;
  14608. }
  14609. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14610. var isTextureForRendering = texture && texture._initialSlot > -1;
  14611. if (currentTextureBound !== texture) {
  14612. if (currentTextureBound) {
  14613. this._removeDesignatedSlot(currentTextureBound);
  14614. }
  14615. this._activateCurrentTexture();
  14616. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14617. this._boundTexturesCache[this._activeChannel] = texture;
  14618. if (texture) {
  14619. if (!this.disableTextureBindingOptimization) {
  14620. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14621. if (slotIndex > -1) {
  14622. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14623. }
  14624. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14625. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14626. }
  14627. texture._designatedSlot = this._activeChannel;
  14628. }
  14629. }
  14630. else if (forTextureDataUpdate) {
  14631. this._activateCurrentTexture();
  14632. }
  14633. if (isTextureForRendering && !forTextureDataUpdate) {
  14634. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14635. }
  14636. };
  14637. Engine.prototype._bindTexture = function (channel, texture) {
  14638. if (channel < 0) {
  14639. return;
  14640. }
  14641. if (texture) {
  14642. channel = this._getCorrectTextureChannel(channel, texture);
  14643. }
  14644. this._activeChannel = channel;
  14645. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14646. };
  14647. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14648. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14649. };
  14650. /**
  14651. * Binds the output of the passed in post process to the texture channel specified
  14652. * @param channel The channel the texture should be bound to
  14653. * @param postProcess The post process which's output should be bound
  14654. */
  14655. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14656. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14657. };
  14658. Engine.prototype.unbindAllTextures = function () {
  14659. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14660. this._activeChannel = channel;
  14661. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14663. if (this.webGLVersion > 1) {
  14664. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14665. }
  14666. }
  14667. };
  14668. /**
  14669. * Sets a texture to the according uniform.
  14670. * @param channel The texture channel
  14671. * @param uniform The uniform to set
  14672. * @param texture The texture to apply
  14673. */
  14674. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14675. if (channel < 0) {
  14676. return;
  14677. }
  14678. if (uniform) {
  14679. this._boundUniforms[channel] = uniform;
  14680. }
  14681. this._setTexture(channel, texture);
  14682. };
  14683. /**
  14684. * Sets a depth stencil texture from a render target to the according uniform.
  14685. * @param channel The texture channel
  14686. * @param uniform The uniform to set
  14687. * @param texture The render target texture containing the depth stencil texture to apply
  14688. */
  14689. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14690. if (channel < 0) {
  14691. return;
  14692. }
  14693. if (uniform) {
  14694. this._boundUniforms[channel] = uniform;
  14695. }
  14696. if (!texture || !texture.depthStencilTexture) {
  14697. this._setTexture(channel, null);
  14698. }
  14699. else {
  14700. this._setTexture(channel, texture, false, true);
  14701. }
  14702. };
  14703. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14704. var uniform = this._boundUniforms[sourceSlot];
  14705. if (uniform._currentState === destination) {
  14706. return;
  14707. }
  14708. this._gl.uniform1i(uniform, destination);
  14709. uniform._currentState = destination;
  14710. };
  14711. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14712. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14713. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14714. // Not ready?
  14715. if (!texture) {
  14716. if (this._boundTexturesCache[channel] != null) {
  14717. this._activeChannel = channel;
  14718. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14719. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14720. if (this.webGLVersion > 1) {
  14721. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14722. }
  14723. }
  14724. return false;
  14725. }
  14726. // Video
  14727. if (texture.video) {
  14728. this._activeChannel = channel;
  14729. texture.update();
  14730. }
  14731. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14732. texture.delayLoad();
  14733. return false;
  14734. }
  14735. var internalTexture;
  14736. if (depthStencilTexture) {
  14737. internalTexture = texture.depthStencilTexture;
  14738. }
  14739. else if (texture.isReady()) {
  14740. internalTexture = texture.getInternalTexture();
  14741. }
  14742. else if (texture.isCube) {
  14743. internalTexture = this.emptyCubeTexture;
  14744. }
  14745. else if (texture.is3D) {
  14746. internalTexture = this.emptyTexture3D;
  14747. }
  14748. else {
  14749. internalTexture = this.emptyTexture;
  14750. }
  14751. if (!isPartOfTextureArray) {
  14752. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14753. }
  14754. if (this._boundTexturesCache[channel] === internalTexture) {
  14755. this._moveBoundTextureOnTop(internalTexture);
  14756. if (!isPartOfTextureArray) {
  14757. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14758. }
  14759. return false;
  14760. }
  14761. this._activeChannel = channel;
  14762. if (internalTexture && internalTexture.is3D) {
  14763. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14764. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14765. internalTexture._cachedWrapU = texture.wrapU;
  14766. switch (texture.wrapU) {
  14767. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14768. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14769. break;
  14770. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14771. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14772. break;
  14773. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14774. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14775. break;
  14776. }
  14777. }
  14778. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14779. internalTexture._cachedWrapV = texture.wrapV;
  14780. switch (texture.wrapV) {
  14781. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14782. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14783. break;
  14784. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14785. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14786. break;
  14787. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14788. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14789. break;
  14790. }
  14791. }
  14792. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14793. internalTexture._cachedWrapR = texture.wrapR;
  14794. switch (texture.wrapR) {
  14795. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14796. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14797. break;
  14798. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14799. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14800. break;
  14801. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14802. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14803. break;
  14804. }
  14805. }
  14806. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14807. }
  14808. else if (internalTexture && internalTexture.isCube) {
  14809. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14810. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14811. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14812. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14813. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14815. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14816. }
  14817. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14818. }
  14819. else {
  14820. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14821. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14822. internalTexture._cachedWrapU = texture.wrapU;
  14823. switch (texture.wrapU) {
  14824. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14825. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14826. break;
  14827. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14828. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14829. break;
  14830. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14831. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14832. break;
  14833. }
  14834. }
  14835. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14836. internalTexture._cachedWrapV = texture.wrapV;
  14837. switch (texture.wrapV) {
  14838. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14839. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14840. break;
  14841. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14842. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14843. break;
  14844. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14845. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14846. break;
  14847. }
  14848. }
  14849. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14850. }
  14851. return true;
  14852. };
  14853. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14854. if (channel < 0 || !uniform) {
  14855. return;
  14856. }
  14857. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14858. this._textureUnits = new Int32Array(textures.length);
  14859. }
  14860. for (var i = 0; i < textures.length; i++) {
  14861. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14862. }
  14863. this._gl.uniform1iv(uniform, this._textureUnits);
  14864. for (var index = 0; index < textures.length; index++) {
  14865. this._setTexture(this._textureUnits[index], textures[index], true);
  14866. }
  14867. };
  14868. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14869. var internalTexture = texture.getInternalTexture();
  14870. if (!internalTexture) {
  14871. return;
  14872. }
  14873. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14874. var value = texture.anisotropicFilteringLevel;
  14875. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14876. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14877. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14878. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14879. }
  14880. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14881. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14882. internalTexture._cachedAnisotropicFilteringLevel = value;
  14883. }
  14884. };
  14885. Engine.prototype.readPixels = function (x, y, width, height) {
  14886. var data = new Uint8Array(height * width * 4);
  14887. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14888. return data;
  14889. };
  14890. /**
  14891. * Add an externaly attached data from its key.
  14892. * This method call will fail and return false, if such key already exists.
  14893. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14894. * @param key the unique key that identifies the data
  14895. * @param data the data object to associate to the key for this Engine instance
  14896. * @return true if no such key were already present and the data was added successfully, false otherwise
  14897. */
  14898. Engine.prototype.addExternalData = function (key, data) {
  14899. if (!this._externalData) {
  14900. this._externalData = new BABYLON.StringDictionary();
  14901. }
  14902. return this._externalData.add(key, data);
  14903. };
  14904. /**
  14905. * Get an externaly attached data from its key
  14906. * @param key the unique key that identifies the data
  14907. * @return the associated data, if present (can be null), or undefined if not present
  14908. */
  14909. Engine.prototype.getExternalData = function (key) {
  14910. if (!this._externalData) {
  14911. this._externalData = new BABYLON.StringDictionary();
  14912. }
  14913. return this._externalData.get(key);
  14914. };
  14915. /**
  14916. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14917. * @param key the unique key that identifies the data
  14918. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14919. * @return the associated data, can be null if the factory returned null.
  14920. */
  14921. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14922. if (!this._externalData) {
  14923. this._externalData = new BABYLON.StringDictionary();
  14924. }
  14925. return this._externalData.getOrAddWithFactory(key, factory);
  14926. };
  14927. /**
  14928. * Remove an externaly attached data from the Engine instance
  14929. * @param key the unique key that identifies the data
  14930. * @return true if the data was successfully removed, false if it doesn't exist
  14931. */
  14932. Engine.prototype.removeExternalData = function (key) {
  14933. if (!this._externalData) {
  14934. this._externalData = new BABYLON.StringDictionary();
  14935. }
  14936. return this._externalData.remove(key);
  14937. };
  14938. Engine.prototype.unbindAllAttributes = function () {
  14939. if (this._mustWipeVertexAttributes) {
  14940. this._mustWipeVertexAttributes = false;
  14941. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14942. this._gl.disableVertexAttribArray(i);
  14943. this._vertexAttribArraysEnabled[i] = false;
  14944. this._currentBufferPointers[i].active = false;
  14945. }
  14946. return;
  14947. }
  14948. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14949. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14950. continue;
  14951. }
  14952. this._gl.disableVertexAttribArray(i);
  14953. this._vertexAttribArraysEnabled[i] = false;
  14954. this._currentBufferPointers[i].active = false;
  14955. }
  14956. };
  14957. Engine.prototype.releaseEffects = function () {
  14958. for (var name in this._compiledEffects) {
  14959. this._deleteProgram(this._compiledEffects[name]._program);
  14960. }
  14961. this._compiledEffects = {};
  14962. };
  14963. // Dispose
  14964. Engine.prototype.dispose = function () {
  14965. this.hideLoadingUI();
  14966. this.stopRenderLoop();
  14967. // Release postProcesses
  14968. while (this.postProcesses.length) {
  14969. this.postProcesses[0].dispose();
  14970. }
  14971. // Empty texture
  14972. if (this._emptyTexture) {
  14973. this._releaseTexture(this._emptyTexture);
  14974. this._emptyTexture = null;
  14975. }
  14976. if (this._emptyCubeTexture) {
  14977. this._releaseTexture(this._emptyCubeTexture);
  14978. this._emptyCubeTexture = null;
  14979. }
  14980. // Rescale PP
  14981. if (this._rescalePostProcess) {
  14982. this._rescalePostProcess.dispose();
  14983. }
  14984. // Release scenes
  14985. while (this.scenes.length) {
  14986. this.scenes[0].dispose();
  14987. }
  14988. // Release audio engine
  14989. if (Engine.audioEngine) {
  14990. Engine.audioEngine.dispose();
  14991. }
  14992. // Release effects
  14993. this.releaseEffects();
  14994. // Unbind
  14995. this.unbindAllAttributes();
  14996. this._boundUniforms = [];
  14997. if (this._dummyFramebuffer) {
  14998. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14999. }
  15000. //WebVR
  15001. this.disableVR();
  15002. // Events
  15003. if (BABYLON.Tools.IsWindowObjectExist()) {
  15004. window.removeEventListener("blur", this._onBlur);
  15005. window.removeEventListener("focus", this._onFocus);
  15006. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15007. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15008. if (this._renderingCanvas) {
  15009. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15010. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15011. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15012. if (!this._doNotHandleContextLost) {
  15013. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15014. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15015. }
  15016. }
  15017. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15018. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15019. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15020. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15021. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15022. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15023. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15024. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15025. if (this._onVrDisplayConnect) {
  15026. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15027. if (this._onVrDisplayDisconnect) {
  15028. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15029. }
  15030. if (this._onVrDisplayPresentChange) {
  15031. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15032. }
  15033. this._onVrDisplayConnect = null;
  15034. this._onVrDisplayDisconnect = null;
  15035. }
  15036. }
  15037. // Remove from Instances
  15038. var index = Engine.Instances.indexOf(this);
  15039. if (index >= 0) {
  15040. Engine.Instances.splice(index, 1);
  15041. }
  15042. this._workingCanvas = null;
  15043. this._workingContext = null;
  15044. this._currentBufferPointers = [];
  15045. this._renderingCanvas = null;
  15046. this._currentProgram = null;
  15047. this._bindedRenderFunction = null;
  15048. this.onResizeObservable.clear();
  15049. this.onCanvasBlurObservable.clear();
  15050. this.onCanvasFocusObservable.clear();
  15051. this.onCanvasPointerOutObservable.clear();
  15052. this.onBeginFrameObservable.clear();
  15053. this.onEndFrameObservable.clear();
  15054. BABYLON.Effect.ResetCache();
  15055. // Abort active requests
  15056. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15057. var request = _a[_i];
  15058. request.abort();
  15059. }
  15060. };
  15061. // Loading screen
  15062. Engine.prototype.displayLoadingUI = function () {
  15063. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15064. return;
  15065. }
  15066. var loadingScreen = this.loadingScreen;
  15067. if (loadingScreen) {
  15068. loadingScreen.displayLoadingUI();
  15069. }
  15070. };
  15071. Engine.prototype.hideLoadingUI = function () {
  15072. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15073. return;
  15074. }
  15075. var loadingScreen = this.loadingScreen;
  15076. if (loadingScreen) {
  15077. loadingScreen.hideLoadingUI();
  15078. }
  15079. };
  15080. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15081. get: function () {
  15082. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15083. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15084. return this._loadingScreen;
  15085. },
  15086. set: function (loadingScreen) {
  15087. this._loadingScreen = loadingScreen;
  15088. },
  15089. enumerable: true,
  15090. configurable: true
  15091. });
  15092. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15093. set: function (text) {
  15094. this.loadingScreen.loadingUIText = text;
  15095. },
  15096. enumerable: true,
  15097. configurable: true
  15098. });
  15099. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15100. set: function (color) {
  15101. this.loadingScreen.loadingUIBackgroundColor = color;
  15102. },
  15103. enumerable: true,
  15104. configurable: true
  15105. });
  15106. Engine.prototype.attachContextLostEvent = function (callback) {
  15107. if (this._renderingCanvas) {
  15108. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15109. }
  15110. };
  15111. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15112. if (this._renderingCanvas) {
  15113. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15114. }
  15115. };
  15116. Engine.prototype.getVertexShaderSource = function (program) {
  15117. var shaders = this._gl.getAttachedShaders(program);
  15118. if (!shaders) {
  15119. return null;
  15120. }
  15121. return this._gl.getShaderSource(shaders[0]);
  15122. };
  15123. Engine.prototype.getFragmentShaderSource = function (program) {
  15124. var shaders = this._gl.getAttachedShaders(program);
  15125. if (!shaders) {
  15126. return null;
  15127. }
  15128. return this._gl.getShaderSource(shaders[1]);
  15129. };
  15130. Engine.prototype.getError = function () {
  15131. return this._gl.getError();
  15132. };
  15133. // FPS
  15134. Engine.prototype.getFps = function () {
  15135. return this._fps;
  15136. };
  15137. Engine.prototype.getDeltaTime = function () {
  15138. return this._deltaTime;
  15139. };
  15140. Engine.prototype._measureFps = function () {
  15141. this._performanceMonitor.sampleFrame();
  15142. this._fps = this._performanceMonitor.averageFPS;
  15143. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15144. };
  15145. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15146. if (faceIndex === void 0) { faceIndex = -1; }
  15147. var gl = this._gl;
  15148. if (!this._dummyFramebuffer) {
  15149. var dummy = gl.createFramebuffer();
  15150. if (!dummy) {
  15151. throw new Error("Unable to create dummy framebuffer");
  15152. }
  15153. this._dummyFramebuffer = dummy;
  15154. }
  15155. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15156. if (faceIndex > -1) {
  15157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15158. }
  15159. else {
  15160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15161. }
  15162. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15163. var buffer;
  15164. switch (readType) {
  15165. case gl.UNSIGNED_BYTE:
  15166. buffer = new Uint8Array(4 * width * height);
  15167. readType = gl.UNSIGNED_BYTE;
  15168. break;
  15169. default:
  15170. buffer = new Float32Array(4 * width * height);
  15171. readType = gl.FLOAT;
  15172. break;
  15173. }
  15174. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15175. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15176. return buffer;
  15177. };
  15178. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15179. if (this._webGLVersion > 1) {
  15180. return this._caps.colorBufferFloat;
  15181. }
  15182. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15183. };
  15184. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15185. if (this._webGLVersion > 1) {
  15186. return this._caps.colorBufferFloat;
  15187. }
  15188. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15189. };
  15190. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15191. Engine.prototype._canRenderToFramebuffer = function (type) {
  15192. var gl = this._gl;
  15193. //clear existing errors
  15194. while (gl.getError() !== gl.NO_ERROR) { }
  15195. var successful = true;
  15196. var texture = gl.createTexture();
  15197. gl.bindTexture(gl.TEXTURE_2D, texture);
  15198. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15201. var fb = gl.createFramebuffer();
  15202. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15203. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15204. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15205. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15206. successful = successful && (gl.getError() === gl.NO_ERROR);
  15207. //try render by clearing frame buffer's color buffer
  15208. if (successful) {
  15209. gl.clear(gl.COLOR_BUFFER_BIT);
  15210. successful = successful && (gl.getError() === gl.NO_ERROR);
  15211. }
  15212. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15213. if (successful) {
  15214. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15215. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15216. var readFormat = gl.RGBA;
  15217. var readType = gl.UNSIGNED_BYTE;
  15218. var buffer = new Uint8Array(4);
  15219. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15220. successful = successful && (gl.getError() === gl.NO_ERROR);
  15221. }
  15222. //clean up
  15223. gl.deleteTexture(texture);
  15224. gl.deleteFramebuffer(fb);
  15225. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15226. //clear accumulated errors
  15227. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15228. return successful;
  15229. };
  15230. Engine.prototype._getWebGLTextureType = function (type) {
  15231. if (type === Engine.TEXTURETYPE_FLOAT) {
  15232. return this._gl.FLOAT;
  15233. }
  15234. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15235. // Add Half Float Constant.
  15236. return this._gl.HALF_FLOAT_OES;
  15237. }
  15238. return this._gl.UNSIGNED_BYTE;
  15239. };
  15240. ;
  15241. Engine.prototype._getInternalFormat = function (format) {
  15242. var internalFormat = this._gl.RGBA;
  15243. switch (format) {
  15244. case Engine.TEXTUREFORMAT_ALPHA:
  15245. internalFormat = this._gl.ALPHA;
  15246. break;
  15247. case Engine.TEXTUREFORMAT_LUMINANCE:
  15248. internalFormat = this._gl.LUMINANCE;
  15249. break;
  15250. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15251. internalFormat = this._gl.LUMINANCE_ALPHA;
  15252. break;
  15253. case Engine.TEXTUREFORMAT_RGB:
  15254. case Engine.TEXTUREFORMAT_RGB32F:
  15255. internalFormat = this._gl.RGB;
  15256. break;
  15257. case Engine.TEXTUREFORMAT_RGBA:
  15258. case Engine.TEXTUREFORMAT_RGBA32F:
  15259. internalFormat = this._gl.RGBA;
  15260. break;
  15261. case Engine.TEXTUREFORMAT_R32F:
  15262. internalFormat = this._gl.RED;
  15263. break;
  15264. case Engine.TEXTUREFORMAT_RG32F:
  15265. internalFormat = this._gl.RG;
  15266. break;
  15267. }
  15268. return internalFormat;
  15269. };
  15270. /** @ignore */
  15271. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15272. if (this._webGLVersion === 1) {
  15273. if (format) {
  15274. switch (format) {
  15275. case Engine.TEXTUREFORMAT_LUMINANCE:
  15276. return this._gl.LUMINANCE;
  15277. }
  15278. }
  15279. return this._gl.RGBA;
  15280. }
  15281. if (type === Engine.TEXTURETYPE_FLOAT) {
  15282. if (format) {
  15283. switch (format) {
  15284. case Engine.TEXTUREFORMAT_R32F:
  15285. return this._gl.R32F;
  15286. case Engine.TEXTUREFORMAT_RG32F:
  15287. return this._gl.RG32F;
  15288. case Engine.TEXTUREFORMAT_RGB32F:
  15289. return this._gl.RGB32F;
  15290. }
  15291. }
  15292. return this._gl.RGBA32F;
  15293. }
  15294. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15295. return this._gl.RGBA16F;
  15296. }
  15297. if (format) {
  15298. switch (format) {
  15299. case Engine.TEXTUREFORMAT_LUMINANCE:
  15300. return this._gl.LUMINANCE;
  15301. }
  15302. }
  15303. return this._gl.RGBA;
  15304. };
  15305. ;
  15306. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15307. if (type === Engine.TEXTURETYPE_FLOAT) {
  15308. return this._gl.RGBA32F;
  15309. }
  15310. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15311. return this._gl.RGBA16F;
  15312. }
  15313. return this._gl.RGBA8;
  15314. };
  15315. ;
  15316. Engine.prototype.createQuery = function () {
  15317. return this._gl.createQuery();
  15318. };
  15319. Engine.prototype.deleteQuery = function (query) {
  15320. this._gl.deleteQuery(query);
  15321. return this;
  15322. };
  15323. Engine.prototype.isQueryResultAvailable = function (query) {
  15324. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15325. };
  15326. Engine.prototype.getQueryResult = function (query) {
  15327. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15328. };
  15329. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15330. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15331. this._gl.beginQuery(glAlgorithm, query);
  15332. return this;
  15333. };
  15334. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15335. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15336. this._gl.endQuery(glAlgorithm);
  15337. return this;
  15338. };
  15339. /* Time queries */
  15340. Engine.prototype._createTimeQuery = function () {
  15341. var timerQuery = this._caps.timerQuery;
  15342. if (timerQuery.createQueryEXT) {
  15343. return timerQuery.createQueryEXT();
  15344. }
  15345. return this.createQuery();
  15346. };
  15347. Engine.prototype._deleteTimeQuery = function (query) {
  15348. var timerQuery = this._caps.timerQuery;
  15349. if (timerQuery.deleteQueryEXT) {
  15350. timerQuery.deleteQueryEXT(query);
  15351. return;
  15352. }
  15353. this.deleteQuery(query);
  15354. };
  15355. Engine.prototype._getTimeQueryResult = function (query) {
  15356. var timerQuery = this._caps.timerQuery;
  15357. if (timerQuery.getQueryObjectEXT) {
  15358. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15359. }
  15360. return this.getQueryResult(query);
  15361. };
  15362. Engine.prototype._getTimeQueryAvailability = function (query) {
  15363. var timerQuery = this._caps.timerQuery;
  15364. if (timerQuery.getQueryObjectEXT) {
  15365. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15366. }
  15367. return this.isQueryResultAvailable(query);
  15368. };
  15369. Engine.prototype.startTimeQuery = function () {
  15370. var timerQuery = this._caps.timerQuery;
  15371. if (!timerQuery) {
  15372. return null;
  15373. }
  15374. var token = new BABYLON._TimeToken();
  15375. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15376. if (this._caps.canUseTimestampForTimerQuery) {
  15377. token._startTimeQuery = this._createTimeQuery();
  15378. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15379. }
  15380. else {
  15381. if (this._currentNonTimestampToken) {
  15382. return this._currentNonTimestampToken;
  15383. }
  15384. token._timeElapsedQuery = this._createTimeQuery();
  15385. if (timerQuery.beginQueryEXT) {
  15386. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15387. }
  15388. else {
  15389. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15390. }
  15391. this._currentNonTimestampToken = token;
  15392. }
  15393. return token;
  15394. };
  15395. Engine.prototype.endTimeQuery = function (token) {
  15396. var timerQuery = this._caps.timerQuery;
  15397. if (!timerQuery || !token) {
  15398. return -1;
  15399. }
  15400. if (this._caps.canUseTimestampForTimerQuery) {
  15401. if (!token._startTimeQuery) {
  15402. return -1;
  15403. }
  15404. if (!token._endTimeQuery) {
  15405. token._endTimeQuery = this._createTimeQuery();
  15406. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15407. }
  15408. }
  15409. else if (!token._timeElapsedQueryEnded) {
  15410. if (!token._timeElapsedQuery) {
  15411. return -1;
  15412. }
  15413. if (timerQuery.endQueryEXT) {
  15414. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15415. }
  15416. else {
  15417. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15418. }
  15419. token._timeElapsedQueryEnded = true;
  15420. }
  15421. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15422. var available = false;
  15423. if (token._endTimeQuery) {
  15424. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15425. }
  15426. else if (token._timeElapsedQuery) {
  15427. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15428. }
  15429. if (available && !disjoint) {
  15430. var result = 0;
  15431. if (this._caps.canUseTimestampForTimerQuery) {
  15432. if (!token._startTimeQuery || !token._endTimeQuery) {
  15433. return -1;
  15434. }
  15435. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15436. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15437. result = timeEnd - timeStart;
  15438. this._deleteTimeQuery(token._startTimeQuery);
  15439. this._deleteTimeQuery(token._endTimeQuery);
  15440. token._startTimeQuery = null;
  15441. token._endTimeQuery = null;
  15442. }
  15443. else {
  15444. if (!token._timeElapsedQuery) {
  15445. return -1;
  15446. }
  15447. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15448. this._deleteTimeQuery(token._timeElapsedQuery);
  15449. token._timeElapsedQuery = null;
  15450. token._timeElapsedQueryEnded = false;
  15451. this._currentNonTimestampToken = null;
  15452. }
  15453. return result;
  15454. }
  15455. return -1;
  15456. };
  15457. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15458. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15459. };
  15460. // Transform feedback
  15461. Engine.prototype.createTransformFeedback = function () {
  15462. return this._gl.createTransformFeedback();
  15463. };
  15464. Engine.prototype.deleteTransformFeedback = function (value) {
  15465. this._gl.deleteTransformFeedback(value);
  15466. };
  15467. Engine.prototype.bindTransformFeedback = function (value) {
  15468. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15469. };
  15470. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15471. if (usePoints === void 0) { usePoints = true; }
  15472. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15473. };
  15474. Engine.prototype.endTransformFeedback = function () {
  15475. this._gl.endTransformFeedback();
  15476. };
  15477. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15478. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15479. };
  15480. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15481. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15482. };
  15483. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15484. var _this = this;
  15485. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15486. this._activeRequests.push(request);
  15487. request.onCompleteObservable.add(function (request) {
  15488. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15489. });
  15490. return request;
  15491. };
  15492. /** @ignore */
  15493. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15494. var _this = this;
  15495. return new Promise(function (resolve, reject) {
  15496. _this._loadFile(url, function (data) {
  15497. resolve(data);
  15498. }, undefined, database, useArrayBuffer, function (request, exception) {
  15499. reject(exception);
  15500. });
  15501. });
  15502. };
  15503. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15504. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15505. var onload = function (data) {
  15506. loadedFiles[index] = data;
  15507. loadedFiles._internalCount++;
  15508. if (loadedFiles._internalCount === 6) {
  15509. onfinish(loadedFiles);
  15510. }
  15511. };
  15512. var onerror = function (request, exception) {
  15513. if (onErrorCallBack && request) {
  15514. onErrorCallBack(request.status + " " + request.statusText, exception);
  15515. }
  15516. };
  15517. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15518. };
  15519. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15520. if (onError === void 0) { onError = null; }
  15521. var loadedFiles = [];
  15522. loadedFiles._internalCount = 0;
  15523. for (var index = 0; index < 6; index++) {
  15524. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15525. }
  15526. };
  15527. // Statics
  15528. Engine.isSupported = function () {
  15529. try {
  15530. var tempcanvas = document.createElement("canvas");
  15531. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15532. return gl != null && !!window.WebGLRenderingContext;
  15533. }
  15534. catch (e) {
  15535. return false;
  15536. }
  15537. };
  15538. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15539. Engine.ExceptionList = [
  15540. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15541. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15542. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15543. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15544. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15545. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15546. ];
  15547. Engine.Instances = new Array();
  15548. // Const statics
  15549. Engine._ALPHA_DISABLE = 0;
  15550. Engine._ALPHA_ADD = 1;
  15551. Engine._ALPHA_COMBINE = 2;
  15552. Engine._ALPHA_SUBTRACT = 3;
  15553. Engine._ALPHA_MULTIPLY = 4;
  15554. Engine._ALPHA_MAXIMIZED = 5;
  15555. Engine._ALPHA_ONEONE = 6;
  15556. Engine._ALPHA_PREMULTIPLIED = 7;
  15557. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15558. Engine._ALPHA_INTERPOLATE = 9;
  15559. Engine._ALPHA_SCREENMODE = 10;
  15560. Engine._DELAYLOADSTATE_NONE = 0;
  15561. Engine._DELAYLOADSTATE_LOADED = 1;
  15562. Engine._DELAYLOADSTATE_LOADING = 2;
  15563. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15564. Engine._TEXTUREFORMAT_ALPHA = 0;
  15565. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15566. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15567. Engine._TEXTUREFORMAT_RGB = 4;
  15568. Engine._TEXTUREFORMAT_RGBA = 5;
  15569. Engine._TEXTUREFORMAT_R32F = 6;
  15570. Engine._TEXTUREFORMAT_RG32F = 7;
  15571. Engine._TEXTUREFORMAT_RGB32F = 8;
  15572. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15573. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15574. Engine._TEXTURETYPE_FLOAT = 1;
  15575. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15576. // Depht or Stencil test Constants.
  15577. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15578. 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.
  15579. 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.
  15580. 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.
  15581. 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.
  15582. 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.
  15583. 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.
  15584. 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.
  15585. // Stencil Actions Constants.
  15586. Engine._KEEP = 0x1E00;
  15587. Engine._REPLACE = 0x1E01;
  15588. Engine._INCR = 0x1E02;
  15589. Engine._DECR = 0x1E03;
  15590. Engine._INVERT = 0x150A;
  15591. Engine._INCR_WRAP = 0x8507;
  15592. Engine._DECR_WRAP = 0x8508;
  15593. // Texture rescaling mode
  15594. Engine._SCALEMODE_FLOOR = 1;
  15595. Engine._SCALEMODE_NEAREST = 2;
  15596. Engine._SCALEMODE_CEILING = 3;
  15597. // Updatable statics so stick with vars here
  15598. Engine.CollisionsEpsilon = 0.001;
  15599. Engine.CodeRepository = "src/";
  15600. Engine.ShadersRepository = "src/Shaders/";
  15601. return Engine;
  15602. }());
  15603. BABYLON.Engine = Engine;
  15604. })(BABYLON || (BABYLON = {}));
  15605. //# sourceMappingURL=babylon.engine.js.map
  15606. "use strict";
  15607. var BABYLON;
  15608. (function (BABYLON) {
  15609. /**
  15610. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15611. */
  15612. var Node = /** @class */ (function () {
  15613. /**
  15614. * Creates a new Node
  15615. * @param {string} name - the name and id to be given to this node
  15616. * @param {BABYLON.Scene} the scene this node will be added to
  15617. */
  15618. function Node(name, scene) {
  15619. if (scene === void 0) { scene = null; }
  15620. /**
  15621. * Gets or sets a string used to store user defined state for the node
  15622. */
  15623. this.state = "";
  15624. /**
  15625. * Gets or sets an object used to store user defined information for the node
  15626. */
  15627. this.metadata = null;
  15628. /**
  15629. * Gets or sets a boolean used to define if the node must be serialized
  15630. */
  15631. this.doNotSerialize = false;
  15632. /** @ignore */
  15633. this._isDisposed = false;
  15634. /**
  15635. * Gets a list of Animations associated with the node
  15636. */
  15637. this.animations = new Array();
  15638. this._ranges = {};
  15639. this._isEnabled = true;
  15640. this._isReady = true;
  15641. /** @ignore */
  15642. this._currentRenderId = -1;
  15643. this._parentRenderId = -1;
  15644. this._childRenderId = -1;
  15645. this._animationPropertiesOverride = null;
  15646. /**
  15647. * An event triggered when the mesh is disposed
  15648. */
  15649. this.onDisposeObservable = new BABYLON.Observable();
  15650. // Behaviors
  15651. this._behaviors = new Array();
  15652. this.name = name;
  15653. this.id = name;
  15654. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15655. this.uniqueId = this._scene.getUniqueId();
  15656. this._initCache();
  15657. }
  15658. /**
  15659. * Gets a boolean indicating if the node has been disposed
  15660. * @returns true if the node was disposed
  15661. */
  15662. Node.prototype.isDisposed = function () {
  15663. return this._isDisposed;
  15664. };
  15665. Object.defineProperty(Node.prototype, "parent", {
  15666. get: function () {
  15667. return this._parentNode;
  15668. },
  15669. /**
  15670. * Gets or sets the parent of the node
  15671. */
  15672. set: function (parent) {
  15673. if (this._parentNode === parent) {
  15674. return;
  15675. }
  15676. // Remove self from list of children of parent
  15677. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15678. var index = this._parentNode._children.indexOf(this);
  15679. if (index !== -1) {
  15680. this._parentNode._children.splice(index, 1);
  15681. }
  15682. }
  15683. // Store new parent
  15684. this._parentNode = parent;
  15685. // Add as child to new parent
  15686. if (this._parentNode) {
  15687. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15688. this._parentNode._children = new Array();
  15689. }
  15690. this._parentNode._children.push(this);
  15691. }
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15697. /**
  15698. * Gets or sets the animation properties override
  15699. */
  15700. get: function () {
  15701. return this._animationPropertiesOverride;
  15702. },
  15703. set: function (value) {
  15704. this._animationPropertiesOverride = value;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. /**
  15710. * Gets a string idenfifying the name of the class
  15711. * @returns "Node" string
  15712. */
  15713. Node.prototype.getClassName = function () {
  15714. return "Node";
  15715. };
  15716. Object.defineProperty(Node.prototype, "onDispose", {
  15717. /**
  15718. * Sets a callback that will be raised when the node will be disposed
  15719. */
  15720. set: function (callback) {
  15721. if (this._onDisposeObserver) {
  15722. this.onDisposeObservable.remove(this._onDisposeObserver);
  15723. }
  15724. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. /**
  15730. * Gets the scene of the node
  15731. * @returns a {BABYLON.Scene}
  15732. */
  15733. Node.prototype.getScene = function () {
  15734. return this._scene;
  15735. };
  15736. /**
  15737. * Gets the engine of the node
  15738. * @returns a {BABYLON.Engine}
  15739. */
  15740. Node.prototype.getEngine = function () {
  15741. return this._scene.getEngine();
  15742. };
  15743. /**
  15744. * Attach a behavior to the node
  15745. * @see http://doc.babylonjs.com/features/behaviour
  15746. * @param behavior defines the behavior to attach
  15747. * @returns the current Node
  15748. */
  15749. Node.prototype.addBehavior = function (behavior) {
  15750. var _this = this;
  15751. var index = this._behaviors.indexOf(behavior);
  15752. if (index !== -1) {
  15753. return this;
  15754. }
  15755. behavior.init();
  15756. if (this._scene.isLoading) {
  15757. // We defer the attach when the scene will be loaded
  15758. var observer = this._scene.onDataLoadedObservable.add(function () {
  15759. behavior.attach(_this);
  15760. setTimeout(function () {
  15761. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15762. _this._scene.onDataLoadedObservable.remove(observer);
  15763. }, 0);
  15764. });
  15765. }
  15766. else {
  15767. behavior.attach(this);
  15768. }
  15769. this._behaviors.push(behavior);
  15770. return this;
  15771. };
  15772. /**
  15773. * Remove an attached behavior
  15774. * @see http://doc.babylonjs.com/features/behaviour
  15775. * @param behavior defines the behavior to attach
  15776. * @returns the current Node
  15777. */
  15778. Node.prototype.removeBehavior = function (behavior) {
  15779. var index = this._behaviors.indexOf(behavior);
  15780. if (index === -1) {
  15781. return this;
  15782. }
  15783. this._behaviors[index].detach();
  15784. this._behaviors.splice(index, 1);
  15785. return this;
  15786. };
  15787. Object.defineProperty(Node.prototype, "behaviors", {
  15788. /**
  15789. * Gets the list of attached behaviors
  15790. * @see http://doc.babylonjs.com/features/behaviour
  15791. */
  15792. get: function () {
  15793. return this._behaviors;
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. /**
  15799. * Gets an attached behavior by name
  15800. * @param name defines the name of the behavior to look for
  15801. * @see http://doc.babylonjs.com/features/behaviour
  15802. * @returns null if behavior was not found else the requested behavior
  15803. */
  15804. Node.prototype.getBehaviorByName = function (name) {
  15805. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15806. var behavior = _a[_i];
  15807. if (behavior.name === name) {
  15808. return behavior;
  15809. }
  15810. }
  15811. return null;
  15812. };
  15813. /**
  15814. * Returns the world matrix of the node
  15815. * @returns a matrix containing the node's world matrix
  15816. */
  15817. Node.prototype.getWorldMatrix = function () {
  15818. return BABYLON.Matrix.Identity();
  15819. };
  15820. // override it in derived class if you add new variables to the cache
  15821. // and call the parent class method
  15822. /** @ignore */
  15823. Node.prototype._initCache = function () {
  15824. this._cache = {};
  15825. this._cache.parent = undefined;
  15826. };
  15827. /** @ignore */
  15828. Node.prototype.updateCache = function (force) {
  15829. if (!force && this.isSynchronized())
  15830. return;
  15831. this._cache.parent = this.parent;
  15832. this._updateCache();
  15833. };
  15834. // override it in derived class if you add new variables to the cache
  15835. // and call the parent class method if !ignoreParentClass
  15836. /** @ignore */
  15837. Node.prototype._updateCache = function (ignoreParentClass) {
  15838. };
  15839. // override it in derived class if you add new variables to the cache
  15840. /** @ignore */
  15841. Node.prototype._isSynchronized = function () {
  15842. return true;
  15843. };
  15844. /** @ignore */
  15845. Node.prototype._markSyncedWithParent = function () {
  15846. if (this.parent) {
  15847. this._parentRenderId = this.parent._childRenderId;
  15848. }
  15849. };
  15850. /** @ignore */
  15851. Node.prototype.isSynchronizedWithParent = function () {
  15852. if (!this.parent) {
  15853. return true;
  15854. }
  15855. if (this._parentRenderId !== this.parent._childRenderId) {
  15856. return false;
  15857. }
  15858. return this.parent.isSynchronized();
  15859. };
  15860. /** @ignore */
  15861. Node.prototype.isSynchronized = function (updateCache) {
  15862. var check = this.hasNewParent();
  15863. check = check || !this.isSynchronizedWithParent();
  15864. check = check || !this._isSynchronized();
  15865. if (updateCache)
  15866. this.updateCache(true);
  15867. return !check;
  15868. };
  15869. /** @ignore */
  15870. Node.prototype.hasNewParent = function (update) {
  15871. if (this._cache.parent === this.parent)
  15872. return false;
  15873. if (update)
  15874. this._cache.parent = this.parent;
  15875. return true;
  15876. };
  15877. /**
  15878. * Is this node ready to be used/rendered
  15879. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15880. * @return true if the node is ready
  15881. */
  15882. Node.prototype.isReady = function (completeCheck) {
  15883. if (completeCheck === void 0) { completeCheck = false; }
  15884. return this._isReady;
  15885. };
  15886. /**
  15887. * Is this node enabled?
  15888. * 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
  15889. * @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
  15890. * @return whether this node (and its parent) is enabled
  15891. */
  15892. Node.prototype.isEnabled = function (checkAncestors) {
  15893. if (checkAncestors === void 0) { checkAncestors = true; }
  15894. if (checkAncestors === false) {
  15895. return this._isEnabled;
  15896. }
  15897. if (this._isEnabled === false) {
  15898. return false;
  15899. }
  15900. if (this.parent !== undefined && this.parent !== null) {
  15901. return this.parent.isEnabled(checkAncestors);
  15902. }
  15903. return true;
  15904. };
  15905. /**
  15906. * Set the enabled state of this node
  15907. * @param value defines the new enabled state
  15908. */
  15909. Node.prototype.setEnabled = function (value) {
  15910. this._isEnabled = value;
  15911. };
  15912. /**
  15913. * Is this node a descendant of the given node?
  15914. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15915. * @param ancestor defines the parent node to inspect
  15916. * @returns a boolean indicating if this node is a descendant of the given node
  15917. */
  15918. Node.prototype.isDescendantOf = function (ancestor) {
  15919. if (this.parent) {
  15920. if (this.parent === ancestor) {
  15921. return true;
  15922. }
  15923. return this.parent.isDescendantOf(ancestor);
  15924. }
  15925. return false;
  15926. };
  15927. /** @ignore */
  15928. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15929. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15930. if (!this._children) {
  15931. return;
  15932. }
  15933. for (var index = 0; index < this._children.length; index++) {
  15934. var item = this._children[index];
  15935. if (!predicate || predicate(item)) {
  15936. results.push(item);
  15937. }
  15938. if (!directDescendantsOnly) {
  15939. item._getDescendants(results, false, predicate);
  15940. }
  15941. }
  15942. };
  15943. /**
  15944. * Will return all nodes that have this node as ascendant
  15945. * @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
  15946. * @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
  15947. * @return all children nodes of all types
  15948. */
  15949. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15950. var results = new Array();
  15951. this._getDescendants(results, directDescendantsOnly, predicate);
  15952. return results;
  15953. };
  15954. /**
  15955. * Get all child-meshes of this node
  15956. * @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
  15957. * @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
  15958. * @returns an array of {BABYLON.AbstractMesh}
  15959. */
  15960. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15961. var results = [];
  15962. this._getDescendants(results, directDescendantsOnly, function (node) {
  15963. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15964. });
  15965. return results;
  15966. };
  15967. /**
  15968. * Get all child-transformNodes of this node
  15969. * @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
  15970. * @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
  15971. * @returns an array of {BABYLON.TransformNode}
  15972. */
  15973. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15974. var results = [];
  15975. this._getDescendants(results, directDescendantsOnly, function (node) {
  15976. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15977. });
  15978. return results;
  15979. };
  15980. /**
  15981. * Get all direct children of this node
  15982. * @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
  15983. * @returns an array of {BABYLON.Node}
  15984. */
  15985. Node.prototype.getChildren = function (predicate) {
  15986. return this.getDescendants(true, predicate);
  15987. };
  15988. /** @ignore */
  15989. Node.prototype._setReady = function (state) {
  15990. if (state === this._isReady) {
  15991. return;
  15992. }
  15993. if (!state) {
  15994. this._isReady = false;
  15995. return;
  15996. }
  15997. if (this.onReady) {
  15998. this.onReady(this);
  15999. }
  16000. this._isReady = true;
  16001. };
  16002. /**
  16003. * Get an animation by name
  16004. * @param name defines the name of the animation to look for
  16005. * @returns null if not found else the requested animation
  16006. */
  16007. Node.prototype.getAnimationByName = function (name) {
  16008. for (var i = 0; i < this.animations.length; i++) {
  16009. var animation = this.animations[i];
  16010. if (animation.name === name) {
  16011. return animation;
  16012. }
  16013. }
  16014. return null;
  16015. };
  16016. /**
  16017. * Creates an animation range for this node
  16018. * @param name defines the name of the range
  16019. * @param from defines the starting key
  16020. * @param to defines the end key
  16021. */
  16022. Node.prototype.createAnimationRange = function (name, from, to) {
  16023. // check name not already in use
  16024. if (!this._ranges[name]) {
  16025. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16026. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16027. if (this.animations[i]) {
  16028. this.animations[i].createRange(name, from, to);
  16029. }
  16030. }
  16031. }
  16032. };
  16033. /**
  16034. * Delete a specific animation range
  16035. * @param name defines the name of the range to delete
  16036. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16037. */
  16038. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16039. if (deleteFrames === void 0) { deleteFrames = true; }
  16040. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16041. if (this.animations[i]) {
  16042. this.animations[i].deleteRange(name, deleteFrames);
  16043. }
  16044. }
  16045. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16046. };
  16047. /**
  16048. * Get an animation range by name
  16049. * @param name defines the name of the animation range to look for
  16050. * @returns null if not found else the requested animation range
  16051. */
  16052. Node.prototype.getAnimationRange = function (name) {
  16053. return this._ranges[name];
  16054. };
  16055. /**
  16056. * Will start the animation sequence
  16057. * @param name defines the range frames for animation sequence
  16058. * @param loop defines if the animation should loop (false by default)
  16059. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16060. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16061. * @returns the object created for this animation. If range does not exist, it will return null
  16062. */
  16063. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16064. var range = this.getAnimationRange(name);
  16065. if (!range) {
  16066. return null;
  16067. }
  16068. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16069. };
  16070. /**
  16071. * Serialize animation ranges into a JSON compatible object
  16072. * @returns serialization object
  16073. */
  16074. Node.prototype.serializeAnimationRanges = function () {
  16075. var serializationRanges = [];
  16076. for (var name in this._ranges) {
  16077. var localRange = this._ranges[name];
  16078. if (!localRange) {
  16079. continue;
  16080. }
  16081. var range = {};
  16082. range.name = name;
  16083. range.from = localRange.from;
  16084. range.to = localRange.to;
  16085. serializationRanges.push(range);
  16086. }
  16087. return serializationRanges;
  16088. };
  16089. /**
  16090. * Computes the world matrix of the node
  16091. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16092. * @returns the world matrix
  16093. */
  16094. Node.prototype.computeWorldMatrix = function (force) {
  16095. return BABYLON.Matrix.Identity();
  16096. };
  16097. /**
  16098. * Releases resources associated with this node.
  16099. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16100. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16101. */
  16102. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16103. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16104. if (!doNotRecurse) {
  16105. var nodes = this.getDescendants(true);
  16106. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16107. var node = nodes_1[_i];
  16108. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16109. }
  16110. }
  16111. else {
  16112. var transformNodes = this.getChildTransformNodes(true);
  16113. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16114. var transformNode = transformNodes_1[_a];
  16115. transformNode.parent = null;
  16116. transformNode.computeWorldMatrix(true);
  16117. }
  16118. }
  16119. this.parent = null;
  16120. // Callback
  16121. this.onDisposeObservable.notifyObservers(this);
  16122. this.onDisposeObservable.clear();
  16123. // Behaviors
  16124. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16125. var behavior = _c[_b];
  16126. behavior.detach();
  16127. }
  16128. this._behaviors = [];
  16129. this._isDisposed = true;
  16130. };
  16131. /**
  16132. * Parse animation range data from a serialization object and store them into a given node
  16133. * @param node defines where to store the animation ranges
  16134. * @param parsedNode defines the serialization object to read data from
  16135. * @param scene defines the hosting scene
  16136. */
  16137. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16138. if (parsedNode.ranges) {
  16139. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16140. var data = parsedNode.ranges[index];
  16141. node.createAnimationRange(data.name, data.from, data.to);
  16142. }
  16143. }
  16144. };
  16145. __decorate([
  16146. BABYLON.serialize()
  16147. ], Node.prototype, "name", void 0);
  16148. __decorate([
  16149. BABYLON.serialize()
  16150. ], Node.prototype, "id", void 0);
  16151. __decorate([
  16152. BABYLON.serialize()
  16153. ], Node.prototype, "uniqueId", void 0);
  16154. __decorate([
  16155. BABYLON.serialize()
  16156. ], Node.prototype, "state", void 0);
  16157. __decorate([
  16158. BABYLON.serialize()
  16159. ], Node.prototype, "metadata", void 0);
  16160. return Node;
  16161. }());
  16162. BABYLON.Node = Node;
  16163. })(BABYLON || (BABYLON = {}));
  16164. //# sourceMappingURL=babylon.node.js.map
  16165. "use strict";
  16166. var BABYLON;
  16167. (function (BABYLON) {
  16168. var BoundingSphere = /** @class */ (function () {
  16169. function BoundingSphere(minimum, maximum) {
  16170. this.minimum = minimum;
  16171. this.maximum = maximum;
  16172. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16173. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16174. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16175. this.radius = distance * 0.5;
  16176. this.centerWorld = BABYLON.Vector3.Zero();
  16177. this._update(BABYLON.Matrix.Identity());
  16178. }
  16179. // Methods
  16180. BoundingSphere.prototype._update = function (world) {
  16181. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16182. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16183. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16184. };
  16185. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16186. for (var i = 0; i < 6; i++) {
  16187. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16188. return false;
  16189. }
  16190. return true;
  16191. };
  16192. BoundingSphere.prototype.intersectsPoint = function (point) {
  16193. var x = this.centerWorld.x - point.x;
  16194. var y = this.centerWorld.y - point.y;
  16195. var z = this.centerWorld.z - point.z;
  16196. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16197. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16198. return false;
  16199. return true;
  16200. };
  16201. // Statics
  16202. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16203. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16204. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16205. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16206. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16207. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16208. return false;
  16209. return true;
  16210. };
  16211. return BoundingSphere;
  16212. }());
  16213. BABYLON.BoundingSphere = BoundingSphere;
  16214. })(BABYLON || (BABYLON = {}));
  16215. //# sourceMappingURL=babylon.boundingSphere.js.map
  16216. "use strict";
  16217. var BABYLON;
  16218. (function (BABYLON) {
  16219. var BoundingBox = /** @class */ (function () {
  16220. function BoundingBox(minimum, maximum) {
  16221. this.minimum = minimum;
  16222. this.maximum = maximum;
  16223. this.vectors = new Array();
  16224. this.vectorsWorld = new Array();
  16225. // Bounding vectors
  16226. this.vectors.push(this.minimum.clone());
  16227. this.vectors.push(this.maximum.clone());
  16228. this.vectors.push(this.minimum.clone());
  16229. this.vectors[2].x = this.maximum.x;
  16230. this.vectors.push(this.minimum.clone());
  16231. this.vectors[3].y = this.maximum.y;
  16232. this.vectors.push(this.minimum.clone());
  16233. this.vectors[4].z = this.maximum.z;
  16234. this.vectors.push(this.maximum.clone());
  16235. this.vectors[5].z = this.minimum.z;
  16236. this.vectors.push(this.maximum.clone());
  16237. this.vectors[6].x = this.minimum.x;
  16238. this.vectors.push(this.maximum.clone());
  16239. this.vectors[7].y = this.minimum.y;
  16240. // OBB
  16241. this.center = this.maximum.add(this.minimum).scale(0.5);
  16242. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16243. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16244. // World
  16245. for (var index = 0; index < this.vectors.length; index++) {
  16246. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16247. }
  16248. this.minimumWorld = BABYLON.Vector3.Zero();
  16249. this.maximumWorld = BABYLON.Vector3.Zero();
  16250. this.centerWorld = BABYLON.Vector3.Zero();
  16251. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16252. this._update(BABYLON.Matrix.Identity());
  16253. }
  16254. // Methods
  16255. BoundingBox.prototype.getWorldMatrix = function () {
  16256. return this._worldMatrix;
  16257. };
  16258. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16259. this._worldMatrix.copyFrom(matrix);
  16260. return this;
  16261. };
  16262. BoundingBox.prototype._update = function (world) {
  16263. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16264. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16265. for (var index = 0; index < this.vectors.length; index++) {
  16266. var v = this.vectorsWorld[index];
  16267. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16268. if (v.x < this.minimumWorld.x)
  16269. this.minimumWorld.x = v.x;
  16270. if (v.y < this.minimumWorld.y)
  16271. this.minimumWorld.y = v.y;
  16272. if (v.z < this.minimumWorld.z)
  16273. this.minimumWorld.z = v.z;
  16274. if (v.x > this.maximumWorld.x)
  16275. this.maximumWorld.x = v.x;
  16276. if (v.y > this.maximumWorld.y)
  16277. this.maximumWorld.y = v.y;
  16278. if (v.z > this.maximumWorld.z)
  16279. this.maximumWorld.z = v.z;
  16280. }
  16281. // Extend
  16282. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16283. this.extendSizeWorld.scaleInPlace(0.5);
  16284. // OBB
  16285. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16286. this.centerWorld.scaleInPlace(0.5);
  16287. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16288. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16289. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16290. this._worldMatrix = world;
  16291. };
  16292. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16293. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16294. };
  16295. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16296. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16297. };
  16298. BoundingBox.prototype.intersectsPoint = function (point) {
  16299. var delta = -BABYLON.Epsilon;
  16300. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16301. return false;
  16302. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16303. return false;
  16304. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16305. return false;
  16306. return true;
  16307. };
  16308. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16309. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16310. };
  16311. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16312. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16313. return false;
  16314. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16315. return false;
  16316. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16317. return false;
  16318. return true;
  16319. };
  16320. // Statics
  16321. BoundingBox.Intersects = function (box0, box1) {
  16322. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16323. return false;
  16324. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16325. return false;
  16326. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16327. return false;
  16328. return true;
  16329. };
  16330. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16331. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16332. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16333. return (num <= (sphereRadius * sphereRadius));
  16334. };
  16335. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16336. for (var p = 0; p < 6; p++) {
  16337. for (var i = 0; i < 8; i++) {
  16338. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16339. return false;
  16340. }
  16341. }
  16342. }
  16343. return true;
  16344. };
  16345. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16346. for (var p = 0; p < 6; p++) {
  16347. var inCount = 8;
  16348. for (var i = 0; i < 8; i++) {
  16349. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16350. --inCount;
  16351. }
  16352. else {
  16353. break;
  16354. }
  16355. }
  16356. if (inCount === 0)
  16357. return false;
  16358. }
  16359. return true;
  16360. };
  16361. return BoundingBox;
  16362. }());
  16363. BABYLON.BoundingBox = BoundingBox;
  16364. })(BABYLON || (BABYLON = {}));
  16365. //# sourceMappingURL=babylon.boundingBox.js.map
  16366. "use strict";
  16367. var BABYLON;
  16368. (function (BABYLON) {
  16369. var computeBoxExtents = function (axis, box) {
  16370. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16371. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16372. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16373. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16374. var r = r0 + r1 + r2;
  16375. return {
  16376. min: p - r,
  16377. max: p + r
  16378. };
  16379. };
  16380. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16381. var axisOverlap = function (axis, box0, box1) {
  16382. var result0 = computeBoxExtents(axis, box0);
  16383. var result1 = computeBoxExtents(axis, box1);
  16384. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16385. };
  16386. var BoundingInfo = /** @class */ (function () {
  16387. function BoundingInfo(minimum, maximum) {
  16388. this.minimum = minimum;
  16389. this.maximum = maximum;
  16390. this._isLocked = false;
  16391. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16392. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16393. }
  16394. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16395. get: function () {
  16396. return this._isLocked;
  16397. },
  16398. set: function (value) {
  16399. this._isLocked = value;
  16400. },
  16401. enumerable: true,
  16402. configurable: true
  16403. });
  16404. // Methods
  16405. BoundingInfo.prototype.update = function (world) {
  16406. if (this._isLocked) {
  16407. return;
  16408. }
  16409. this.boundingBox._update(world);
  16410. this.boundingSphere._update(world);
  16411. };
  16412. /**
  16413. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16414. * @param center New center of the bounding info
  16415. * @param extend New extend of the bounding info
  16416. */
  16417. BoundingInfo.prototype.centerOn = function (center, extend) {
  16418. this.minimum = center.subtract(extend);
  16419. this.maximum = center.add(extend);
  16420. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16421. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16422. return this;
  16423. };
  16424. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16425. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16426. return false;
  16427. return this.boundingBox.isInFrustum(frustumPlanes);
  16428. };
  16429. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16430. /**
  16431. * Gets the world distance between the min and max points of the bounding box
  16432. */
  16433. get: function () {
  16434. var boundingBox = this.boundingBox;
  16435. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16436. return size.length();
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16442. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16443. };
  16444. BoundingInfo.prototype._checkCollision = function (collider) {
  16445. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16446. };
  16447. BoundingInfo.prototype.intersectsPoint = function (point) {
  16448. if (!this.boundingSphere.centerWorld) {
  16449. return false;
  16450. }
  16451. if (!this.boundingSphere.intersectsPoint(point)) {
  16452. return false;
  16453. }
  16454. if (!this.boundingBox.intersectsPoint(point)) {
  16455. return false;
  16456. }
  16457. return true;
  16458. };
  16459. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16460. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16461. return false;
  16462. }
  16463. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16464. return false;
  16465. }
  16466. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16467. return false;
  16468. }
  16469. if (!precise) {
  16470. return true;
  16471. }
  16472. var box0 = this.boundingBox;
  16473. var box1 = boundingInfo.boundingBox;
  16474. if (!axisOverlap(box0.directions[0], box0, box1))
  16475. return false;
  16476. if (!axisOverlap(box0.directions[1], box0, box1))
  16477. return false;
  16478. if (!axisOverlap(box0.directions[2], box0, box1))
  16479. return false;
  16480. if (!axisOverlap(box1.directions[0], box0, box1))
  16481. return false;
  16482. if (!axisOverlap(box1.directions[1], box0, box1))
  16483. return false;
  16484. if (!axisOverlap(box1.directions[2], box0, box1))
  16485. return false;
  16486. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16487. return false;
  16488. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16489. return false;
  16490. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16491. return false;
  16492. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16493. return false;
  16494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16495. return false;
  16496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16497. return false;
  16498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16499. return false;
  16500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16501. return false;
  16502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16503. return false;
  16504. return true;
  16505. };
  16506. return BoundingInfo;
  16507. }());
  16508. BABYLON.BoundingInfo = BoundingInfo;
  16509. })(BABYLON || (BABYLON = {}));
  16510. //# sourceMappingURL=babylon.boundingInfo.js.map
  16511. "use strict";
  16512. var BABYLON;
  16513. (function (BABYLON) {
  16514. var TransformNode = /** @class */ (function (_super) {
  16515. __extends(TransformNode, _super);
  16516. function TransformNode(name, scene, isPure) {
  16517. if (scene === void 0) { scene = null; }
  16518. if (isPure === void 0) { isPure = true; }
  16519. var _this = _super.call(this, name, scene) || this;
  16520. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16521. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16522. _this._up = new BABYLON.Vector3(0, 1, 0);
  16523. _this._right = new BABYLON.Vector3(1, 0, 0);
  16524. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16525. // Properties
  16526. _this._rotation = BABYLON.Vector3.Zero();
  16527. _this._scaling = BABYLON.Vector3.One();
  16528. _this._isDirty = false;
  16529. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16530. _this.scalingDeterminant = 1;
  16531. _this.infiniteDistance = false;
  16532. _this.position = BABYLON.Vector3.Zero();
  16533. _this._localWorld = BABYLON.Matrix.Zero();
  16534. _this._worldMatrix = BABYLON.Matrix.Zero();
  16535. _this._worldMatrixDeterminant = 0;
  16536. _this._absolutePosition = BABYLON.Vector3.Zero();
  16537. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16538. _this._postMultiplyPivotMatrix = false;
  16539. _this._isWorldMatrixFrozen = false;
  16540. /**
  16541. * An event triggered after the world matrix is updated
  16542. */
  16543. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16544. _this._nonUniformScaling = false;
  16545. if (isPure) {
  16546. _this.getScene().addTransformNode(_this);
  16547. }
  16548. return _this;
  16549. }
  16550. /**
  16551. * Gets a string idenfifying the name of the class
  16552. * @returns "TransformNode" string
  16553. */
  16554. TransformNode.prototype.getClassName = function () {
  16555. return "TransformNode";
  16556. };
  16557. Object.defineProperty(TransformNode.prototype, "rotation", {
  16558. /**
  16559. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16560. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16561. * Default : (0.0, 0.0, 0.0)
  16562. */
  16563. get: function () {
  16564. return this._rotation;
  16565. },
  16566. set: function (newRotation) {
  16567. this._rotation = newRotation;
  16568. },
  16569. enumerable: true,
  16570. configurable: true
  16571. });
  16572. Object.defineProperty(TransformNode.prototype, "scaling", {
  16573. /**
  16574. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16575. * Default : (1.0, 1.0, 1.0)
  16576. */
  16577. get: function () {
  16578. return this._scaling;
  16579. },
  16580. /**
  16581. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16582. * Default : (1.0, 1.0, 1.0)
  16583. */
  16584. set: function (newScaling) {
  16585. this._scaling = newScaling;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16591. /**
  16592. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16593. * It's null by default.
  16594. * 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)
  16595. */
  16596. get: function () {
  16597. return this._rotationQuaternion;
  16598. },
  16599. set: function (quaternion) {
  16600. this._rotationQuaternion = quaternion;
  16601. //reset the rotation vector.
  16602. if (quaternion && this.rotation.length()) {
  16603. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16604. }
  16605. },
  16606. enumerable: true,
  16607. configurable: true
  16608. });
  16609. Object.defineProperty(TransformNode.prototype, "forward", {
  16610. /**
  16611. * The forward direction of that transform in world space.
  16612. */
  16613. get: function () {
  16614. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16615. },
  16616. enumerable: true,
  16617. configurable: true
  16618. });
  16619. Object.defineProperty(TransformNode.prototype, "up", {
  16620. /**
  16621. * The up direction of that transform in world space.
  16622. */
  16623. get: function () {
  16624. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(TransformNode.prototype, "right", {
  16630. /**
  16631. * The right direction of that transform in world space.
  16632. */
  16633. get: function () {
  16634. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. /**
  16640. * Returns the latest update of the World matrix
  16641. * Returns a Matrix.
  16642. */
  16643. TransformNode.prototype.getWorldMatrix = function () {
  16644. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16645. this.computeWorldMatrix();
  16646. }
  16647. return this._worldMatrix;
  16648. };
  16649. /**
  16650. * Returns the latest update of the World matrix determinant.
  16651. */
  16652. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16653. return this._worldMatrixDeterminant;
  16654. };
  16655. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16656. /**
  16657. * Returns directly the latest state of the mesh World matrix.
  16658. * A Matrix is returned.
  16659. */
  16660. get: function () {
  16661. return this._worldMatrix;
  16662. },
  16663. enumerable: true,
  16664. configurable: true
  16665. });
  16666. /**
  16667. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16668. * Returns the TransformNode.
  16669. */
  16670. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16671. this._poseMatrix.copyFrom(matrix);
  16672. return this;
  16673. };
  16674. /**
  16675. * Returns the mesh Pose matrix.
  16676. * Returned object : Matrix
  16677. */
  16678. TransformNode.prototype.getPoseMatrix = function () {
  16679. return this._poseMatrix;
  16680. };
  16681. TransformNode.prototype._isSynchronized = function () {
  16682. if (this._isDirty) {
  16683. return false;
  16684. }
  16685. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16686. return false;
  16687. if (this._cache.pivotMatrixUpdated) {
  16688. return false;
  16689. }
  16690. if (this.infiniteDistance) {
  16691. return false;
  16692. }
  16693. if (!this._cache.position.equals(this.position))
  16694. return false;
  16695. if (this.rotationQuaternion) {
  16696. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16697. return false;
  16698. }
  16699. if (!this._cache.rotation.equals(this.rotation))
  16700. return false;
  16701. if (!this._cache.scaling.equals(this.scaling))
  16702. return false;
  16703. return true;
  16704. };
  16705. TransformNode.prototype._initCache = function () {
  16706. _super.prototype._initCache.call(this);
  16707. this._cache.localMatrixUpdated = false;
  16708. this._cache.position = BABYLON.Vector3.Zero();
  16709. this._cache.scaling = BABYLON.Vector3.Zero();
  16710. this._cache.rotation = BABYLON.Vector3.Zero();
  16711. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16712. this._cache.billboardMode = -1;
  16713. };
  16714. TransformNode.prototype.markAsDirty = function (property) {
  16715. if (property === "rotation") {
  16716. this.rotationQuaternion = null;
  16717. }
  16718. this._currentRenderId = Number.MAX_VALUE;
  16719. this._isDirty = true;
  16720. return this;
  16721. };
  16722. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16723. /**
  16724. * Returns the current mesh absolute position.
  16725. * Retuns a Vector3.
  16726. */
  16727. get: function () {
  16728. return this._absolutePosition;
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. /**
  16734. * Sets a new matrix to apply before all other transformation
  16735. * @param matrix defines the transform matrix
  16736. * @returns the current TransformNode
  16737. */
  16738. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16739. return this.setPivotMatrix(matrix, false);
  16740. };
  16741. /**
  16742. * Sets a new pivot matrix to the current node
  16743. * @param matrix defines the new pivot matrix to use
  16744. * @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
  16745. * @returns the current TransformNode
  16746. */
  16747. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16748. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16749. this._pivotMatrix = matrix.clone();
  16750. this._cache.pivotMatrixUpdated = true;
  16751. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16752. if (this._postMultiplyPivotMatrix) {
  16753. if (!this._pivotMatrixInverse) {
  16754. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16755. }
  16756. else {
  16757. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16758. }
  16759. }
  16760. return this;
  16761. };
  16762. /**
  16763. * Returns the mesh pivot matrix.
  16764. * Default : Identity.
  16765. * A Matrix is returned.
  16766. */
  16767. TransformNode.prototype.getPivotMatrix = function () {
  16768. return this._pivotMatrix;
  16769. };
  16770. /**
  16771. * Prevents the World matrix to be computed any longer.
  16772. * Returns the TransformNode.
  16773. */
  16774. TransformNode.prototype.freezeWorldMatrix = function () {
  16775. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16776. this.computeWorldMatrix(true);
  16777. this._isWorldMatrixFrozen = true;
  16778. return this;
  16779. };
  16780. /**
  16781. * Allows back the World matrix computation.
  16782. * Returns the TransformNode.
  16783. */
  16784. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16785. this._isWorldMatrixFrozen = false;
  16786. this.computeWorldMatrix(true);
  16787. return this;
  16788. };
  16789. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16790. /**
  16791. * True if the World matrix has been frozen.
  16792. * Returns a boolean.
  16793. */
  16794. get: function () {
  16795. return this._isWorldMatrixFrozen;
  16796. },
  16797. enumerable: true,
  16798. configurable: true
  16799. });
  16800. /**
  16801. * Retuns the mesh absolute position in the World.
  16802. * Returns a Vector3.
  16803. */
  16804. TransformNode.prototype.getAbsolutePosition = function () {
  16805. this.computeWorldMatrix();
  16806. return this._absolutePosition;
  16807. };
  16808. /**
  16809. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16810. * Returns the TransformNode.
  16811. */
  16812. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16813. if (!absolutePosition) {
  16814. return this;
  16815. }
  16816. var absolutePositionX;
  16817. var absolutePositionY;
  16818. var absolutePositionZ;
  16819. if (absolutePosition.x === undefined) {
  16820. if (arguments.length < 3) {
  16821. return this;
  16822. }
  16823. absolutePositionX = arguments[0];
  16824. absolutePositionY = arguments[1];
  16825. absolutePositionZ = arguments[2];
  16826. }
  16827. else {
  16828. absolutePositionX = absolutePosition.x;
  16829. absolutePositionY = absolutePosition.y;
  16830. absolutePositionZ = absolutePosition.z;
  16831. }
  16832. if (this.parent) {
  16833. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16834. invertParentWorldMatrix.invert();
  16835. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16836. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16837. }
  16838. else {
  16839. this.position.x = absolutePositionX;
  16840. this.position.y = absolutePositionY;
  16841. this.position.z = absolutePositionZ;
  16842. }
  16843. return this;
  16844. };
  16845. /**
  16846. * Sets the mesh position in its local space.
  16847. * Returns the TransformNode.
  16848. */
  16849. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16850. this.computeWorldMatrix();
  16851. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16852. return this;
  16853. };
  16854. /**
  16855. * Returns the mesh position in the local space from the current World matrix values.
  16856. * Returns a new Vector3.
  16857. */
  16858. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16859. this.computeWorldMatrix();
  16860. var invLocalWorldMatrix = this._localWorld.clone();
  16861. invLocalWorldMatrix.invert();
  16862. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16863. };
  16864. /**
  16865. * Translates the mesh along the passed Vector3 in its local space.
  16866. * Returns the TransformNode.
  16867. */
  16868. TransformNode.prototype.locallyTranslate = function (vector3) {
  16869. this.computeWorldMatrix(true);
  16870. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16871. return this;
  16872. };
  16873. /**
  16874. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16875. * @param targetPoint the position (must be in same space as current mesh) to look at
  16876. * @param yawCor optional yaw (y-axis) correction in radians
  16877. * @param pitchCor optional pitch (x-axis) correction in radians
  16878. * @param rollCor optional roll (z-axis) correction in radians
  16879. * @param space the choosen space of the target
  16880. * @returns the TransformNode.
  16881. */
  16882. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16883. if (yawCor === void 0) { yawCor = 0; }
  16884. if (pitchCor === void 0) { pitchCor = 0; }
  16885. if (rollCor === void 0) { rollCor = 0; }
  16886. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16887. var dv = TransformNode._lookAtVectorCache;
  16888. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16889. targetPoint.subtractToRef(pos, dv);
  16890. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16891. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16892. var pitch = Math.atan2(dv.y, len);
  16893. if (this.rotationQuaternion) {
  16894. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16895. }
  16896. else {
  16897. this.rotation.x = pitch + pitchCor;
  16898. this.rotation.y = yaw + yawCor;
  16899. this.rotation.z = rollCor;
  16900. }
  16901. return this;
  16902. };
  16903. /**
  16904. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16905. * This Vector3 is expressed in the World space.
  16906. */
  16907. TransformNode.prototype.getDirection = function (localAxis) {
  16908. var result = BABYLON.Vector3.Zero();
  16909. this.getDirectionToRef(localAxis, result);
  16910. return result;
  16911. };
  16912. /**
  16913. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16914. * localAxis is expressed in the mesh local space.
  16915. * result is computed in the Wordl space from the mesh World matrix.
  16916. * Returns the TransformNode.
  16917. */
  16918. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16919. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16920. return this;
  16921. };
  16922. /**
  16923. * Sets a new pivot point to the current node
  16924. * @param point defines the new pivot point to use
  16925. * @param space defines if the point is in world or local space (local by default)
  16926. * @returns the current TransformNode
  16927. */
  16928. TransformNode.prototype.setPivotPoint = function (point, space) {
  16929. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16930. if (this.getScene().getRenderId() == 0) {
  16931. this.computeWorldMatrix(true);
  16932. }
  16933. var wm = this.getWorldMatrix();
  16934. if (space == BABYLON.Space.WORLD) {
  16935. var tmat = BABYLON.Tmp.Matrix[0];
  16936. wm.invertToRef(tmat);
  16937. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16938. }
  16939. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16940. };
  16941. /**
  16942. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16943. */
  16944. TransformNode.prototype.getPivotPoint = function () {
  16945. var point = BABYLON.Vector3.Zero();
  16946. this.getPivotPointToRef(point);
  16947. return point;
  16948. };
  16949. /**
  16950. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16951. * Returns the TransformNode.
  16952. */
  16953. TransformNode.prototype.getPivotPointToRef = function (result) {
  16954. result.x = -this._pivotMatrix.m[12];
  16955. result.y = -this._pivotMatrix.m[13];
  16956. result.z = -this._pivotMatrix.m[14];
  16957. return this;
  16958. };
  16959. /**
  16960. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16961. */
  16962. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16963. var point = BABYLON.Vector3.Zero();
  16964. this.getAbsolutePivotPointToRef(point);
  16965. return point;
  16966. };
  16967. /**
  16968. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16969. * Returns the TransformNode.
  16970. */
  16971. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16972. result.x = this._pivotMatrix.m[12];
  16973. result.y = this._pivotMatrix.m[13];
  16974. result.z = this._pivotMatrix.m[14];
  16975. this.getPivotPointToRef(result);
  16976. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16977. return this;
  16978. };
  16979. /**
  16980. * Defines the passed node as the parent of the current node.
  16981. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16982. * Returns the TransformNode.
  16983. */
  16984. TransformNode.prototype.setParent = function (node) {
  16985. if (node === null) {
  16986. var rotation = BABYLON.Tmp.Quaternion[0];
  16987. var position = BABYLON.Tmp.Vector3[0];
  16988. var scale = BABYLON.Tmp.Vector3[1];
  16989. if (this.parent && this.parent.computeWorldMatrix) {
  16990. this.parent.computeWorldMatrix(true);
  16991. }
  16992. this.computeWorldMatrix(true);
  16993. this.getWorldMatrix().decompose(scale, rotation, position);
  16994. if (this.rotationQuaternion) {
  16995. this.rotationQuaternion.copyFrom(rotation);
  16996. }
  16997. else {
  16998. rotation.toEulerAnglesToRef(this.rotation);
  16999. }
  17000. this.scaling.x = scale.x;
  17001. this.scaling.y = scale.y;
  17002. this.scaling.z = scale.z;
  17003. this.position.x = position.x;
  17004. this.position.y = position.y;
  17005. this.position.z = position.z;
  17006. }
  17007. else {
  17008. var rotation = BABYLON.Tmp.Quaternion[0];
  17009. var position = BABYLON.Tmp.Vector3[0];
  17010. var scale = BABYLON.Tmp.Vector3[1];
  17011. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17012. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17013. this.computeWorldMatrix(true);
  17014. node.computeWorldMatrix(true);
  17015. node.getWorldMatrix().invertToRef(invParentMatrix);
  17016. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17017. diffMatrix.decompose(scale, rotation, position);
  17018. if (this.rotationQuaternion) {
  17019. this.rotationQuaternion.copyFrom(rotation);
  17020. }
  17021. else {
  17022. rotation.toEulerAnglesToRef(this.rotation);
  17023. }
  17024. this.position.x = position.x;
  17025. this.position.y = position.y;
  17026. this.position.z = position.z;
  17027. this.scaling.x = scale.x;
  17028. this.scaling.y = scale.y;
  17029. this.scaling.z = scale.z;
  17030. }
  17031. this.parent = node;
  17032. return this;
  17033. };
  17034. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17035. get: function () {
  17036. return this._nonUniformScaling;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17042. if (this._nonUniformScaling === value) {
  17043. return false;
  17044. }
  17045. this._nonUniformScaling = true;
  17046. return true;
  17047. };
  17048. /**
  17049. * Attach the current TransformNode to another TransformNode associated with a bone
  17050. * @param bone Bone affecting the TransformNode
  17051. * @param affectedTransformNode TransformNode associated with the bone
  17052. */
  17053. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17054. this._transformToBoneReferal = affectedTransformNode;
  17055. this.parent = bone;
  17056. if (bone.getWorldMatrix().determinant() < 0) {
  17057. this.scalingDeterminant *= -1;
  17058. }
  17059. return this;
  17060. };
  17061. TransformNode.prototype.detachFromBone = function () {
  17062. if (!this.parent) {
  17063. return this;
  17064. }
  17065. if (this.parent.getWorldMatrix().determinant() < 0) {
  17066. this.scalingDeterminant *= -1;
  17067. }
  17068. this._transformToBoneReferal = null;
  17069. this.parent = null;
  17070. return this;
  17071. };
  17072. /**
  17073. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17074. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17075. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17076. * The passed axis is also normalized.
  17077. * Returns the TransformNode.
  17078. */
  17079. TransformNode.prototype.rotate = function (axis, amount, space) {
  17080. axis.normalize();
  17081. if (!this.rotationQuaternion) {
  17082. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17083. this.rotation = BABYLON.Vector3.Zero();
  17084. }
  17085. var rotationQuaternion;
  17086. if (!space || space === BABYLON.Space.LOCAL) {
  17087. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17088. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17089. }
  17090. else {
  17091. if (this.parent) {
  17092. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17093. invertParentWorldMatrix.invert();
  17094. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17095. }
  17096. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17097. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17098. }
  17099. return this;
  17100. };
  17101. /**
  17102. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17103. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17104. * The passed axis is also normalized.
  17105. * Returns the TransformNode.
  17106. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17107. */
  17108. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17109. axis.normalize();
  17110. if (!this.rotationQuaternion) {
  17111. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17112. this.rotation.copyFromFloats(0, 0, 0);
  17113. }
  17114. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17115. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17116. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17117. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17118. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17119. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17120. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17121. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17122. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17123. return this;
  17124. };
  17125. /**
  17126. * Translates the mesh along the axis vector for the passed distance in the given space.
  17127. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17128. * Returns the TransformNode.
  17129. */
  17130. TransformNode.prototype.translate = function (axis, distance, space) {
  17131. var displacementVector = axis.scale(distance);
  17132. if (!space || space === BABYLON.Space.LOCAL) {
  17133. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17134. this.setPositionWithLocalVector(tempV3);
  17135. }
  17136. else {
  17137. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17138. }
  17139. return this;
  17140. };
  17141. /**
  17142. * Adds a rotation step to the mesh current rotation.
  17143. * x, y, z are Euler angles expressed in radians.
  17144. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17145. * This means this rotation is made in the mesh local space only.
  17146. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17147. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17148. * ```javascript
  17149. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17150. * ```
  17151. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17152. * 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.
  17153. * Returns the TransformNode.
  17154. */
  17155. TransformNode.prototype.addRotation = function (x, y, z) {
  17156. var rotationQuaternion;
  17157. if (this.rotationQuaternion) {
  17158. rotationQuaternion = this.rotationQuaternion;
  17159. }
  17160. else {
  17161. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17162. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17163. }
  17164. var accumulation = BABYLON.Tmp.Quaternion[0];
  17165. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17166. rotationQuaternion.multiplyInPlace(accumulation);
  17167. if (!this.rotationQuaternion) {
  17168. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17169. }
  17170. return this;
  17171. };
  17172. /**
  17173. * Computes the mesh World matrix and returns it.
  17174. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17175. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17176. * If the parameter `force`is set to `true`, the actual computation is done.
  17177. * Returns the mesh World Matrix.
  17178. */
  17179. TransformNode.prototype.computeWorldMatrix = function (force) {
  17180. if (this._isWorldMatrixFrozen) {
  17181. return this._worldMatrix;
  17182. }
  17183. if (!force && this.isSynchronized(true)) {
  17184. this._currentRenderId = this.getScene().getRenderId();
  17185. return this._worldMatrix;
  17186. }
  17187. this._cache.position.copyFrom(this.position);
  17188. this._cache.scaling.copyFrom(this.scaling);
  17189. this._cache.pivotMatrixUpdated = false;
  17190. this._cache.billboardMode = this.billboardMode;
  17191. this._currentRenderId = this.getScene().getRenderId();
  17192. this._childRenderId = this.getScene().getRenderId();
  17193. this._isDirty = false;
  17194. // Scaling
  17195. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17196. // Rotation
  17197. //rotate, if quaternion is set and rotation was used
  17198. if (this.rotationQuaternion) {
  17199. var len = this.rotation.length();
  17200. if (len) {
  17201. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17202. this.rotation.copyFromFloats(0, 0, 0);
  17203. }
  17204. }
  17205. if (this.rotationQuaternion) {
  17206. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17207. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17208. }
  17209. else {
  17210. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17211. this._cache.rotation.copyFrom(this.rotation);
  17212. }
  17213. // Translation
  17214. var camera = this.getScene().activeCamera;
  17215. if (this.infiniteDistance && !this.parent && camera) {
  17216. var cameraWorldMatrix = camera.getWorldMatrix();
  17217. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17218. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17219. }
  17220. else {
  17221. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17222. }
  17223. // Composing transformations
  17224. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17225. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17226. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17227. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17228. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17229. // Need to decompose each rotation here
  17230. var currentPosition = BABYLON.Tmp.Vector3[3];
  17231. if (this.parent && this.parent.getWorldMatrix) {
  17232. if (this._transformToBoneReferal) {
  17233. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17234. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17235. }
  17236. else {
  17237. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17238. }
  17239. }
  17240. else {
  17241. currentPosition.copyFrom(this.position);
  17242. }
  17243. currentPosition.subtractInPlace(camera.globalPosition);
  17244. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17245. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17246. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17247. }
  17248. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17249. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17250. }
  17251. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17252. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17253. }
  17254. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17255. }
  17256. else {
  17257. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17258. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17259. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17260. }
  17261. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17262. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17263. }
  17264. // Local world
  17265. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17266. // Parent
  17267. if (this.parent && this.parent.getWorldMatrix) {
  17268. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17269. if (this._transformToBoneReferal) {
  17270. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17271. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17272. }
  17273. else {
  17274. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17275. }
  17276. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17277. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17278. this._worldMatrix.copyFrom(this._localWorld);
  17279. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17280. }
  17281. else {
  17282. if (this._transformToBoneReferal) {
  17283. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17284. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17285. }
  17286. else {
  17287. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17288. }
  17289. }
  17290. this._markSyncedWithParent();
  17291. }
  17292. else {
  17293. this._worldMatrix.copyFrom(this._localWorld);
  17294. }
  17295. // Post multiply inverse of pivotMatrix
  17296. if (this._postMultiplyPivotMatrix) {
  17297. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17298. }
  17299. // Normal matrix
  17300. if (this.scaling.isNonUniform) {
  17301. this._updateNonUniformScalingState(true);
  17302. }
  17303. else if (this.parent && this.parent._nonUniformScaling) {
  17304. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17305. }
  17306. else {
  17307. this._updateNonUniformScalingState(false);
  17308. }
  17309. this._afterComputeWorldMatrix();
  17310. // Absolute position
  17311. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17312. // Callbacks
  17313. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17314. if (!this._poseMatrix) {
  17315. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17316. }
  17317. // Cache the determinant
  17318. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17319. return this._worldMatrix;
  17320. };
  17321. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17322. };
  17323. /**
  17324. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17325. * @param func: callback function to add
  17326. *
  17327. * Returns the TransformNode.
  17328. */
  17329. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17330. this.onAfterWorldMatrixUpdateObservable.add(func);
  17331. return this;
  17332. };
  17333. /**
  17334. * Removes a registered callback function.
  17335. * Returns the TransformNode.
  17336. */
  17337. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17338. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17339. return this;
  17340. };
  17341. /**
  17342. * Clone the current transform node
  17343. * Returns the new transform node
  17344. * @param name Name of the new clone
  17345. * @param newParent New parent for the clone
  17346. * @param doNotCloneChildren Do not clone children hierarchy
  17347. */
  17348. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17349. var _this = this;
  17350. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17351. result.name = name;
  17352. result.id = name;
  17353. if (newParent) {
  17354. result.parent = newParent;
  17355. }
  17356. if (!doNotCloneChildren) {
  17357. // Children
  17358. var directDescendants = this.getDescendants(true);
  17359. for (var index = 0; index < directDescendants.length; index++) {
  17360. var child = directDescendants[index];
  17361. if (child.clone) {
  17362. child.clone(name + "." + child.name, result);
  17363. }
  17364. }
  17365. }
  17366. return result;
  17367. };
  17368. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17369. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17370. serializationObject.type = this.getClassName();
  17371. // Parent
  17372. if (this.parent) {
  17373. serializationObject.parentId = this.parent.id;
  17374. }
  17375. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17376. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17377. }
  17378. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17379. serializationObject.isEnabled = this.isEnabled();
  17380. // Parent
  17381. if (this.parent) {
  17382. serializationObject.parentId = this.parent.id;
  17383. }
  17384. return serializationObject;
  17385. };
  17386. // Statics
  17387. /**
  17388. * Returns a new TransformNode object parsed from the source provided.
  17389. * The parameter `parsedMesh` is the source.
  17390. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17391. */
  17392. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17393. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17394. if (BABYLON.Tags) {
  17395. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17396. }
  17397. if (parsedTransformNode.localMatrix) {
  17398. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17399. }
  17400. else if (parsedTransformNode.pivotMatrix) {
  17401. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17402. }
  17403. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17404. // Parent
  17405. if (parsedTransformNode.parentId) {
  17406. transformNode._waitingParentId = parsedTransformNode.parentId;
  17407. }
  17408. return transformNode;
  17409. };
  17410. /**
  17411. * Releases resources associated with this transform node.
  17412. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17413. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17414. */
  17415. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17416. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17417. // Animations
  17418. this.getScene().stopAnimation(this);
  17419. // Remove from scene
  17420. this.getScene().removeTransformNode(this);
  17421. this.onAfterWorldMatrixUpdateObservable.clear();
  17422. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17423. };
  17424. // Statics
  17425. TransformNode.BILLBOARDMODE_NONE = 0;
  17426. TransformNode.BILLBOARDMODE_X = 1;
  17427. TransformNode.BILLBOARDMODE_Y = 2;
  17428. TransformNode.BILLBOARDMODE_Z = 4;
  17429. TransformNode.BILLBOARDMODE_ALL = 7;
  17430. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17431. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17432. __decorate([
  17433. BABYLON.serializeAsVector3()
  17434. ], TransformNode.prototype, "_rotation", void 0);
  17435. __decorate([
  17436. BABYLON.serializeAsQuaternion()
  17437. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17438. __decorate([
  17439. BABYLON.serializeAsVector3()
  17440. ], TransformNode.prototype, "_scaling", void 0);
  17441. __decorate([
  17442. BABYLON.serialize()
  17443. ], TransformNode.prototype, "billboardMode", void 0);
  17444. __decorate([
  17445. BABYLON.serialize()
  17446. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17447. __decorate([
  17448. BABYLON.serialize()
  17449. ], TransformNode.prototype, "infiniteDistance", void 0);
  17450. __decorate([
  17451. BABYLON.serializeAsVector3()
  17452. ], TransformNode.prototype, "position", void 0);
  17453. return TransformNode;
  17454. }(BABYLON.Node));
  17455. BABYLON.TransformNode = TransformNode;
  17456. })(BABYLON || (BABYLON = {}));
  17457. //# sourceMappingURL=babylon.transformNode.js.map
  17458. "use strict";
  17459. var BABYLON;
  17460. (function (BABYLON) {
  17461. var AbstractMesh = /** @class */ (function (_super) {
  17462. __extends(AbstractMesh, _super);
  17463. // Constructor
  17464. function AbstractMesh(name, scene) {
  17465. if (scene === void 0) { scene = null; }
  17466. var _this = _super.call(this, name, scene, false) || this;
  17467. _this._facetNb = 0; // facet number
  17468. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17469. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17470. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17471. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17472. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17473. _this._subDiv = {
  17474. max: 1,
  17475. X: 1,
  17476. Y: 1,
  17477. Z: 1
  17478. };
  17479. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17480. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17481. // Events
  17482. /**
  17483. * An event triggered when this mesh collides with another one
  17484. */
  17485. _this.onCollideObservable = new BABYLON.Observable();
  17486. /**
  17487. * An event triggered when the collision's position changes
  17488. */
  17489. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17490. /**
  17491. * An event triggered when material is changed
  17492. */
  17493. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17494. // Properties
  17495. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17496. /**
  17497. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17498. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17499. * or
  17500. * 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.
  17501. * for more info check WebGl documentations
  17502. */
  17503. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17504. /**
  17505. * 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:
  17506. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17507. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17508. * 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.
  17509. */
  17510. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17511. /**
  17512. * 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.
  17513. * The default value is -1 which means don't break the query and wait till the result.
  17514. */
  17515. _this.occlusionRetryCount = -1;
  17516. _this._occlusionInternalRetryCounter = 0;
  17517. _this._isOccluded = false;
  17518. _this._isOcclusionQueryInProgress = false;
  17519. _this._visibility = 1.0;
  17520. _this.alphaIndex = Number.MAX_VALUE;
  17521. _this.isVisible = true;
  17522. _this.isPickable = true;
  17523. _this.showBoundingBox = false;
  17524. _this.showSubMeshesBoundingBox = false;
  17525. _this.isBlocker = false;
  17526. _this.enablePointerMoveEvents = false;
  17527. _this.renderingGroupId = 0;
  17528. _this._receiveShadows = false;
  17529. _this.renderOutline = false;
  17530. _this.outlineColor = BABYLON.Color3.Red();
  17531. _this.outlineWidth = 0.02;
  17532. _this.renderOverlay = false;
  17533. _this.overlayColor = BABYLON.Color3.Red();
  17534. _this.overlayAlpha = 0.5;
  17535. _this._hasVertexAlpha = false;
  17536. _this._useVertexColors = true;
  17537. _this._computeBonesUsingShaders = true;
  17538. _this._numBoneInfluencers = 4;
  17539. _this._applyFog = true;
  17540. _this.useOctreeForRenderingSelection = true;
  17541. _this.useOctreeForPicking = true;
  17542. _this.useOctreeForCollisions = true;
  17543. _this._layerMask = 0x0FFFFFFF;
  17544. /**
  17545. * True if the mesh must be rendered in any case.
  17546. */
  17547. _this.alwaysSelectAsActiveMesh = false;
  17548. /**
  17549. * This scene's action manager
  17550. */
  17551. _this.actionManager = null;
  17552. // Physics
  17553. _this.physicsImpostor = null;
  17554. // Collisions
  17555. _this._checkCollisions = false;
  17556. _this._collisionMask = -1;
  17557. _this._collisionGroup = -1;
  17558. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17559. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17560. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17561. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17562. // Edges
  17563. _this.edgesWidth = 1;
  17564. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17565. // Cache
  17566. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17567. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17568. _this._renderId = 0;
  17569. _this._intersectionsInProgress = new Array();
  17570. _this._unIndexed = false;
  17571. _this._lightSources = new Array();
  17572. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17573. if (collidedMesh === void 0) { collidedMesh = null; }
  17574. //TODO move this to the collision coordinator!
  17575. if (_this.getScene().workerCollisions)
  17576. newPosition.multiplyInPlace(_this._collider._radius);
  17577. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17578. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17579. _this.position.addInPlace(_this._diffPositionForCollisions);
  17580. }
  17581. if (collidedMesh) {
  17582. _this.onCollideObservable.notifyObservers(collidedMesh);
  17583. }
  17584. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17585. };
  17586. _this.getScene().addMesh(_this);
  17587. _this._resyncLightSources();
  17588. return _this;
  17589. }
  17590. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17591. get: function () {
  17592. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17598. get: function () {
  17599. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17600. },
  17601. enumerable: true,
  17602. configurable: true
  17603. });
  17604. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17605. get: function () {
  17606. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17607. },
  17608. enumerable: true,
  17609. configurable: true
  17610. });
  17611. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17612. get: function () {
  17613. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17619. get: function () {
  17620. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17626. /**
  17627. * Read-only : the number of facets in the mesh
  17628. */
  17629. get: function () {
  17630. return this._facetNb;
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17636. /**
  17637. * The number (integer) of subdivisions per axis in the partioning space
  17638. */
  17639. get: function () {
  17640. return this._partitioningSubdivisions;
  17641. },
  17642. set: function (nb) {
  17643. this._partitioningSubdivisions = nb;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17649. /**
  17650. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17651. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17652. */
  17653. get: function () {
  17654. return this._partitioningBBoxRatio;
  17655. },
  17656. set: function (ratio) {
  17657. this._partitioningBBoxRatio = ratio;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17663. /**
  17664. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17665. * Works only for updatable meshes.
  17666. * Doesn't work with multi-materials.
  17667. */
  17668. get: function () {
  17669. return this._facetDepthSort;
  17670. },
  17671. set: function (sort) {
  17672. this._facetDepthSort = sort;
  17673. },
  17674. enumerable: true,
  17675. configurable: true
  17676. });
  17677. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17678. /**
  17679. * The location (Vector3) where the facet depth sort must be computed from.
  17680. * By default, the active camera position.
  17681. * Used only when facet depth sort is enabled.
  17682. */
  17683. get: function () {
  17684. return this._facetDepthSortFrom;
  17685. },
  17686. set: function (location) {
  17687. this._facetDepthSortFrom = location;
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17693. /**
  17694. * Read-only boolean : is the feature facetData enabled ?
  17695. */
  17696. get: function () {
  17697. return this._facetDataEnabled;
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17703. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17704. return false;
  17705. }
  17706. this._markSubMeshesAsMiscDirty();
  17707. return true;
  17708. };
  17709. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17710. set: function (callback) {
  17711. if (this._onCollideObserver) {
  17712. this.onCollideObservable.remove(this._onCollideObserver);
  17713. }
  17714. this._onCollideObserver = this.onCollideObservable.add(callback);
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17720. set: function (callback) {
  17721. if (this._onCollisionPositionChangeObserver) {
  17722. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17723. }
  17724. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17730. /**
  17731. * 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.
  17732. */
  17733. get: function () {
  17734. return this._isOccluded;
  17735. },
  17736. set: function (value) {
  17737. this._isOccluded = value;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17743. /**
  17744. * Flag to check the progress status of the query
  17745. */
  17746. get: function () {
  17747. return this._isOcclusionQueryInProgress;
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17753. /**
  17754. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17755. */
  17756. get: function () {
  17757. return this._visibility;
  17758. },
  17759. /**
  17760. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17761. */
  17762. set: function (value) {
  17763. if (this._visibility === value) {
  17764. return;
  17765. }
  17766. this._visibility = value;
  17767. this._markSubMeshesAsMiscDirty();
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(AbstractMesh.prototype, "material", {
  17773. get: function () {
  17774. return this._material;
  17775. },
  17776. set: function (value) {
  17777. if (this._material === value) {
  17778. return;
  17779. }
  17780. this._material = value;
  17781. if (this.onMaterialChangedObservable.hasObservers) {
  17782. this.onMaterialChangedObservable.notifyObservers(this);
  17783. }
  17784. if (!this.subMeshes) {
  17785. return;
  17786. }
  17787. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17788. var subMesh = _a[_i];
  17789. subMesh.setEffect(null);
  17790. }
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17796. get: function () {
  17797. return this._receiveShadows;
  17798. },
  17799. set: function (value) {
  17800. if (this._receiveShadows === value) {
  17801. return;
  17802. }
  17803. this._receiveShadows = value;
  17804. this._markSubMeshesAsLightDirty();
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17810. get: function () {
  17811. return this._hasVertexAlpha;
  17812. },
  17813. set: function (value) {
  17814. if (this._hasVertexAlpha === value) {
  17815. return;
  17816. }
  17817. this._hasVertexAlpha = value;
  17818. this._markSubMeshesAsAttributesDirty();
  17819. this._markSubMeshesAsMiscDirty();
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17825. get: function () {
  17826. return this._useVertexColors;
  17827. },
  17828. set: function (value) {
  17829. if (this._useVertexColors === value) {
  17830. return;
  17831. }
  17832. this._useVertexColors = value;
  17833. this._markSubMeshesAsAttributesDirty();
  17834. },
  17835. enumerable: true,
  17836. configurable: true
  17837. });
  17838. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17839. get: function () {
  17840. return this._computeBonesUsingShaders;
  17841. },
  17842. set: function (value) {
  17843. if (this._computeBonesUsingShaders === value) {
  17844. return;
  17845. }
  17846. this._computeBonesUsingShaders = value;
  17847. this._markSubMeshesAsAttributesDirty();
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17853. get: function () {
  17854. return this._numBoneInfluencers;
  17855. },
  17856. set: function (value) {
  17857. if (this._numBoneInfluencers === value) {
  17858. return;
  17859. }
  17860. this._numBoneInfluencers = value;
  17861. this._markSubMeshesAsAttributesDirty();
  17862. },
  17863. enumerable: true,
  17864. configurable: true
  17865. });
  17866. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17867. get: function () {
  17868. return this._applyFog;
  17869. },
  17870. set: function (value) {
  17871. if (this._applyFog === value) {
  17872. return;
  17873. }
  17874. this._applyFog = value;
  17875. this._markSubMeshesAsMiscDirty();
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17881. get: function () {
  17882. return this._layerMask;
  17883. },
  17884. set: function (value) {
  17885. if (value === this._layerMask) {
  17886. return;
  17887. }
  17888. this._layerMask = value;
  17889. this._resyncLightSources();
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17895. get: function () {
  17896. return this._collisionMask;
  17897. },
  17898. set: function (mask) {
  17899. this._collisionMask = !isNaN(mask) ? mask : -1;
  17900. },
  17901. enumerable: true,
  17902. configurable: true
  17903. });
  17904. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17905. get: function () {
  17906. return this._collisionGroup;
  17907. },
  17908. set: function (mask) {
  17909. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17910. },
  17911. enumerable: true,
  17912. configurable: true
  17913. });
  17914. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17915. get: function () {
  17916. return null;
  17917. },
  17918. enumerable: true,
  17919. configurable: true
  17920. });
  17921. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17922. get: function () {
  17923. return this._skeleton;
  17924. },
  17925. set: function (value) {
  17926. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17927. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17928. }
  17929. if (value && value.needInitialSkinMatrix) {
  17930. value._registerMeshWithPoseMatrix(this);
  17931. }
  17932. this._skeleton = value;
  17933. if (!this._skeleton) {
  17934. this._bonesTransformMatrices = null;
  17935. }
  17936. this._markSubMeshesAsAttributesDirty();
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. /**
  17942. * Returns the string "AbstractMesh"
  17943. */
  17944. AbstractMesh.prototype.getClassName = function () {
  17945. return "AbstractMesh";
  17946. };
  17947. /**
  17948. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17949. */
  17950. AbstractMesh.prototype.toString = function (fullDetails) {
  17951. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17952. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17953. if (this._skeleton) {
  17954. ret += ", skeleton: " + this._skeleton.name;
  17955. }
  17956. if (fullDetails) {
  17957. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17958. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17959. }
  17960. return ret;
  17961. };
  17962. AbstractMesh.prototype._rebuild = function () {
  17963. if (this._occlusionQuery) {
  17964. this._occlusionQuery = null;
  17965. }
  17966. if (this._edgesRenderer) {
  17967. this._edgesRenderer._rebuild();
  17968. }
  17969. if (!this.subMeshes) {
  17970. return;
  17971. }
  17972. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17973. var subMesh = _a[_i];
  17974. subMesh._rebuild();
  17975. }
  17976. };
  17977. AbstractMesh.prototype._resyncLightSources = function () {
  17978. this._lightSources.length = 0;
  17979. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17980. var light = _a[_i];
  17981. if (!light.isEnabled()) {
  17982. continue;
  17983. }
  17984. if (light.canAffectMesh(this)) {
  17985. this._lightSources.push(light);
  17986. }
  17987. }
  17988. this._markSubMeshesAsLightDirty();
  17989. };
  17990. AbstractMesh.prototype._resyncLighSource = function (light) {
  17991. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17992. var index = this._lightSources.indexOf(light);
  17993. if (index === -1) {
  17994. if (!isIn) {
  17995. return;
  17996. }
  17997. this._lightSources.push(light);
  17998. }
  17999. else {
  18000. if (isIn) {
  18001. return;
  18002. }
  18003. this._lightSources.splice(index, 1);
  18004. }
  18005. this._markSubMeshesAsLightDirty();
  18006. };
  18007. AbstractMesh.prototype._removeLightSource = function (light) {
  18008. var index = this._lightSources.indexOf(light);
  18009. if (index === -1) {
  18010. return;
  18011. }
  18012. this._lightSources.splice(index, 1);
  18013. this._markSubMeshesAsLightDirty();
  18014. };
  18015. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18016. if (!this.subMeshes) {
  18017. return;
  18018. }
  18019. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18020. var subMesh = _a[_i];
  18021. if (subMesh._materialDefines) {
  18022. func(subMesh._materialDefines);
  18023. }
  18024. }
  18025. };
  18026. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18027. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18028. };
  18029. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18030. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18031. };
  18032. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18033. if (!this.subMeshes) {
  18034. return;
  18035. }
  18036. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18037. var subMesh = _a[_i];
  18038. var material = subMesh.getMaterial();
  18039. if (material) {
  18040. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18041. }
  18042. }
  18043. };
  18044. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18045. /**
  18046. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18047. * Default : (1.0, 1.0, 1.0)
  18048. */
  18049. get: function () {
  18050. return this._scaling;
  18051. },
  18052. /**
  18053. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18054. * Default : (1.0, 1.0, 1.0)
  18055. */
  18056. set: function (newScaling) {
  18057. this._scaling = newScaling;
  18058. if (this.physicsImpostor) {
  18059. this.physicsImpostor.forceUpdate();
  18060. }
  18061. },
  18062. enumerable: true,
  18063. configurable: true
  18064. });
  18065. // Methods
  18066. /**
  18067. * Disables the mesh edger rendering mode.
  18068. * Returns the AbstractMesh.
  18069. */
  18070. AbstractMesh.prototype.disableEdgesRendering = function () {
  18071. if (this._edgesRenderer) {
  18072. this._edgesRenderer.dispose();
  18073. this._edgesRenderer = null;
  18074. }
  18075. return this;
  18076. };
  18077. /**
  18078. * Enables the edge rendering mode on the mesh.
  18079. * This mode makes the mesh edges visible.
  18080. * Returns the AbstractMesh.
  18081. */
  18082. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18083. if (epsilon === void 0) { epsilon = 0.95; }
  18084. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18085. this.disableEdgesRendering();
  18086. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18087. return this;
  18088. };
  18089. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18090. /**
  18091. * Returns true if the mesh is blocked. Used by the class Mesh.
  18092. * Returns the boolean `false` by default.
  18093. */
  18094. get: function () {
  18095. return false;
  18096. },
  18097. enumerable: true,
  18098. configurable: true
  18099. });
  18100. /**
  18101. * Returns the mesh itself by default, used by the class Mesh.
  18102. * Returned type : AbstractMesh
  18103. */
  18104. AbstractMesh.prototype.getLOD = function (camera) {
  18105. return this;
  18106. };
  18107. /**
  18108. * Returns 0 by default, used by the class Mesh.
  18109. * Returns an integer.
  18110. */
  18111. AbstractMesh.prototype.getTotalVertices = function () {
  18112. return 0;
  18113. };
  18114. /**
  18115. * Returns null by default, used by the class Mesh.
  18116. * Returned type : integer array
  18117. */
  18118. AbstractMesh.prototype.getIndices = function () {
  18119. return null;
  18120. };
  18121. /**
  18122. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18123. * Returned type : float array or Float32Array
  18124. */
  18125. AbstractMesh.prototype.getVerticesData = function (kind) {
  18126. return null;
  18127. };
  18128. /**
  18129. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18130. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18131. * The `data` are either a numeric array either a Float32Array.
  18132. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18133. * 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).
  18134. * Note that a new underlying VertexBuffer object is created each call.
  18135. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18136. *
  18137. * Possible `kind` values :
  18138. * - BABYLON.VertexBuffer.PositionKind
  18139. * - BABYLON.VertexBuffer.UVKind
  18140. * - BABYLON.VertexBuffer.UV2Kind
  18141. * - BABYLON.VertexBuffer.UV3Kind
  18142. * - BABYLON.VertexBuffer.UV4Kind
  18143. * - BABYLON.VertexBuffer.UV5Kind
  18144. * - BABYLON.VertexBuffer.UV6Kind
  18145. * - BABYLON.VertexBuffer.ColorKind
  18146. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18147. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18148. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18149. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18150. *
  18151. * Returns the Mesh.
  18152. */
  18153. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18154. return this;
  18155. };
  18156. /**
  18157. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18158. * If the mesh has no geometry, it is simply returned as it is.
  18159. * The `data` are either a numeric array either a Float32Array.
  18160. * No new underlying VertexBuffer object is created.
  18161. * 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.
  18162. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18163. *
  18164. * Possible `kind` values :
  18165. * - BABYLON.VertexBuffer.PositionKind
  18166. * - BABYLON.VertexBuffer.UVKind
  18167. * - BABYLON.VertexBuffer.UV2Kind
  18168. * - BABYLON.VertexBuffer.UV3Kind
  18169. * - BABYLON.VertexBuffer.UV4Kind
  18170. * - BABYLON.VertexBuffer.UV5Kind
  18171. * - BABYLON.VertexBuffer.UV6Kind
  18172. * - BABYLON.VertexBuffer.ColorKind
  18173. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18174. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18175. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18176. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18177. *
  18178. * Returns the Mesh.
  18179. */
  18180. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18181. return this;
  18182. };
  18183. /**
  18184. * Sets the mesh indices.
  18185. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18186. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18187. * This method creates a new index buffer each call.
  18188. * Returns the Mesh.
  18189. */
  18190. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18191. return this;
  18192. };
  18193. /** Returns false by default, used by the class Mesh.
  18194. * Returns a boolean
  18195. */
  18196. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18197. return false;
  18198. };
  18199. /**
  18200. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18201. * Returns a BoundingInfo
  18202. */
  18203. AbstractMesh.prototype.getBoundingInfo = function () {
  18204. if (this._masterMesh) {
  18205. return this._masterMesh.getBoundingInfo();
  18206. }
  18207. if (!this._boundingInfo) {
  18208. // this._boundingInfo is being created here
  18209. this._updateBoundingInfo();
  18210. }
  18211. // cannot be null.
  18212. return this._boundingInfo;
  18213. };
  18214. /**
  18215. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18216. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18217. */
  18218. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18219. if (includeDescendants === void 0) { includeDescendants = true; }
  18220. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18221. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18222. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18223. if (maxDimension === 0) {
  18224. return this;
  18225. }
  18226. var scale = 1 / maxDimension;
  18227. this.scaling.scaleInPlace(scale);
  18228. return this;
  18229. };
  18230. /**
  18231. * Sets a mesh new object BoundingInfo.
  18232. * Returns the AbstractMesh.
  18233. */
  18234. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18235. this._boundingInfo = boundingInfo;
  18236. return this;
  18237. };
  18238. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18239. get: function () {
  18240. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18241. },
  18242. enumerable: true,
  18243. configurable: true
  18244. });
  18245. AbstractMesh.prototype._preActivate = function () {
  18246. };
  18247. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18248. };
  18249. AbstractMesh.prototype._activate = function (renderId) {
  18250. this._renderId = renderId;
  18251. };
  18252. /**
  18253. * Returns the latest update of the World matrix
  18254. * Returns a Matrix.
  18255. */
  18256. AbstractMesh.prototype.getWorldMatrix = function () {
  18257. if (this._masterMesh) {
  18258. return this._masterMesh.getWorldMatrix();
  18259. }
  18260. return _super.prototype.getWorldMatrix.call(this);
  18261. };
  18262. /**
  18263. * Returns the latest update of the World matrix determinant.
  18264. */
  18265. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18266. if (this._masterMesh) {
  18267. return this._masterMesh._getWorldMatrixDeterminant();
  18268. }
  18269. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18270. };
  18271. // ================================== Point of View Movement =================================
  18272. /**
  18273. * Perform relative position change from the point of view of behind the front of the mesh.
  18274. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18275. * Supports definition of mesh facing forward or backward.
  18276. * @param {number} amountRight
  18277. * @param {number} amountUp
  18278. * @param {number} amountForward
  18279. *
  18280. * Returns the AbstractMesh.
  18281. */
  18282. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18283. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18284. return this;
  18285. };
  18286. /**
  18287. * Calculate relative position change from the point of view of behind the front of the mesh.
  18288. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18289. * Supports definition of mesh facing forward or backward.
  18290. * @param {number} amountRight
  18291. * @param {number} amountUp
  18292. * @param {number} amountForward
  18293. *
  18294. * Returns a new Vector3.
  18295. */
  18296. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18297. var rotMatrix = new BABYLON.Matrix();
  18298. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18299. rotQuaternion.toRotationMatrix(rotMatrix);
  18300. var translationDelta = BABYLON.Vector3.Zero();
  18301. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18302. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18303. return translationDelta;
  18304. };
  18305. // ================================== Point of View Rotation =================================
  18306. /**
  18307. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18308. * Supports definition of mesh facing forward or backward.
  18309. * @param {number} flipBack
  18310. * @param {number} twirlClockwise
  18311. * @param {number} tiltRight
  18312. *
  18313. * Returns the AbstractMesh.
  18314. */
  18315. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18316. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18317. return this;
  18318. };
  18319. /**
  18320. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18321. * Supports definition of mesh facing forward or backward.
  18322. * @param {number} flipBack
  18323. * @param {number} twirlClockwise
  18324. * @param {number} tiltRight
  18325. *
  18326. * Returns a new Vector3.
  18327. */
  18328. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18329. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18330. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18331. };
  18332. /**
  18333. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18334. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18335. */
  18336. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18337. if (includeDescendants === void 0) { includeDescendants = true; }
  18338. this.computeWorldMatrix(true);
  18339. var min;
  18340. var max;
  18341. var boundingInfo = this.getBoundingInfo();
  18342. if (!this.subMeshes) {
  18343. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18344. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18345. }
  18346. else {
  18347. min = boundingInfo.boundingBox.minimumWorld;
  18348. max = boundingInfo.boundingBox.maximumWorld;
  18349. }
  18350. if (includeDescendants) {
  18351. var descendants = this.getDescendants(false);
  18352. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18353. var descendant = descendants_1[_i];
  18354. var childMesh = descendant;
  18355. childMesh.computeWorldMatrix(true);
  18356. //make sure we have the needed params to get mix and max
  18357. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18358. continue;
  18359. }
  18360. var childBoundingInfo = childMesh.getBoundingInfo();
  18361. var boundingBox = childBoundingInfo.boundingBox;
  18362. var minBox = boundingBox.minimumWorld;
  18363. var maxBox = boundingBox.maximumWorld;
  18364. BABYLON.Tools.CheckExtends(minBox, min, max);
  18365. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18366. }
  18367. }
  18368. return {
  18369. min: min,
  18370. max: max
  18371. };
  18372. };
  18373. /**
  18374. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18375. * Returns the AbstractMesh.
  18376. */
  18377. AbstractMesh.prototype._updateBoundingInfo = function () {
  18378. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18379. this._boundingInfo.update(this.worldMatrixFromCache);
  18380. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18381. return this;
  18382. };
  18383. /**
  18384. * Update a mesh's children BoundingInfo objects only.
  18385. * Returns the AbstractMesh.
  18386. */
  18387. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18388. if (!this.subMeshes) {
  18389. return this;
  18390. }
  18391. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18392. var subMesh = this.subMeshes[subIndex];
  18393. if (!subMesh.IsGlobal) {
  18394. subMesh.updateBoundingInfo(matrix);
  18395. }
  18396. }
  18397. return this;
  18398. };
  18399. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18400. // Bounding info
  18401. this._updateBoundingInfo();
  18402. };
  18403. /**
  18404. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18405. * A mesh is in the frustum if its bounding box intersects the frustum.
  18406. * Boolean returned.
  18407. */
  18408. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18409. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18410. };
  18411. /**
  18412. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18413. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18414. * Boolean returned.
  18415. */
  18416. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18417. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18418. ;
  18419. };
  18420. /**
  18421. * True if the mesh intersects another mesh or a SolidParticle object.
  18422. * 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)
  18423. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18424. * Returns a boolean.
  18425. */
  18426. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18427. if (precise === void 0) { precise = false; }
  18428. if (!this._boundingInfo || !mesh._boundingInfo) {
  18429. return false;
  18430. }
  18431. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18432. return true;
  18433. }
  18434. if (includeDescendants) {
  18435. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18436. var child = _a[_i];
  18437. if (child.intersectsMesh(mesh, precise, true)) {
  18438. return true;
  18439. }
  18440. }
  18441. }
  18442. return false;
  18443. };
  18444. /**
  18445. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18446. * Returns a boolean.
  18447. */
  18448. AbstractMesh.prototype.intersectsPoint = function (point) {
  18449. if (!this._boundingInfo) {
  18450. return false;
  18451. }
  18452. return this._boundingInfo.intersectsPoint(point);
  18453. };
  18454. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18455. return this.physicsImpostor;
  18456. };
  18457. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18458. if (camera === void 0) { camera = null; }
  18459. if (!camera) {
  18460. camera = this.getScene().activeCamera;
  18461. }
  18462. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18463. };
  18464. /**
  18465. * Returns the distance from the mesh to the active camera.
  18466. * Returns a float.
  18467. */
  18468. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18469. if (camera === void 0) { camera = null; }
  18470. if (!camera) {
  18471. camera = this.getScene().activeCamera;
  18472. }
  18473. return this.absolutePosition.subtract(camera.position).length();
  18474. };
  18475. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18476. if (!this.physicsImpostor) {
  18477. return this;
  18478. }
  18479. this.physicsImpostor.applyImpulse(force, contactPoint);
  18480. return this;
  18481. };
  18482. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18483. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18484. return this;
  18485. }
  18486. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18487. mainPivot: pivot1,
  18488. connectedPivot: pivot2,
  18489. nativeParams: options
  18490. });
  18491. return this;
  18492. };
  18493. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18494. // Collisions
  18495. /**
  18496. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18497. * Default `false`.
  18498. */
  18499. get: function () {
  18500. return this._checkCollisions;
  18501. },
  18502. set: function (collisionEnabled) {
  18503. this._checkCollisions = collisionEnabled;
  18504. if (this.getScene().workerCollisions) {
  18505. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18506. }
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18512. /**
  18513. * Gets Collider object used to compute collisions (not physics)
  18514. */
  18515. get: function () {
  18516. return this._collider;
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18522. var globalPosition = this.getAbsolutePosition();
  18523. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18524. if (!this._collider) {
  18525. this._collider = new BABYLON.Collider();
  18526. }
  18527. this._collider._radius = this.ellipsoid;
  18528. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18529. return this;
  18530. };
  18531. // Submeshes octree
  18532. /**
  18533. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18534. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18535. * Returns an Octree of submeshes.
  18536. */
  18537. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18538. if (maxCapacity === void 0) { maxCapacity = 64; }
  18539. if (maxDepth === void 0) { maxDepth = 2; }
  18540. if (!this._submeshesOctree) {
  18541. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18542. }
  18543. this.computeWorldMatrix(true);
  18544. var boundingInfo = this.getBoundingInfo();
  18545. // Update octree
  18546. var bbox = boundingInfo.boundingBox;
  18547. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18548. return this._submeshesOctree;
  18549. };
  18550. // Collisions
  18551. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18552. this._generatePointsArray();
  18553. if (!this._positions) {
  18554. return this;
  18555. }
  18556. // Transformation
  18557. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18558. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18559. subMesh._lastColliderWorldVertices = [];
  18560. subMesh._trianglePlanes = [];
  18561. var start = subMesh.verticesStart;
  18562. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18563. for (var i = start; i < end; i++) {
  18564. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18565. }
  18566. }
  18567. // Collide
  18568. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18569. if (collider.collisionFound) {
  18570. collider.collidedMesh = this;
  18571. }
  18572. return this;
  18573. };
  18574. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18575. var subMeshes;
  18576. var len;
  18577. // Octrees
  18578. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18579. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18580. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18581. len = intersections.length;
  18582. subMeshes = intersections.data;
  18583. }
  18584. else {
  18585. subMeshes = this.subMeshes;
  18586. len = subMeshes.length;
  18587. }
  18588. for (var index = 0; index < len; index++) {
  18589. var subMesh = subMeshes[index];
  18590. // Bounding test
  18591. if (len > 1 && !subMesh._checkCollision(collider))
  18592. continue;
  18593. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18594. }
  18595. return this;
  18596. };
  18597. AbstractMesh.prototype._checkCollision = function (collider) {
  18598. // Bounding box test
  18599. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18600. return this;
  18601. // Transformation matrix
  18602. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18603. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18604. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18605. return this;
  18606. };
  18607. // Picking
  18608. AbstractMesh.prototype._generatePointsArray = function () {
  18609. return false;
  18610. };
  18611. /**
  18612. * Checks if the passed Ray intersects with the mesh.
  18613. * Returns an object PickingInfo.
  18614. */
  18615. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18616. var pickingInfo = new BABYLON.PickingInfo();
  18617. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18618. return pickingInfo;
  18619. }
  18620. if (!this._generatePointsArray()) {
  18621. return pickingInfo;
  18622. }
  18623. var intersectInfo = null;
  18624. // Octrees
  18625. var subMeshes;
  18626. var len;
  18627. if (this._submeshesOctree && this.useOctreeForPicking) {
  18628. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18629. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18630. len = intersections.length;
  18631. subMeshes = intersections.data;
  18632. }
  18633. else {
  18634. subMeshes = this.subMeshes;
  18635. len = subMeshes.length;
  18636. }
  18637. for (var index = 0; index < len; index++) {
  18638. var subMesh = subMeshes[index];
  18639. // Bounding test
  18640. if (len > 1 && !subMesh.canIntersects(ray))
  18641. continue;
  18642. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18643. if (currentIntersectInfo) {
  18644. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18645. intersectInfo = currentIntersectInfo;
  18646. intersectInfo.subMeshId = index;
  18647. if (fastCheck) {
  18648. break;
  18649. }
  18650. }
  18651. }
  18652. }
  18653. if (intersectInfo) {
  18654. // Get picked point
  18655. var world = this.getWorldMatrix();
  18656. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18657. var direction = ray.direction.clone();
  18658. direction = direction.scale(intersectInfo.distance);
  18659. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18660. var pickedPoint = worldOrigin.add(worldDirection);
  18661. // Return result
  18662. pickingInfo.hit = true;
  18663. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18664. pickingInfo.pickedPoint = pickedPoint;
  18665. pickingInfo.pickedMesh = this;
  18666. pickingInfo.bu = intersectInfo.bu || 0;
  18667. pickingInfo.bv = intersectInfo.bv || 0;
  18668. pickingInfo.faceId = intersectInfo.faceId;
  18669. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18670. return pickingInfo;
  18671. }
  18672. return pickingInfo;
  18673. };
  18674. /**
  18675. * Clones the mesh, used by the class Mesh.
  18676. * Just returns `null` for an AbstractMesh.
  18677. */
  18678. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18679. return null;
  18680. };
  18681. /**
  18682. * Disposes all the mesh submeshes.
  18683. * Returns the AbstractMesh.
  18684. */
  18685. AbstractMesh.prototype.releaseSubMeshes = function () {
  18686. if (this.subMeshes) {
  18687. while (this.subMeshes.length) {
  18688. this.subMeshes[0].dispose();
  18689. }
  18690. }
  18691. else {
  18692. this.subMeshes = new Array();
  18693. }
  18694. return this;
  18695. };
  18696. /**
  18697. * Releases resources associated with this abstract mesh.
  18698. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18699. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18700. */
  18701. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18702. var _this = this;
  18703. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18704. var index;
  18705. // Smart Array Retainers.
  18706. this.getScene().freeActiveMeshes();
  18707. this.getScene().freeRenderingGroups();
  18708. // Action manager
  18709. if (this.actionManager !== undefined && this.actionManager !== null) {
  18710. this.actionManager.dispose();
  18711. this.actionManager = null;
  18712. }
  18713. // Skeleton
  18714. this._skeleton = null;
  18715. // Physics
  18716. if (this.physicsImpostor) {
  18717. this.physicsImpostor.dispose();
  18718. }
  18719. // Intersections in progress
  18720. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18721. var other = this._intersectionsInProgress[index];
  18722. var pos = other._intersectionsInProgress.indexOf(this);
  18723. other._intersectionsInProgress.splice(pos, 1);
  18724. }
  18725. this._intersectionsInProgress = [];
  18726. // Lights
  18727. var lights = this.getScene().lights;
  18728. lights.forEach(function (light) {
  18729. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18730. if (meshIndex !== -1) {
  18731. light.includedOnlyMeshes.splice(meshIndex, 1);
  18732. }
  18733. meshIndex = light.excludedMeshes.indexOf(_this);
  18734. if (meshIndex !== -1) {
  18735. light.excludedMeshes.splice(meshIndex, 1);
  18736. }
  18737. // Shadow generators
  18738. var generator = light.getShadowGenerator();
  18739. if (generator) {
  18740. var shadowMap = generator.getShadowMap();
  18741. if (shadowMap && shadowMap.renderList) {
  18742. meshIndex = shadowMap.renderList.indexOf(_this);
  18743. if (meshIndex !== -1) {
  18744. shadowMap.renderList.splice(meshIndex, 1);
  18745. }
  18746. }
  18747. }
  18748. });
  18749. // Edges
  18750. if (this._edgesRenderer) {
  18751. this._edgesRenderer.dispose();
  18752. this._edgesRenderer = null;
  18753. }
  18754. // SubMeshes
  18755. if (this.getClassName() !== "InstancedMesh") {
  18756. this.releaseSubMeshes();
  18757. }
  18758. // Octree
  18759. var sceneOctree = this.getScene().selectionOctree;
  18760. if (sceneOctree !== undefined && sceneOctree !== null) {
  18761. var index = sceneOctree.dynamicContent.indexOf(this);
  18762. if (index !== -1) {
  18763. sceneOctree.dynamicContent.splice(index, 1);
  18764. }
  18765. }
  18766. // Query
  18767. var engine = this.getScene().getEngine();
  18768. if (this._occlusionQuery) {
  18769. this._isOcclusionQueryInProgress = false;
  18770. engine.deleteQuery(this._occlusionQuery);
  18771. this._occlusionQuery = null;
  18772. }
  18773. // Engine
  18774. engine.wipeCaches();
  18775. // Remove from scene
  18776. this.getScene().removeMesh(this);
  18777. if (disposeMaterialAndTextures) {
  18778. if (this.material) {
  18779. this.material.dispose(false, true);
  18780. }
  18781. }
  18782. if (!doNotRecurse) {
  18783. // Particles
  18784. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18785. if (this.getScene().particleSystems[index].emitter === this) {
  18786. this.getScene().particleSystems[index].dispose();
  18787. index--;
  18788. }
  18789. }
  18790. }
  18791. // facet data
  18792. if (this._facetDataEnabled) {
  18793. this.disableFacetData();
  18794. }
  18795. this.onAfterWorldMatrixUpdateObservable.clear();
  18796. this.onCollideObservable.clear();
  18797. this.onCollisionPositionChangeObservable.clear();
  18798. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18799. };
  18800. /**
  18801. * Adds the passed mesh as a child to the current mesh.
  18802. * Returns the AbstractMesh.
  18803. */
  18804. AbstractMesh.prototype.addChild = function (mesh) {
  18805. mesh.setParent(this);
  18806. return this;
  18807. };
  18808. /**
  18809. * Removes the passed mesh from the current mesh children list.
  18810. * Returns the AbstractMesh.
  18811. */
  18812. AbstractMesh.prototype.removeChild = function (mesh) {
  18813. mesh.setParent(null);
  18814. return this;
  18815. };
  18816. // Facet data
  18817. /**
  18818. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18819. * Returns the AbstractMesh.
  18820. */
  18821. AbstractMesh.prototype._initFacetData = function () {
  18822. if (!this._facetNormals) {
  18823. this._facetNormals = new Array();
  18824. }
  18825. if (!this._facetPositions) {
  18826. this._facetPositions = new Array();
  18827. }
  18828. if (!this._facetPartitioning) {
  18829. this._facetPartitioning = new Array();
  18830. }
  18831. this._facetNb = (this.getIndices().length / 3) | 0;
  18832. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18833. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18834. for (var f = 0; f < this._facetNb; f++) {
  18835. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18836. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18837. }
  18838. this._facetDataEnabled = true;
  18839. return this;
  18840. };
  18841. /**
  18842. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18843. * This method can be called within the render loop.
  18844. * 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.
  18845. * Returns the AbstractMesh.
  18846. */
  18847. AbstractMesh.prototype.updateFacetData = function () {
  18848. if (!this._facetDataEnabled) {
  18849. this._initFacetData();
  18850. }
  18851. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18852. var indices = this.getIndices();
  18853. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18854. var bInfo = this.getBoundingInfo();
  18855. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18856. // init arrays, matrix and sort function on first call
  18857. this._facetDepthSortEnabled = true;
  18858. if (indices instanceof Uint16Array) {
  18859. this._depthSortedIndices = new Uint16Array(indices);
  18860. }
  18861. else if (indices instanceof Uint32Array) {
  18862. this._depthSortedIndices = new Uint32Array(indices);
  18863. }
  18864. else {
  18865. var needs32bits = false;
  18866. for (var i = 0; i < indices.length; i++) {
  18867. if (indices[i] > 65535) {
  18868. needs32bits = true;
  18869. break;
  18870. }
  18871. }
  18872. if (needs32bits) {
  18873. this._depthSortedIndices = new Uint32Array(indices);
  18874. }
  18875. else {
  18876. this._depthSortedIndices = new Uint16Array(indices);
  18877. }
  18878. }
  18879. this._facetDepthSortFunction = function (f1, f2) {
  18880. return (f2.sqDistance - f1.sqDistance);
  18881. };
  18882. if (!this._facetDepthSortFrom) {
  18883. var camera = this.getScene().activeCamera;
  18884. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18885. }
  18886. this._depthSortedFacets = [];
  18887. for (var f = 0; f < this._facetNb; f++) {
  18888. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18889. this._depthSortedFacets.push(depthSortedFacet);
  18890. }
  18891. this._invertedMatrix = BABYLON.Matrix.Identity();
  18892. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18893. }
  18894. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18895. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18896. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18897. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18898. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18899. this._subDiv.max = this._partitioningSubdivisions;
  18900. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18901. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18902. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18903. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18904. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18905. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18906. // set the parameters for ComputeNormals()
  18907. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18908. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18909. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18910. this._facetParameters.bInfo = bInfo;
  18911. this._facetParameters.bbSize = this._bbSize;
  18912. this._facetParameters.subDiv = this._subDiv;
  18913. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18914. this._facetParameters.depthSort = this._facetDepthSort;
  18915. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18916. this.computeWorldMatrix(true);
  18917. this._worldMatrix.invertToRef(this._invertedMatrix);
  18918. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18919. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18920. }
  18921. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18922. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18923. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18924. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18925. var l = (this._depthSortedIndices.length / 3) | 0;
  18926. for (var f = 0; f < l; f++) {
  18927. var sind = this._depthSortedFacets[f].ind;
  18928. this._depthSortedIndices[f * 3] = indices[sind];
  18929. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18930. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18931. }
  18932. this.updateIndices(this._depthSortedIndices);
  18933. }
  18934. return this;
  18935. };
  18936. /**
  18937. * Returns the facetLocalNormals array.
  18938. * The normals are expressed in the mesh local space.
  18939. */
  18940. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18941. if (!this._facetNormals) {
  18942. this.updateFacetData();
  18943. }
  18944. return this._facetNormals;
  18945. };
  18946. /**
  18947. * Returns the facetLocalPositions array.
  18948. * The facet positions are expressed in the mesh local space.
  18949. */
  18950. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18951. if (!this._facetPositions) {
  18952. this.updateFacetData();
  18953. }
  18954. return this._facetPositions;
  18955. };
  18956. /**
  18957. * Returns the facetLocalPartioning array.
  18958. */
  18959. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18960. if (!this._facetPartitioning) {
  18961. this.updateFacetData();
  18962. }
  18963. return this._facetPartitioning;
  18964. };
  18965. /**
  18966. * Returns the i-th facet position in the world system.
  18967. * This method allocates a new Vector3 per call.
  18968. */
  18969. AbstractMesh.prototype.getFacetPosition = function (i) {
  18970. var pos = BABYLON.Vector3.Zero();
  18971. this.getFacetPositionToRef(i, pos);
  18972. return pos;
  18973. };
  18974. /**
  18975. * Sets the reference Vector3 with the i-th facet position in the world system.
  18976. * Returns the AbstractMesh.
  18977. */
  18978. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18979. var localPos = (this.getFacetLocalPositions())[i];
  18980. var world = this.getWorldMatrix();
  18981. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18982. return this;
  18983. };
  18984. /**
  18985. * Returns the i-th facet normal in the world system.
  18986. * This method allocates a new Vector3 per call.
  18987. */
  18988. AbstractMesh.prototype.getFacetNormal = function (i) {
  18989. var norm = BABYLON.Vector3.Zero();
  18990. this.getFacetNormalToRef(i, norm);
  18991. return norm;
  18992. };
  18993. /**
  18994. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18995. * Returns the AbstractMesh.
  18996. */
  18997. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18998. var localNorm = (this.getFacetLocalNormals())[i];
  18999. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19000. return this;
  19001. };
  19002. /**
  19003. * 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).
  19004. */
  19005. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19006. var bInfo = this.getBoundingInfo();
  19007. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19008. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19009. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19010. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19011. return null;
  19012. }
  19013. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19014. };
  19015. /**
  19016. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19017. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19018. * 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.
  19019. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19020. * 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.
  19021. */
  19022. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19023. if (checkFace === void 0) { checkFace = false; }
  19024. if (facing === void 0) { facing = true; }
  19025. var world = this.getWorldMatrix();
  19026. var invMat = BABYLON.Tmp.Matrix[5];
  19027. world.invertToRef(invMat);
  19028. var invVect = BABYLON.Tmp.Vector3[8];
  19029. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19030. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19031. if (projected) {
  19032. // tranform the local computed projected vector to world coordinates
  19033. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19034. }
  19035. return closest;
  19036. };
  19037. /**
  19038. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19039. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19040. * 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.
  19041. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19042. * 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.
  19043. */
  19044. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19045. if (checkFace === void 0) { checkFace = false; }
  19046. if (facing === void 0) { facing = true; }
  19047. var closest = null;
  19048. var tmpx = 0.0;
  19049. var tmpy = 0.0;
  19050. var tmpz = 0.0;
  19051. var d = 0.0; // tmp dot facet normal * facet position
  19052. var t0 = 0.0;
  19053. var projx = 0.0;
  19054. var projy = 0.0;
  19055. var projz = 0.0;
  19056. // Get all the facets in the same partitioning block than (x, y, z)
  19057. var facetPositions = this.getFacetLocalPositions();
  19058. var facetNormals = this.getFacetLocalNormals();
  19059. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19060. if (!facetsInBlock) {
  19061. return null;
  19062. }
  19063. // Get the closest facet to (x, y, z)
  19064. var shortest = Number.MAX_VALUE; // init distance vars
  19065. var tmpDistance = shortest;
  19066. var fib; // current facet in the block
  19067. var norm; // current facet normal
  19068. var p0; // current facet barycenter position
  19069. // loop on all the facets in the current partitioning block
  19070. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19071. fib = facetsInBlock[idx];
  19072. norm = facetNormals[fib];
  19073. p0 = facetPositions[fib];
  19074. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19075. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19076. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19077. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19078. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19079. projx = x + norm.x * t0;
  19080. projy = y + norm.y * t0;
  19081. projz = z + norm.z * t0;
  19082. tmpx = projx - x;
  19083. tmpy = projy - y;
  19084. tmpz = projz - z;
  19085. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19086. if (tmpDistance < shortest) {
  19087. shortest = tmpDistance;
  19088. closest = fib;
  19089. if (projected) {
  19090. projected.x = projx;
  19091. projected.y = projy;
  19092. projected.z = projz;
  19093. }
  19094. }
  19095. }
  19096. }
  19097. return closest;
  19098. };
  19099. /**
  19100. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19101. */
  19102. AbstractMesh.prototype.getFacetDataParameters = function () {
  19103. return this._facetParameters;
  19104. };
  19105. /**
  19106. * Disables the feature FacetData and frees the related memory.
  19107. * Returns the AbstractMesh.
  19108. */
  19109. AbstractMesh.prototype.disableFacetData = function () {
  19110. if (this._facetDataEnabled) {
  19111. this._facetDataEnabled = false;
  19112. this._facetPositions = new Array();
  19113. this._facetNormals = new Array();
  19114. this._facetPartitioning = new Array();
  19115. this._facetParameters = null;
  19116. this._depthSortedIndices = new Uint32Array(0);
  19117. }
  19118. return this;
  19119. };
  19120. /**
  19121. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19122. * Returns the mesh.
  19123. */
  19124. AbstractMesh.prototype.updateIndices = function (indices) {
  19125. return this;
  19126. };
  19127. /**
  19128. * The mesh Geometry. Actually used by the Mesh object.
  19129. * Returns a blank geometry object.
  19130. */
  19131. /**
  19132. * Creates new normals data for the mesh.
  19133. * @param updatable.
  19134. */
  19135. AbstractMesh.prototype.createNormals = function (updatable) {
  19136. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19137. var indices = this.getIndices();
  19138. var normals;
  19139. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19140. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19141. }
  19142. else {
  19143. normals = [];
  19144. }
  19145. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19146. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19147. };
  19148. /**
  19149. * Align the mesh with a normal.
  19150. * Returns the mesh.
  19151. */
  19152. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19153. if (!upDirection) {
  19154. upDirection = BABYLON.Axis.Y;
  19155. }
  19156. var axisX = BABYLON.Tmp.Vector3[0];
  19157. var axisZ = BABYLON.Tmp.Vector3[1];
  19158. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19159. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19160. if (this.rotationQuaternion) {
  19161. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19162. }
  19163. else {
  19164. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19165. }
  19166. return this;
  19167. };
  19168. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19169. var engine = this.getEngine();
  19170. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19171. this._isOccluded = false;
  19172. return;
  19173. }
  19174. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19175. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19176. if (isOcclusionQueryAvailable) {
  19177. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19178. this._isOcclusionQueryInProgress = false;
  19179. this._occlusionInternalRetryCounter = 0;
  19180. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19181. }
  19182. else {
  19183. this._occlusionInternalRetryCounter++;
  19184. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19185. this._isOcclusionQueryInProgress = false;
  19186. this._occlusionInternalRetryCounter = 0;
  19187. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19188. // if strict continue the last state of the object.
  19189. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19190. }
  19191. else {
  19192. return;
  19193. }
  19194. }
  19195. }
  19196. var scene = this.getScene();
  19197. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19198. if (!this._occlusionQuery) {
  19199. this._occlusionQuery = engine.createQuery();
  19200. }
  19201. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19202. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19203. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19204. this._isOcclusionQueryInProgress = true;
  19205. };
  19206. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19207. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19208. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19209. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19210. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19211. return AbstractMesh;
  19212. }(BABYLON.TransformNode));
  19213. BABYLON.AbstractMesh = AbstractMesh;
  19214. })(BABYLON || (BABYLON = {}));
  19215. //# sourceMappingURL=babylon.abstractMesh.js.map
  19216. "use strict";
  19217. var BABYLON;
  19218. (function (BABYLON) {
  19219. /**
  19220. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19221. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19222. * 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.
  19223. */
  19224. var Light = /** @class */ (function (_super) {
  19225. __extends(Light, _super);
  19226. /**
  19227. * Creates a Light object in the scene.
  19228. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19229. * @param name The firendly name of the light
  19230. * @param scene The scene the light belongs too
  19231. */
  19232. function Light(name, scene) {
  19233. var _this = _super.call(this, name, scene) || this;
  19234. /**
  19235. * Diffuse gives the basic color to an object.
  19236. */
  19237. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19238. /**
  19239. * Specular produces a highlight color on an object.
  19240. * Note: This is note affecting PBR materials.
  19241. */
  19242. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19243. /**
  19244. * Strength of the light.
  19245. * Note: By default it is define in the framework own unit.
  19246. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19247. */
  19248. _this.intensity = 1.0;
  19249. /**
  19250. * Defines how far from the source the light is impacting in scene units.
  19251. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19252. */
  19253. _this.range = Number.MAX_VALUE;
  19254. /**
  19255. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19256. * of light.
  19257. */
  19258. _this._photometricScale = 1.0;
  19259. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19260. _this._radius = 0.00001;
  19261. /**
  19262. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19263. * exceeding the number allowed of the materials.
  19264. */
  19265. _this.renderPriority = 0;
  19266. /**
  19267. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19268. * the current shadow generator.
  19269. */
  19270. _this.shadowEnabled = true;
  19271. _this._excludeWithLayerMask = 0;
  19272. _this._includeOnlyWithLayerMask = 0;
  19273. _this._lightmapMode = 0;
  19274. /**
  19275. * @ignore Internal use only.
  19276. */
  19277. _this._excludedMeshesIds = new Array();
  19278. /**
  19279. * @ignore Internal use only.
  19280. */
  19281. _this._includedOnlyMeshesIds = new Array();
  19282. _this.getScene().addLight(_this);
  19283. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19284. _this._buildUniformLayout();
  19285. _this.includedOnlyMeshes = new Array();
  19286. _this.excludedMeshes = new Array();
  19287. _this._resyncMeshes();
  19288. return _this;
  19289. }
  19290. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19291. /**
  19292. * If every light affecting the material is in this lightmapMode,
  19293. * material.lightmapTexture adds or multiplies
  19294. * (depends on material.useLightmapAsShadowmap)
  19295. * after every other light calculations.
  19296. */
  19297. get: function () {
  19298. return Light._LIGHTMAP_DEFAULT;
  19299. },
  19300. enumerable: true,
  19301. configurable: true
  19302. });
  19303. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19304. /**
  19305. * material.lightmapTexture as only diffuse lighting from this light
  19306. * adds only specular lighting from this light
  19307. * adds dynamic shadows
  19308. */
  19309. get: function () {
  19310. return Light._LIGHTMAP_SPECULAR;
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19316. /**
  19317. * material.lightmapTexture as only lighting
  19318. * no light calculation from this light
  19319. * only adds dynamic shadows from this light
  19320. */
  19321. get: function () {
  19322. return Light._LIGHTMAP_SHADOWSONLY;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19328. /**
  19329. * Each light type uses the default quantity according to its type:
  19330. * point/spot lights use luminous intensity
  19331. * directional lights use illuminance
  19332. */
  19333. get: function () {
  19334. return Light._INTENSITYMODE_AUTOMATIC;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19340. /**
  19341. * lumen (lm)
  19342. */
  19343. get: function () {
  19344. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19345. },
  19346. enumerable: true,
  19347. configurable: true
  19348. });
  19349. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19350. /**
  19351. * candela (lm/sr)
  19352. */
  19353. get: function () {
  19354. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19360. /**
  19361. * lux (lm/m^2)
  19362. */
  19363. get: function () {
  19364. return Light._INTENSITYMODE_ILLUMINANCE;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19370. /**
  19371. * nit (cd/m^2)
  19372. */
  19373. get: function () {
  19374. return Light._INTENSITYMODE_LUMINANCE;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19380. /**
  19381. * Light type const id of the point light.
  19382. */
  19383. get: function () {
  19384. return Light._LIGHTTYPEID_POINTLIGHT;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19390. /**
  19391. * Light type const id of the directional light.
  19392. */
  19393. get: function () {
  19394. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19400. /**
  19401. * Light type const id of the spot light.
  19402. */
  19403. get: function () {
  19404. return Light._LIGHTTYPEID_SPOTLIGHT;
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19410. /**
  19411. * Light type const id of the hemispheric light.
  19412. */
  19413. get: function () {
  19414. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. Object.defineProperty(Light.prototype, "intensityMode", {
  19420. /**
  19421. * Gets the photometric scale used to interpret the intensity.
  19422. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19423. */
  19424. get: function () {
  19425. return this._intensityMode;
  19426. },
  19427. /**
  19428. * Sets the photometric scale used to interpret the intensity.
  19429. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19430. */
  19431. set: function (value) {
  19432. this._intensityMode = value;
  19433. this._computePhotometricScale();
  19434. },
  19435. enumerable: true,
  19436. configurable: true
  19437. });
  19438. ;
  19439. ;
  19440. Object.defineProperty(Light.prototype, "radius", {
  19441. /**
  19442. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19443. */
  19444. get: function () {
  19445. return this._radius;
  19446. },
  19447. /**
  19448. * sets the light radius used by PBR Materials to simulate soft area lights.
  19449. */
  19450. set: function (value) {
  19451. this._radius = value;
  19452. this._computePhotometricScale();
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. ;
  19458. ;
  19459. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19460. /**
  19461. * Gets the only meshes impacted by this light.
  19462. */
  19463. get: function () {
  19464. return this._includedOnlyMeshes;
  19465. },
  19466. /**
  19467. * Sets the only meshes impacted by this light.
  19468. */
  19469. set: function (value) {
  19470. this._includedOnlyMeshes = value;
  19471. this._hookArrayForIncludedOnly(value);
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19477. /**
  19478. * Gets the meshes not impacted by this light.
  19479. */
  19480. get: function () {
  19481. return this._excludedMeshes;
  19482. },
  19483. /**
  19484. * Sets the meshes not impacted by this light.
  19485. */
  19486. set: function (value) {
  19487. this._excludedMeshes = value;
  19488. this._hookArrayForExcluded(value);
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19494. /**
  19495. * Gets the layer id use to find what meshes are not impacted by the light.
  19496. * Inactive if 0
  19497. */
  19498. get: function () {
  19499. return this._excludeWithLayerMask;
  19500. },
  19501. /**
  19502. * Sets the layer id use to find what meshes are not impacted by the light.
  19503. * Inactive if 0
  19504. */
  19505. set: function (value) {
  19506. this._excludeWithLayerMask = value;
  19507. this._resyncMeshes();
  19508. },
  19509. enumerable: true,
  19510. configurable: true
  19511. });
  19512. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19513. /**
  19514. * Gets the layer id use to find what meshes are impacted by the light.
  19515. * Inactive if 0
  19516. */
  19517. get: function () {
  19518. return this._includeOnlyWithLayerMask;
  19519. },
  19520. /**
  19521. * Sets the layer id use to find what meshes are impacted by the light.
  19522. * Inactive if 0
  19523. */
  19524. set: function (value) {
  19525. this._includeOnlyWithLayerMask = value;
  19526. this._resyncMeshes();
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. Object.defineProperty(Light.prototype, "lightmapMode", {
  19532. /**
  19533. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19534. */
  19535. get: function () {
  19536. return this._lightmapMode;
  19537. },
  19538. /**
  19539. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19540. */
  19541. set: function (value) {
  19542. if (this._lightmapMode === value) {
  19543. return;
  19544. }
  19545. this._lightmapMode = value;
  19546. this._markMeshesAsLightDirty();
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. /**
  19552. * Returns the string "Light".
  19553. * @returns the class name
  19554. */
  19555. Light.prototype.getClassName = function () {
  19556. return "Light";
  19557. };
  19558. /**
  19559. * Converts the light information to a readable string for debug purpose.
  19560. * @param fullDetails Supports for multiple levels of logging within scene loading
  19561. * @returns the human readable light info
  19562. */
  19563. Light.prototype.toString = function (fullDetails) {
  19564. var ret = "Name: " + this.name;
  19565. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19566. if (this.animations) {
  19567. for (var i = 0; i < this.animations.length; i++) {
  19568. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19569. }
  19570. }
  19571. if (fullDetails) {
  19572. }
  19573. return ret;
  19574. };
  19575. /**
  19576. * Set the enabled state of this node.
  19577. * @param value - the new enabled state
  19578. */
  19579. Light.prototype.setEnabled = function (value) {
  19580. _super.prototype.setEnabled.call(this, value);
  19581. this._resyncMeshes();
  19582. };
  19583. /**
  19584. * Returns the Light associated shadow generator if any.
  19585. * @return the associated shadow generator.
  19586. */
  19587. Light.prototype.getShadowGenerator = function () {
  19588. return this._shadowGenerator;
  19589. };
  19590. /**
  19591. * Returns a Vector3, the absolute light position in the World.
  19592. * @returns the world space position of the light
  19593. */
  19594. Light.prototype.getAbsolutePosition = function () {
  19595. return BABYLON.Vector3.Zero();
  19596. };
  19597. /**
  19598. * Specifies if the light will affect the passed mesh.
  19599. * @param mesh The mesh to test against the light
  19600. * @return true the mesh is affected otherwise, false.
  19601. */
  19602. Light.prototype.canAffectMesh = function (mesh) {
  19603. if (!mesh) {
  19604. return true;
  19605. }
  19606. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19607. return false;
  19608. }
  19609. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19610. return false;
  19611. }
  19612. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19613. return false;
  19614. }
  19615. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19616. return false;
  19617. }
  19618. return true;
  19619. };
  19620. /**
  19621. * Computes and Returns the light World matrix.
  19622. * @returns the world matrix
  19623. */
  19624. Light.prototype.getWorldMatrix = function () {
  19625. this._currentRenderId = this.getScene().getRenderId();
  19626. this._childRenderId = this._currentRenderId;
  19627. var worldMatrix = this._getWorldMatrix();
  19628. if (this.parent && this.parent.getWorldMatrix) {
  19629. if (!this._parentedWorldMatrix) {
  19630. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19631. }
  19632. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19633. this._markSyncedWithParent();
  19634. return this._parentedWorldMatrix;
  19635. }
  19636. return worldMatrix;
  19637. };
  19638. /**
  19639. * Sort function to order lights for rendering.
  19640. * @param a First Light object to compare to second.
  19641. * @param b Second Light object to compare first.
  19642. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19643. */
  19644. Light.CompareLightsPriority = function (a, b) {
  19645. //shadow-casting lights have priority over non-shadow-casting lights
  19646. //the renderPrioirty is a secondary sort criterion
  19647. if (a.shadowEnabled !== b.shadowEnabled) {
  19648. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19649. }
  19650. return b.renderPriority - a.renderPriority;
  19651. };
  19652. /**
  19653. * Releases resources associated with this node.
  19654. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19655. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19656. */
  19657. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19658. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19659. if (this._shadowGenerator) {
  19660. this._shadowGenerator.dispose();
  19661. this._shadowGenerator = null;
  19662. }
  19663. // Animations
  19664. this.getScene().stopAnimation(this);
  19665. // Remove from meshes
  19666. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19667. var mesh = _a[_i];
  19668. mesh._removeLightSource(this);
  19669. }
  19670. this._uniformBuffer.dispose();
  19671. // Remove from scene
  19672. this.getScene().removeLight(this);
  19673. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19674. };
  19675. /**
  19676. * Returns the light type ID (integer).
  19677. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19678. */
  19679. Light.prototype.getTypeID = function () {
  19680. return 0;
  19681. };
  19682. /**
  19683. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19684. * @returns the scaled intensity in intensity mode unit
  19685. */
  19686. Light.prototype.getScaledIntensity = function () {
  19687. return this._photometricScale * this.intensity;
  19688. };
  19689. /**
  19690. * Returns a new Light object, named "name", from the current one.
  19691. * @param name The name of the cloned light
  19692. * @returns the new created light
  19693. */
  19694. Light.prototype.clone = function (name) {
  19695. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19696. if (!constructor) {
  19697. return null;
  19698. }
  19699. return BABYLON.SerializationHelper.Clone(constructor, this);
  19700. };
  19701. /**
  19702. * Serializes the current light into a Serialization object.
  19703. * @returns the serialized object.
  19704. */
  19705. Light.prototype.serialize = function () {
  19706. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19707. // Type
  19708. serializationObject.type = this.getTypeID();
  19709. // Parent
  19710. if (this.parent) {
  19711. serializationObject.parentId = this.parent.id;
  19712. }
  19713. // Inclusion / exclusions
  19714. if (this.excludedMeshes.length > 0) {
  19715. serializationObject.excludedMeshesIds = [];
  19716. this.excludedMeshes.forEach(function (mesh) {
  19717. serializationObject.excludedMeshesIds.push(mesh.id);
  19718. });
  19719. }
  19720. if (this.includedOnlyMeshes.length > 0) {
  19721. serializationObject.includedOnlyMeshesIds = [];
  19722. this.includedOnlyMeshes.forEach(function (mesh) {
  19723. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19724. });
  19725. }
  19726. // Animations
  19727. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19728. serializationObject.ranges = this.serializeAnimationRanges();
  19729. return serializationObject;
  19730. };
  19731. /**
  19732. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19733. * This new light is named "name" and added to the passed scene.
  19734. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19735. * @param name The friendly name of the light
  19736. * @param scene The scene the new light will belong to
  19737. * @returns the constructor function
  19738. */
  19739. Light.GetConstructorFromName = function (type, name, scene) {
  19740. switch (type) {
  19741. case 0:
  19742. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19743. case 1:
  19744. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19745. case 2:
  19746. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19747. case 3:
  19748. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19749. }
  19750. return null;
  19751. };
  19752. /**
  19753. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19754. * @param parsedLight The JSON representation of the light
  19755. * @param scene The scene to create the parsed light in
  19756. * @returns the created light after parsing
  19757. */
  19758. Light.Parse = function (parsedLight, scene) {
  19759. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19760. if (!constructor) {
  19761. return null;
  19762. }
  19763. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19764. // Inclusion / exclusions
  19765. if (parsedLight.excludedMeshesIds) {
  19766. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19767. }
  19768. if (parsedLight.includedOnlyMeshesIds) {
  19769. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19770. }
  19771. // Parent
  19772. if (parsedLight.parentId) {
  19773. light._waitingParentId = parsedLight.parentId;
  19774. }
  19775. // Animations
  19776. if (parsedLight.animations) {
  19777. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19778. var parsedAnimation = parsedLight.animations[animationIndex];
  19779. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19780. }
  19781. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19782. }
  19783. if (parsedLight.autoAnimate) {
  19784. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19785. }
  19786. return light;
  19787. };
  19788. Light.prototype._hookArrayForExcluded = function (array) {
  19789. var _this = this;
  19790. var oldPush = array.push;
  19791. array.push = function () {
  19792. var items = [];
  19793. for (var _i = 0; _i < arguments.length; _i++) {
  19794. items[_i] = arguments[_i];
  19795. }
  19796. var result = oldPush.apply(array, items);
  19797. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19798. var item = items_1[_a];
  19799. item._resyncLighSource(_this);
  19800. }
  19801. return result;
  19802. };
  19803. var oldSplice = array.splice;
  19804. array.splice = function (index, deleteCount) {
  19805. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19806. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19807. var item = deleted_1[_i];
  19808. item._resyncLighSource(_this);
  19809. }
  19810. return deleted;
  19811. };
  19812. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19813. var item = array_1[_i];
  19814. item._resyncLighSource(this);
  19815. }
  19816. };
  19817. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19818. var _this = this;
  19819. var oldPush = array.push;
  19820. array.push = function () {
  19821. var items = [];
  19822. for (var _i = 0; _i < arguments.length; _i++) {
  19823. items[_i] = arguments[_i];
  19824. }
  19825. var result = oldPush.apply(array, items);
  19826. _this._resyncMeshes();
  19827. return result;
  19828. };
  19829. var oldSplice = array.splice;
  19830. array.splice = function (index, deleteCount) {
  19831. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19832. _this._resyncMeshes();
  19833. return deleted;
  19834. };
  19835. this._resyncMeshes();
  19836. };
  19837. Light.prototype._resyncMeshes = function () {
  19838. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19839. var mesh = _a[_i];
  19840. mesh._resyncLighSource(this);
  19841. }
  19842. };
  19843. /**
  19844. * Forces the meshes to update their light related information in their rendering used effects
  19845. * @ignore Internal Use Only
  19846. */
  19847. Light.prototype._markMeshesAsLightDirty = function () {
  19848. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19849. var mesh = _a[_i];
  19850. if (mesh._lightSources.indexOf(this) !== -1) {
  19851. mesh._markSubMeshesAsLightDirty();
  19852. }
  19853. }
  19854. };
  19855. /**
  19856. * Recomputes the cached photometric scale if needed.
  19857. */
  19858. Light.prototype._computePhotometricScale = function () {
  19859. this._photometricScale = this._getPhotometricScale();
  19860. this.getScene().resetCachedMaterial();
  19861. };
  19862. /**
  19863. * Returns the Photometric Scale according to the light type and intensity mode.
  19864. */
  19865. Light.prototype._getPhotometricScale = function () {
  19866. var photometricScale = 0.0;
  19867. var lightTypeID = this.getTypeID();
  19868. //get photometric mode
  19869. var photometricMode = this.intensityMode;
  19870. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19871. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19872. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19873. }
  19874. else {
  19875. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19876. }
  19877. }
  19878. //compute photometric scale
  19879. switch (lightTypeID) {
  19880. case Light.LIGHTTYPEID_POINTLIGHT:
  19881. case Light.LIGHTTYPEID_SPOTLIGHT:
  19882. switch (photometricMode) {
  19883. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19884. photometricScale = 1.0 / (4.0 * Math.PI);
  19885. break;
  19886. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19887. photometricScale = 1.0;
  19888. break;
  19889. case Light.INTENSITYMODE_LUMINANCE:
  19890. photometricScale = this.radius * this.radius;
  19891. break;
  19892. }
  19893. break;
  19894. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19895. switch (photometricMode) {
  19896. case Light.INTENSITYMODE_ILLUMINANCE:
  19897. photometricScale = 1.0;
  19898. break;
  19899. case Light.INTENSITYMODE_LUMINANCE:
  19900. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19901. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19902. var apexAngleRadians = this.radius;
  19903. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19904. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19905. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19906. photometricScale = solidAngle;
  19907. break;
  19908. }
  19909. break;
  19910. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19911. // No fall off in hemisperic light.
  19912. photometricScale = 1.0;
  19913. break;
  19914. }
  19915. return photometricScale;
  19916. };
  19917. /**
  19918. * Reorder the light in the scene according to their defined priority.
  19919. * @ignore Internal Use Only
  19920. */
  19921. Light.prototype._reorderLightsInScene = function () {
  19922. var scene = this.getScene();
  19923. if (this._renderPriority != 0) {
  19924. scene.requireLightSorting = true;
  19925. }
  19926. this.getScene().sortLightsByPriority();
  19927. };
  19928. //lightmapMode Consts
  19929. Light._LIGHTMAP_DEFAULT = 0;
  19930. Light._LIGHTMAP_SPECULAR = 1;
  19931. Light._LIGHTMAP_SHADOWSONLY = 2;
  19932. // Intensity Mode Consts
  19933. Light._INTENSITYMODE_AUTOMATIC = 0;
  19934. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19935. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19936. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19937. Light._INTENSITYMODE_LUMINANCE = 4;
  19938. // Light types ids const.
  19939. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19940. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19941. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19942. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19943. __decorate([
  19944. BABYLON.serializeAsColor3()
  19945. ], Light.prototype, "diffuse", void 0);
  19946. __decorate([
  19947. BABYLON.serializeAsColor3()
  19948. ], Light.prototype, "specular", void 0);
  19949. __decorate([
  19950. BABYLON.serialize()
  19951. ], Light.prototype, "intensity", void 0);
  19952. __decorate([
  19953. BABYLON.serialize()
  19954. ], Light.prototype, "range", void 0);
  19955. __decorate([
  19956. BABYLON.serialize()
  19957. ], Light.prototype, "intensityMode", null);
  19958. __decorate([
  19959. BABYLON.serialize()
  19960. ], Light.prototype, "radius", null);
  19961. __decorate([
  19962. BABYLON.serialize()
  19963. ], Light.prototype, "_renderPriority", void 0);
  19964. __decorate([
  19965. BABYLON.expandToProperty("_reorderLightsInScene")
  19966. ], Light.prototype, "renderPriority", void 0);
  19967. __decorate([
  19968. BABYLON.serialize()
  19969. ], Light.prototype, "shadowEnabled", void 0);
  19970. __decorate([
  19971. BABYLON.serialize("excludeWithLayerMask")
  19972. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19973. __decorate([
  19974. BABYLON.serialize("includeOnlyWithLayerMask")
  19975. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19976. __decorate([
  19977. BABYLON.serialize("lightmapMode")
  19978. ], Light.prototype, "_lightmapMode", void 0);
  19979. return Light;
  19980. }(BABYLON.Node));
  19981. BABYLON.Light = Light;
  19982. })(BABYLON || (BABYLON = {}));
  19983. //# sourceMappingURL=babylon.light.js.map
  19984. "use strict";
  19985. var BABYLON;
  19986. (function (BABYLON) {
  19987. var Camera = /** @class */ (function (_super) {
  19988. __extends(Camera, _super);
  19989. function Camera(name, position, scene) {
  19990. var _this = _super.call(this, name, scene) || this;
  19991. /**
  19992. * The vector the camera should consider as up.
  19993. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19994. */
  19995. _this.upVector = BABYLON.Vector3.Up();
  19996. _this.orthoLeft = null;
  19997. _this.orthoRight = null;
  19998. _this.orthoBottom = null;
  19999. _this.orthoTop = null;
  20000. /**
  20001. * FOV is set in Radians. (default is 0.8)
  20002. */
  20003. _this.fov = 0.8;
  20004. _this.minZ = 1;
  20005. _this.maxZ = 10000.0;
  20006. _this.inertia = 0.9;
  20007. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20008. _this.isIntermediate = false;
  20009. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20010. /**
  20011. * Restricts the camera to viewing objects with the same layerMask.
  20012. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20013. */
  20014. _this.layerMask = 0x0FFFFFFF;
  20015. /**
  20016. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20017. */
  20018. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20019. // Camera rig members
  20020. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20021. _this._rigCameras = new Array();
  20022. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20023. _this._skipRendering = false;
  20024. _this.customRenderTargets = new Array();
  20025. // Observables
  20026. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20027. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20028. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20029. _this.onRestoreStateObservable = new BABYLON.Observable();
  20030. // Cache
  20031. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20032. _this._projectionMatrix = new BABYLON.Matrix();
  20033. _this._doNotComputeProjectionMatrix = false;
  20034. _this._postProcesses = new Array();
  20035. _this._transformMatrix = BABYLON.Matrix.Zero();
  20036. _this._activeMeshes = new BABYLON.SmartArray(256);
  20037. _this._globalPosition = BABYLON.Vector3.Zero();
  20038. _this._refreshFrustumPlanes = true;
  20039. _this.getScene().addCamera(_this);
  20040. if (!_this.getScene().activeCamera) {
  20041. _this.getScene().activeCamera = _this;
  20042. }
  20043. _this.position = position;
  20044. return _this;
  20045. }
  20046. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20047. get: function () {
  20048. return Camera._PERSPECTIVE_CAMERA;
  20049. },
  20050. enumerable: true,
  20051. configurable: true
  20052. });
  20053. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20054. get: function () {
  20055. return Camera._ORTHOGRAPHIC_CAMERA;
  20056. },
  20057. enumerable: true,
  20058. configurable: true
  20059. });
  20060. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20061. /**
  20062. * This is the default FOV mode for perspective cameras.
  20063. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20064. *
  20065. */
  20066. get: function () {
  20067. return Camera._FOVMODE_VERTICAL_FIXED;
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20073. /**
  20074. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20075. *
  20076. */
  20077. get: function () {
  20078. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20084. get: function () {
  20085. return Camera._RIG_MODE_NONE;
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20091. get: function () {
  20092. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20093. },
  20094. enumerable: true,
  20095. configurable: true
  20096. });
  20097. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20098. get: function () {
  20099. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20100. },
  20101. enumerable: true,
  20102. configurable: true
  20103. });
  20104. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20105. get: function () {
  20106. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20112. get: function () {
  20113. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20114. },
  20115. enumerable: true,
  20116. configurable: true
  20117. });
  20118. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20119. get: function () {
  20120. return Camera._RIG_MODE_VR;
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20126. get: function () {
  20127. return Camera._RIG_MODE_WEBVR;
  20128. },
  20129. enumerable: true,
  20130. configurable: true
  20131. });
  20132. /**
  20133. * Store current camera state (fov, position, etc..)
  20134. */
  20135. Camera.prototype.storeState = function () {
  20136. this._stateStored = true;
  20137. this._storedFov = this.fov;
  20138. return this;
  20139. };
  20140. /**
  20141. * Restores the camera state values if it has been stored. You must call storeState() first
  20142. */
  20143. Camera.prototype._restoreStateValues = function () {
  20144. if (!this._stateStored) {
  20145. return false;
  20146. }
  20147. this.fov = this._storedFov;
  20148. return true;
  20149. };
  20150. /**
  20151. * Restored camera state. You must call storeState() first
  20152. */
  20153. Camera.prototype.restoreState = function () {
  20154. if (this._restoreStateValues()) {
  20155. this.onRestoreStateObservable.notifyObservers(this);
  20156. return true;
  20157. }
  20158. return false;
  20159. };
  20160. Camera.prototype.getClassName = function () {
  20161. return "Camera";
  20162. };
  20163. /**
  20164. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20165. */
  20166. Camera.prototype.toString = function (fullDetails) {
  20167. var ret = "Name: " + this.name;
  20168. ret += ", type: " + this.getClassName();
  20169. if (this.animations) {
  20170. for (var i = 0; i < this.animations.length; i++) {
  20171. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20172. }
  20173. }
  20174. if (fullDetails) {
  20175. }
  20176. return ret;
  20177. };
  20178. Object.defineProperty(Camera.prototype, "globalPosition", {
  20179. get: function () {
  20180. return this._globalPosition;
  20181. },
  20182. enumerable: true,
  20183. configurable: true
  20184. });
  20185. Camera.prototype.getActiveMeshes = function () {
  20186. return this._activeMeshes;
  20187. };
  20188. Camera.prototype.isActiveMesh = function (mesh) {
  20189. return (this._activeMeshes.indexOf(mesh) !== -1);
  20190. };
  20191. /**
  20192. * Is this camera ready to be used/rendered
  20193. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  20194. * @return true if the camera is ready
  20195. */
  20196. Camera.prototype.isReady = function (completeCheck) {
  20197. if (completeCheck === void 0) { completeCheck = false; }
  20198. if (completeCheck) {
  20199. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  20200. var pp = _a[_i];
  20201. if (pp && !pp.isReady()) {
  20202. return false;
  20203. }
  20204. }
  20205. }
  20206. return _super.prototype.isReady.call(this, completeCheck);
  20207. };
  20208. //Cache
  20209. Camera.prototype._initCache = function () {
  20210. _super.prototype._initCache.call(this);
  20211. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20212. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20213. this._cache.mode = undefined;
  20214. this._cache.minZ = undefined;
  20215. this._cache.maxZ = undefined;
  20216. this._cache.fov = undefined;
  20217. this._cache.fovMode = undefined;
  20218. this._cache.aspectRatio = undefined;
  20219. this._cache.orthoLeft = undefined;
  20220. this._cache.orthoRight = undefined;
  20221. this._cache.orthoBottom = undefined;
  20222. this._cache.orthoTop = undefined;
  20223. this._cache.renderWidth = undefined;
  20224. this._cache.renderHeight = undefined;
  20225. };
  20226. Camera.prototype._updateCache = function (ignoreParentClass) {
  20227. if (!ignoreParentClass) {
  20228. _super.prototype._updateCache.call(this);
  20229. }
  20230. this._cache.position.copyFrom(this.position);
  20231. this._cache.upVector.copyFrom(this.upVector);
  20232. };
  20233. // Synchronized
  20234. Camera.prototype._isSynchronized = function () {
  20235. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20236. };
  20237. Camera.prototype._isSynchronizedViewMatrix = function () {
  20238. if (!_super.prototype._isSynchronized.call(this))
  20239. return false;
  20240. return this._cache.position.equals(this.position)
  20241. && this._cache.upVector.equals(this.upVector)
  20242. && this.isSynchronizedWithParent();
  20243. };
  20244. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20245. var check = this._cache.mode === this.mode
  20246. && this._cache.minZ === this.minZ
  20247. && this._cache.maxZ === this.maxZ;
  20248. if (!check) {
  20249. return false;
  20250. }
  20251. var engine = this.getEngine();
  20252. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20253. check = this._cache.fov === this.fov
  20254. && this._cache.fovMode === this.fovMode
  20255. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20256. }
  20257. else {
  20258. check = this._cache.orthoLeft === this.orthoLeft
  20259. && this._cache.orthoRight === this.orthoRight
  20260. && this._cache.orthoBottom === this.orthoBottom
  20261. && this._cache.orthoTop === this.orthoTop
  20262. && this._cache.renderWidth === engine.getRenderWidth()
  20263. && this._cache.renderHeight === engine.getRenderHeight();
  20264. }
  20265. return check;
  20266. };
  20267. // Controls
  20268. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20269. };
  20270. Camera.prototype.detachControl = function (element) {
  20271. };
  20272. Camera.prototype.update = function () {
  20273. this._checkInputs();
  20274. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20275. this._updateRigCameras();
  20276. }
  20277. };
  20278. Camera.prototype._checkInputs = function () {
  20279. this.onAfterCheckInputsObservable.notifyObservers(this);
  20280. };
  20281. Object.defineProperty(Camera.prototype, "rigCameras", {
  20282. get: function () {
  20283. return this._rigCameras;
  20284. },
  20285. enumerable: true,
  20286. configurable: true
  20287. });
  20288. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20289. get: function () {
  20290. return this._rigPostProcess;
  20291. },
  20292. enumerable: true,
  20293. configurable: true
  20294. });
  20295. /**
  20296. * Internal, gets the first post proces.
  20297. * @returns the first post process to be run on this camera.
  20298. */
  20299. Camera.prototype._getFirstPostProcess = function () {
  20300. for (var pp in this._postProcesses) {
  20301. if (this._postProcesses[pp] !== null) {
  20302. return this._postProcesses[pp];
  20303. }
  20304. }
  20305. return null;
  20306. };
  20307. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20308. // invalidate framebuffer
  20309. var firstPostProcess = this._getFirstPostProcess();
  20310. if (firstPostProcess) {
  20311. firstPostProcess.markTextureDirty();
  20312. }
  20313. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20314. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20315. var cam = this._rigCameras[i];
  20316. var rigPostProcess = cam._rigPostProcess;
  20317. // for VR rig, there does not have to be a post process
  20318. if (rigPostProcess) {
  20319. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20320. if (isPass) {
  20321. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20322. cam.isIntermediate = this._postProcesses.length === 0;
  20323. }
  20324. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20325. rigPostProcess.markTextureDirty();
  20326. }
  20327. else {
  20328. cam._postProcesses = this._postProcesses.slice(0);
  20329. }
  20330. }
  20331. };
  20332. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20333. if (insertAt === void 0) { insertAt = null; }
  20334. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20335. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20336. return 0;
  20337. }
  20338. if (insertAt == null || insertAt < 0) {
  20339. this._postProcesses.push(postProcess);
  20340. }
  20341. else if (this._postProcesses[insertAt] === null) {
  20342. this._postProcesses[insertAt] = postProcess;
  20343. }
  20344. else {
  20345. this._postProcesses.splice(insertAt, 0, postProcess);
  20346. }
  20347. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20348. return this._postProcesses.indexOf(postProcess);
  20349. };
  20350. Camera.prototype.detachPostProcess = function (postProcess) {
  20351. var idx = this._postProcesses.indexOf(postProcess);
  20352. if (idx !== -1) {
  20353. this._postProcesses[idx] = null;
  20354. }
  20355. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20356. };
  20357. Camera.prototype.getWorldMatrix = function () {
  20358. if (!this._worldMatrix) {
  20359. this._worldMatrix = BABYLON.Matrix.Identity();
  20360. }
  20361. var viewMatrix = this.getViewMatrix();
  20362. viewMatrix.invertToRef(this._worldMatrix);
  20363. return this._worldMatrix;
  20364. };
  20365. Camera.prototype._getViewMatrix = function () {
  20366. return BABYLON.Matrix.Identity();
  20367. };
  20368. Camera.prototype.getViewMatrix = function (force) {
  20369. if (!force && this._isSynchronizedViewMatrix()) {
  20370. return this._computedViewMatrix;
  20371. }
  20372. this.updateCache();
  20373. this._computedViewMatrix = this._getViewMatrix();
  20374. this._currentRenderId = this.getScene().getRenderId();
  20375. this._childRenderId = this._currentRenderId;
  20376. this._refreshFrustumPlanes = true;
  20377. if (!this.parent || !this.parent.getWorldMatrix) {
  20378. this._globalPosition.copyFrom(this.position);
  20379. }
  20380. else {
  20381. if (!this._worldMatrix) {
  20382. this._worldMatrix = BABYLON.Matrix.Identity();
  20383. }
  20384. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20385. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20386. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20387. this._computedViewMatrix.invert();
  20388. this._markSyncedWithParent();
  20389. }
  20390. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20391. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20392. }
  20393. this.onViewMatrixChangedObservable.notifyObservers(this);
  20394. return this._computedViewMatrix;
  20395. };
  20396. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20397. this._doNotComputeProjectionMatrix = true;
  20398. if (projection !== undefined) {
  20399. this._projectionMatrix = projection;
  20400. }
  20401. };
  20402. ;
  20403. Camera.prototype.unfreezeProjectionMatrix = function () {
  20404. this._doNotComputeProjectionMatrix = false;
  20405. };
  20406. ;
  20407. Camera.prototype.getProjectionMatrix = function (force) {
  20408. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20409. return this._projectionMatrix;
  20410. }
  20411. // Cache
  20412. this._cache.mode = this.mode;
  20413. this._cache.minZ = this.minZ;
  20414. this._cache.maxZ = this.maxZ;
  20415. // Matrix
  20416. this._refreshFrustumPlanes = true;
  20417. var engine = this.getEngine();
  20418. var scene = this.getScene();
  20419. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20420. this._cache.fov = this.fov;
  20421. this._cache.fovMode = this.fovMode;
  20422. this._cache.aspectRatio = engine.getAspectRatio(this);
  20423. if (this.minZ <= 0) {
  20424. this.minZ = 0.1;
  20425. }
  20426. if (scene.useRightHandedSystem) {
  20427. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20428. }
  20429. else {
  20430. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20431. }
  20432. }
  20433. else {
  20434. var halfWidth = engine.getRenderWidth() / 2.0;
  20435. var halfHeight = engine.getRenderHeight() / 2.0;
  20436. if (scene.useRightHandedSystem) {
  20437. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20438. }
  20439. else {
  20440. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20441. }
  20442. this._cache.orthoLeft = this.orthoLeft;
  20443. this._cache.orthoRight = this.orthoRight;
  20444. this._cache.orthoBottom = this.orthoBottom;
  20445. this._cache.orthoTop = this.orthoTop;
  20446. this._cache.renderWidth = engine.getRenderWidth();
  20447. this._cache.renderHeight = engine.getRenderHeight();
  20448. }
  20449. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20450. return this._projectionMatrix;
  20451. };
  20452. Camera.prototype.getTranformationMatrix = function () {
  20453. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20454. return this._transformMatrix;
  20455. };
  20456. Camera.prototype.updateFrustumPlanes = function () {
  20457. if (!this._refreshFrustumPlanes) {
  20458. return;
  20459. }
  20460. this.getTranformationMatrix();
  20461. if (!this._frustumPlanes) {
  20462. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20463. }
  20464. else {
  20465. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20466. }
  20467. this._refreshFrustumPlanes = false;
  20468. };
  20469. Camera.prototype.isInFrustum = function (target) {
  20470. this.updateFrustumPlanes();
  20471. return target.isInFrustum(this._frustumPlanes);
  20472. };
  20473. Camera.prototype.isCompletelyInFrustum = function (target) {
  20474. this.updateFrustumPlanes();
  20475. return target.isCompletelyInFrustum(this._frustumPlanes);
  20476. };
  20477. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20478. if (length === void 0) { length = 100; }
  20479. if (!transform) {
  20480. transform = this.getWorldMatrix();
  20481. }
  20482. if (!origin) {
  20483. origin = this.position;
  20484. }
  20485. var forward = new BABYLON.Vector3(0, 0, 1);
  20486. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20487. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20488. return new BABYLON.Ray(origin, direction, length);
  20489. };
  20490. /**
  20491. * Releases resources associated with this node.
  20492. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20493. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20494. */
  20495. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20496. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20497. // Observables
  20498. this.onViewMatrixChangedObservable.clear();
  20499. this.onProjectionMatrixChangedObservable.clear();
  20500. this.onAfterCheckInputsObservable.clear();
  20501. this.onRestoreStateObservable.clear();
  20502. // Inputs
  20503. if (this.inputs) {
  20504. this.inputs.clear();
  20505. }
  20506. // Animations
  20507. this.getScene().stopAnimation(this);
  20508. // Remove from scene
  20509. this.getScene().removeCamera(this);
  20510. while (this._rigCameras.length > 0) {
  20511. var camera = this._rigCameras.pop();
  20512. if (camera) {
  20513. camera.dispose();
  20514. }
  20515. }
  20516. // Postprocesses
  20517. if (this._rigPostProcess) {
  20518. this._rigPostProcess.dispose(this);
  20519. this._rigPostProcess = null;
  20520. this._postProcesses = [];
  20521. }
  20522. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20523. this._rigPostProcess = null;
  20524. this._postProcesses = [];
  20525. }
  20526. else {
  20527. var i = this._postProcesses.length;
  20528. while (--i >= 0) {
  20529. var postProcess = this._postProcesses[i];
  20530. if (postProcess) {
  20531. postProcess.dispose(this);
  20532. }
  20533. }
  20534. }
  20535. // Render targets
  20536. var i = this.customRenderTargets.length;
  20537. while (--i >= 0) {
  20538. this.customRenderTargets[i].dispose();
  20539. }
  20540. this.customRenderTargets = [];
  20541. // Active Meshes
  20542. this._activeMeshes.dispose();
  20543. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20544. };
  20545. Object.defineProperty(Camera.prototype, "leftCamera", {
  20546. // ---- Camera rigs section ----
  20547. get: function () {
  20548. if (this._rigCameras.length < 1) {
  20549. return null;
  20550. }
  20551. return this._rigCameras[0];
  20552. },
  20553. enumerable: true,
  20554. configurable: true
  20555. });
  20556. Object.defineProperty(Camera.prototype, "rightCamera", {
  20557. get: function () {
  20558. if (this._rigCameras.length < 2) {
  20559. return null;
  20560. }
  20561. return this._rigCameras[1];
  20562. },
  20563. enumerable: true,
  20564. configurable: true
  20565. });
  20566. Camera.prototype.getLeftTarget = function () {
  20567. if (this._rigCameras.length < 1) {
  20568. return null;
  20569. }
  20570. return this._rigCameras[0].getTarget();
  20571. };
  20572. Camera.prototype.getRightTarget = function () {
  20573. if (this._rigCameras.length < 2) {
  20574. return null;
  20575. }
  20576. return this._rigCameras[1].getTarget();
  20577. };
  20578. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20579. if (this.cameraRigMode === mode) {
  20580. return;
  20581. }
  20582. while (this._rigCameras.length > 0) {
  20583. var camera = this._rigCameras.pop();
  20584. if (camera) {
  20585. camera.dispose();
  20586. }
  20587. }
  20588. this.cameraRigMode = mode;
  20589. this._cameraRigParams = {};
  20590. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20591. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20592. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20593. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20594. // create the rig cameras, unless none
  20595. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20596. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20597. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20598. if (leftCamera && rightCamera) {
  20599. this._rigCameras.push(leftCamera);
  20600. this._rigCameras.push(rightCamera);
  20601. }
  20602. }
  20603. switch (this.cameraRigMode) {
  20604. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20605. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20606. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20607. break;
  20608. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20609. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20610. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20611. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20612. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20613. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20614. break;
  20615. case Camera.RIG_MODE_VR:
  20616. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20617. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20618. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20619. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20620. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20621. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20622. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20623. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20624. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20625. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20626. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20627. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20628. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20629. if (metrics.compensateDistortion) {
  20630. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20631. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20632. }
  20633. break;
  20634. case Camera.RIG_MODE_WEBVR:
  20635. if (rigParams.vrDisplay) {
  20636. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20637. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20638. //Left eye
  20639. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20640. this._rigCameras[0].setCameraRigParameter("left", true);
  20641. //leaving this for future reference
  20642. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20643. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20644. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20645. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20646. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20647. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20648. this._rigCameras[0].parent = this;
  20649. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20650. //Right eye
  20651. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20652. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20653. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20654. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20655. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20656. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20657. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20658. this._rigCameras[1].parent = this;
  20659. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20660. if (Camera.UseAlternateWebVRRendering) {
  20661. this._rigCameras[1]._skipRendering = true;
  20662. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20663. }
  20664. }
  20665. break;
  20666. }
  20667. this._cascadePostProcessesToRigCams();
  20668. this.update();
  20669. };
  20670. Camera.prototype._getVRProjectionMatrix = function () {
  20671. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20672. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20673. return this._projectionMatrix;
  20674. };
  20675. Camera.prototype._updateCameraRotationMatrix = function () {
  20676. //Here for WebVR
  20677. };
  20678. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20679. //Here for WebVR
  20680. };
  20681. /**
  20682. * This function MUST be overwritten by the different WebVR cameras available.
  20683. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20684. */
  20685. Camera.prototype._getWebVRProjectionMatrix = function () {
  20686. return BABYLON.Matrix.Identity();
  20687. };
  20688. /**
  20689. * This function MUST be overwritten by the different WebVR cameras available.
  20690. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20691. */
  20692. Camera.prototype._getWebVRViewMatrix = function () {
  20693. return BABYLON.Matrix.Identity();
  20694. };
  20695. Camera.prototype.setCameraRigParameter = function (name, value) {
  20696. if (!this._cameraRigParams) {
  20697. this._cameraRigParams = {};
  20698. }
  20699. this._cameraRigParams[name] = value;
  20700. //provisionnally:
  20701. if (name === "interaxialDistance") {
  20702. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20703. }
  20704. };
  20705. /**
  20706. * needs to be overridden by children so sub has required properties to be copied
  20707. */
  20708. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20709. return null;
  20710. };
  20711. /**
  20712. * May need to be overridden by children
  20713. */
  20714. Camera.prototype._updateRigCameras = function () {
  20715. for (var i = 0; i < this._rigCameras.length; i++) {
  20716. this._rigCameras[i].minZ = this.minZ;
  20717. this._rigCameras[i].maxZ = this.maxZ;
  20718. this._rigCameras[i].fov = this.fov;
  20719. }
  20720. // only update viewport when ANAGLYPH
  20721. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20722. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20723. }
  20724. };
  20725. Camera.prototype._setupInputs = function () {
  20726. };
  20727. Camera.prototype.serialize = function () {
  20728. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20729. // Type
  20730. serializationObject.type = this.getClassName();
  20731. // Parent
  20732. if (this.parent) {
  20733. serializationObject.parentId = this.parent.id;
  20734. }
  20735. if (this.inputs) {
  20736. this.inputs.serialize(serializationObject);
  20737. }
  20738. // Animations
  20739. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20740. serializationObject.ranges = this.serializeAnimationRanges();
  20741. return serializationObject;
  20742. };
  20743. Camera.prototype.clone = function (name) {
  20744. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20745. };
  20746. Camera.prototype.getDirection = function (localAxis) {
  20747. var result = BABYLON.Vector3.Zero();
  20748. this.getDirectionToRef(localAxis, result);
  20749. return result;
  20750. };
  20751. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20752. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20753. };
  20754. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20755. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20756. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20757. switch (type) {
  20758. case "ArcRotateCamera":
  20759. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20760. case "DeviceOrientationCamera":
  20761. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20762. case "FollowCamera":
  20763. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20764. case "ArcFollowCamera":
  20765. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20766. case "GamepadCamera":
  20767. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20768. case "TouchCamera":
  20769. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20770. case "VirtualJoysticksCamera":
  20771. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20772. case "WebVRFreeCamera":
  20773. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20774. case "WebVRGamepadCamera":
  20775. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20776. case "VRDeviceOrientationFreeCamera":
  20777. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20778. case "VRDeviceOrientationGamepadCamera":
  20779. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20780. case "AnaglyphArcRotateCamera":
  20781. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20782. case "AnaglyphFreeCamera":
  20783. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20784. case "AnaglyphGamepadCamera":
  20785. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20786. case "AnaglyphUniversalCamera":
  20787. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20788. case "StereoscopicArcRotateCamera":
  20789. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20790. case "StereoscopicFreeCamera":
  20791. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20792. case "StereoscopicGamepadCamera":
  20793. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20794. case "StereoscopicUniversalCamera":
  20795. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20796. case "FreeCamera":// Forcing Universal here
  20797. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20798. default:// Universal Camera is the default value
  20799. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20800. }
  20801. };
  20802. Camera.prototype.computeWorldMatrix = function () {
  20803. return this.getWorldMatrix();
  20804. };
  20805. Camera.Parse = function (parsedCamera, scene) {
  20806. var type = parsedCamera.type;
  20807. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20808. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20809. // Parent
  20810. if (parsedCamera.parentId) {
  20811. camera._waitingParentId = parsedCamera.parentId;
  20812. }
  20813. //If camera has an input manager, let it parse inputs settings
  20814. if (camera.inputs) {
  20815. camera.inputs.parse(parsedCamera);
  20816. camera._setupInputs();
  20817. }
  20818. if (camera.setPosition) {
  20819. camera.position.copyFromFloats(0, 0, 0);
  20820. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20821. }
  20822. // Target
  20823. if (parsedCamera.target) {
  20824. if (camera.setTarget) {
  20825. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20826. }
  20827. }
  20828. // Apply 3d rig, when found
  20829. if (parsedCamera.cameraRigMode) {
  20830. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20831. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20832. }
  20833. // Animations
  20834. if (parsedCamera.animations) {
  20835. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20836. var parsedAnimation = parsedCamera.animations[animationIndex];
  20837. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20838. }
  20839. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20840. }
  20841. if (parsedCamera.autoAnimate) {
  20842. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20843. }
  20844. return camera;
  20845. };
  20846. // Statics
  20847. Camera._PERSPECTIVE_CAMERA = 0;
  20848. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20849. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20850. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20851. Camera._RIG_MODE_NONE = 0;
  20852. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20853. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20854. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20855. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20856. Camera._RIG_MODE_VR = 20;
  20857. Camera._RIG_MODE_WEBVR = 21;
  20858. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20859. Camera.UseAlternateWebVRRendering = false;
  20860. __decorate([
  20861. BABYLON.serializeAsVector3()
  20862. ], Camera.prototype, "position", void 0);
  20863. __decorate([
  20864. BABYLON.serializeAsVector3()
  20865. ], Camera.prototype, "upVector", void 0);
  20866. __decorate([
  20867. BABYLON.serialize()
  20868. ], Camera.prototype, "orthoLeft", void 0);
  20869. __decorate([
  20870. BABYLON.serialize()
  20871. ], Camera.prototype, "orthoRight", void 0);
  20872. __decorate([
  20873. BABYLON.serialize()
  20874. ], Camera.prototype, "orthoBottom", void 0);
  20875. __decorate([
  20876. BABYLON.serialize()
  20877. ], Camera.prototype, "orthoTop", void 0);
  20878. __decorate([
  20879. BABYLON.serialize()
  20880. ], Camera.prototype, "fov", void 0);
  20881. __decorate([
  20882. BABYLON.serialize()
  20883. ], Camera.prototype, "minZ", void 0);
  20884. __decorate([
  20885. BABYLON.serialize()
  20886. ], Camera.prototype, "maxZ", void 0);
  20887. __decorate([
  20888. BABYLON.serialize()
  20889. ], Camera.prototype, "inertia", void 0);
  20890. __decorate([
  20891. BABYLON.serialize()
  20892. ], Camera.prototype, "mode", void 0);
  20893. __decorate([
  20894. BABYLON.serialize()
  20895. ], Camera.prototype, "layerMask", void 0);
  20896. __decorate([
  20897. BABYLON.serialize()
  20898. ], Camera.prototype, "fovMode", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], Camera.prototype, "cameraRigMode", void 0);
  20902. __decorate([
  20903. BABYLON.serialize()
  20904. ], Camera.prototype, "interaxialDistance", void 0);
  20905. __decorate([
  20906. BABYLON.serialize()
  20907. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20908. return Camera;
  20909. }(BABYLON.Node));
  20910. BABYLON.Camera = Camera;
  20911. })(BABYLON || (BABYLON = {}));
  20912. //# sourceMappingURL=babylon.camera.js.map
  20913. "use strict";
  20914. var BABYLON;
  20915. (function (BABYLON) {
  20916. var RenderingManager = /** @class */ (function () {
  20917. function RenderingManager(scene) {
  20918. this._renderingGroups = new Array();
  20919. this._autoClearDepthStencil = {};
  20920. this._customOpaqueSortCompareFn = {};
  20921. this._customAlphaTestSortCompareFn = {};
  20922. this._customTransparentSortCompareFn = {};
  20923. this._renderinGroupInfo = null;
  20924. this._scene = scene;
  20925. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20926. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20927. }
  20928. }
  20929. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20930. if (depth === void 0) { depth = true; }
  20931. if (stencil === void 0) { stencil = true; }
  20932. if (this._depthStencilBufferAlreadyCleaned) {
  20933. return;
  20934. }
  20935. this._scene.getEngine().clear(null, false, depth, stencil);
  20936. this._depthStencilBufferAlreadyCleaned = true;
  20937. };
  20938. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20939. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20940. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20941. var info = null;
  20942. if (observable) {
  20943. if (!this._renderinGroupInfo) {
  20944. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20945. }
  20946. info = this._renderinGroupInfo;
  20947. info.scene = this._scene;
  20948. info.camera = this._scene.activeCamera;
  20949. }
  20950. // Dispatch sprites
  20951. if (renderSprites) {
  20952. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20953. var manager = this._scene.spriteManagers[index];
  20954. this.dispatchSprites(manager);
  20955. }
  20956. }
  20957. // Render
  20958. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20959. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20960. var renderingGroup = this._renderingGroups[index];
  20961. if (!renderingGroup && !observable)
  20962. continue;
  20963. var renderingGroupMask = 0;
  20964. // Fire PRECLEAR stage
  20965. if (observable && info) {
  20966. renderingGroupMask = Math.pow(2, index);
  20967. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20968. info.renderingGroupId = index;
  20969. observable.notifyObservers(info, renderingGroupMask);
  20970. }
  20971. // Clear depth/stencil if needed
  20972. if (RenderingManager.AUTOCLEAR) {
  20973. var autoClear = this._autoClearDepthStencil[index];
  20974. if (autoClear && autoClear.autoClear) {
  20975. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20976. }
  20977. }
  20978. if (observable && info) {
  20979. // Fire PREOPAQUE stage
  20980. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20981. observable.notifyObservers(info, renderingGroupMask);
  20982. // Fire PRETRANSPARENT stage
  20983. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20984. observable.notifyObservers(info, renderingGroupMask);
  20985. }
  20986. if (renderingGroup)
  20987. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20988. // Fire POSTTRANSPARENT stage
  20989. if (observable && info) {
  20990. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20991. observable.notifyObservers(info, renderingGroupMask);
  20992. }
  20993. }
  20994. };
  20995. RenderingManager.prototype.reset = function () {
  20996. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20997. var renderingGroup = this._renderingGroups[index];
  20998. if (renderingGroup) {
  20999. renderingGroup.prepare();
  21000. }
  21001. }
  21002. };
  21003. RenderingManager.prototype.dispose = function () {
  21004. this.freeRenderingGroups();
  21005. this._renderingGroups.length = 0;
  21006. };
  21007. /**
  21008. * Clear the info related to rendering groups preventing retention points during dispose.
  21009. */
  21010. RenderingManager.prototype.freeRenderingGroups = function () {
  21011. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21012. var renderingGroup = this._renderingGroups[index];
  21013. if (renderingGroup) {
  21014. renderingGroup.dispose();
  21015. }
  21016. }
  21017. };
  21018. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21019. if (this._renderingGroups[renderingGroupId] === undefined) {
  21020. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21021. }
  21022. };
  21023. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21024. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21025. this._prepareRenderingGroup(renderingGroupId);
  21026. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21027. };
  21028. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21029. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21030. this._prepareRenderingGroup(renderingGroupId);
  21031. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21032. };
  21033. /**
  21034. * @param subMesh The submesh to dispatch
  21035. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21036. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21037. */
  21038. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21039. if (mesh === undefined) {
  21040. mesh = subMesh.getMesh();
  21041. }
  21042. var renderingGroupId = mesh.renderingGroupId || 0;
  21043. this._prepareRenderingGroup(renderingGroupId);
  21044. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21045. };
  21046. /**
  21047. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21048. * This allowed control for front to back rendering or reversly depending of the special needs.
  21049. *
  21050. * @param renderingGroupId The rendering group id corresponding to its index
  21051. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21052. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21053. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21054. */
  21055. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21056. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21057. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21058. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21059. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21060. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21061. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21062. if (this._renderingGroups[renderingGroupId]) {
  21063. var group = this._renderingGroups[renderingGroupId];
  21064. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21065. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21066. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21067. }
  21068. };
  21069. /**
  21070. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21071. *
  21072. * @param renderingGroupId The rendering group id corresponding to its index
  21073. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21074. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21075. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21076. */
  21077. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21078. if (depth === void 0) { depth = true; }
  21079. if (stencil === void 0) { stencil = true; }
  21080. this._autoClearDepthStencil[renderingGroupId] = {
  21081. autoClear: autoClearDepthStencil,
  21082. depth: depth,
  21083. stencil: stencil
  21084. };
  21085. };
  21086. /**
  21087. * The max id used for rendering groups (not included)
  21088. */
  21089. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21090. /**
  21091. * The min id used for rendering groups (included)
  21092. */
  21093. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21094. /**
  21095. * Used to globally prevent autoclearing scenes.
  21096. */
  21097. RenderingManager.AUTOCLEAR = true;
  21098. return RenderingManager;
  21099. }());
  21100. BABYLON.RenderingManager = RenderingManager;
  21101. })(BABYLON || (BABYLON = {}));
  21102. //# sourceMappingURL=babylon.renderingManager.js.map
  21103. "use strict";
  21104. var BABYLON;
  21105. (function (BABYLON) {
  21106. var RenderingGroup = /** @class */ (function () {
  21107. /**
  21108. * Creates a new rendering group.
  21109. * @param index The rendering group index
  21110. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21111. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21112. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21113. */
  21114. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21115. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21116. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21117. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21118. this.index = index;
  21119. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21120. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21121. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21122. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21123. this._particleSystems = new BABYLON.SmartArray(256);
  21124. this._spriteManagers = new BABYLON.SmartArray(256);
  21125. this._edgesRenderers = new BABYLON.SmartArray(16);
  21126. this._scene = scene;
  21127. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21128. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21129. this.transparentSortCompareFn = transparentSortCompareFn;
  21130. }
  21131. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21132. /**
  21133. * Set the opaque sort comparison function.
  21134. * If null the sub meshes will be render in the order they were created
  21135. */
  21136. set: function (value) {
  21137. this._opaqueSortCompareFn = value;
  21138. if (value) {
  21139. this._renderOpaque = this.renderOpaqueSorted;
  21140. }
  21141. else {
  21142. this._renderOpaque = RenderingGroup.renderUnsorted;
  21143. }
  21144. },
  21145. enumerable: true,
  21146. configurable: true
  21147. });
  21148. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21149. /**
  21150. * Set the alpha test sort comparison function.
  21151. * If null the sub meshes will be render in the order they were created
  21152. */
  21153. set: function (value) {
  21154. this._alphaTestSortCompareFn = value;
  21155. if (value) {
  21156. this._renderAlphaTest = this.renderAlphaTestSorted;
  21157. }
  21158. else {
  21159. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21160. }
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21166. /**
  21167. * Set the transparent sort comparison function.
  21168. * If null the sub meshes will be render in the order they were created
  21169. */
  21170. set: function (value) {
  21171. if (value) {
  21172. this._transparentSortCompareFn = value;
  21173. }
  21174. else {
  21175. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21176. }
  21177. this._renderTransparent = this.renderTransparentSorted;
  21178. },
  21179. enumerable: true,
  21180. configurable: true
  21181. });
  21182. /**
  21183. * Render all the sub meshes contained in the group.
  21184. * @param customRenderFunction Used to override the default render behaviour of the group.
  21185. * @returns true if rendered some submeshes.
  21186. */
  21187. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21188. if (customRenderFunction) {
  21189. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21190. return;
  21191. }
  21192. var engine = this._scene.getEngine();
  21193. // Depth only
  21194. if (this._depthOnlySubMeshes.length !== 0) {
  21195. engine.setColorWrite(false);
  21196. this._renderAlphaTest(this._depthOnlySubMeshes);
  21197. engine.setColorWrite(true);
  21198. }
  21199. // Opaque
  21200. if (this._opaqueSubMeshes.length !== 0) {
  21201. this._renderOpaque(this._opaqueSubMeshes);
  21202. }
  21203. // Alpha test
  21204. if (this._alphaTestSubMeshes.length !== 0) {
  21205. this._renderAlphaTest(this._alphaTestSubMeshes);
  21206. }
  21207. var stencilState = engine.getStencilBuffer();
  21208. engine.setStencilBuffer(false);
  21209. // Sprites
  21210. if (renderSprites) {
  21211. this._renderSprites();
  21212. }
  21213. // Particles
  21214. if (renderParticles) {
  21215. this._renderParticles(activeMeshes);
  21216. }
  21217. if (this.onBeforeTransparentRendering) {
  21218. this.onBeforeTransparentRendering();
  21219. }
  21220. // Transparent
  21221. if (this._transparentSubMeshes.length !== 0) {
  21222. this._renderTransparent(this._transparentSubMeshes);
  21223. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21224. }
  21225. // Set back stencil to false in case it changes before the edge renderer.
  21226. engine.setStencilBuffer(false);
  21227. // Edges
  21228. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21229. this._edgesRenderers.data[edgesRendererIndex].render();
  21230. }
  21231. // Restore Stencil state.
  21232. engine.setStencilBuffer(stencilState);
  21233. };
  21234. /**
  21235. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21236. * @param subMeshes The submeshes to render
  21237. */
  21238. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21239. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21240. };
  21241. /**
  21242. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21243. * @param subMeshes The submeshes to render
  21244. */
  21245. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21246. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21247. };
  21248. /**
  21249. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21250. * @param subMeshes The submeshes to render
  21251. */
  21252. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21253. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21254. };
  21255. /**
  21256. * Renders the submeshes in a specified order.
  21257. * @param subMeshes The submeshes to sort before render
  21258. * @param sortCompareFn The comparison function use to sort
  21259. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21260. * @param transparent Specifies to activate blending if true
  21261. */
  21262. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21263. var subIndex = 0;
  21264. var subMesh;
  21265. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21266. for (; subIndex < subMeshes.length; subIndex++) {
  21267. subMesh = subMeshes.data[subIndex];
  21268. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21269. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21270. }
  21271. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21272. if (sortCompareFn) {
  21273. sortedArray.sort(sortCompareFn);
  21274. }
  21275. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21276. subMesh = sortedArray[subIndex];
  21277. if (transparent) {
  21278. var material = subMesh.getMaterial();
  21279. if (material && material.needDepthPrePass) {
  21280. var engine = material.getScene().getEngine();
  21281. engine.setColorWrite(false);
  21282. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21283. subMesh.render(false);
  21284. engine.setColorWrite(true);
  21285. }
  21286. }
  21287. subMesh.render(transparent);
  21288. }
  21289. };
  21290. /**
  21291. * Renders the submeshes in the order they were dispatched (no sort applied).
  21292. * @param subMeshes The submeshes to render
  21293. */
  21294. RenderingGroup.renderUnsorted = function (subMeshes) {
  21295. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21296. var submesh = subMeshes.data[subIndex];
  21297. submesh.render(false);
  21298. }
  21299. };
  21300. /**
  21301. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21302. * are rendered back to front if in the same alpha index.
  21303. *
  21304. * @param a The first submesh
  21305. * @param b The second submesh
  21306. * @returns The result of the comparison
  21307. */
  21308. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21309. // Alpha index first
  21310. if (a._alphaIndex > b._alphaIndex) {
  21311. return 1;
  21312. }
  21313. if (a._alphaIndex < b._alphaIndex) {
  21314. return -1;
  21315. }
  21316. // Then distance to camera
  21317. return RenderingGroup.backToFrontSortCompare(a, b);
  21318. };
  21319. /**
  21320. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21321. * are rendered back to front.
  21322. *
  21323. * @param a The first submesh
  21324. * @param b The second submesh
  21325. * @returns The result of the comparison
  21326. */
  21327. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21328. // Then distance to camera
  21329. if (a._distanceToCamera < b._distanceToCamera) {
  21330. return 1;
  21331. }
  21332. if (a._distanceToCamera > b._distanceToCamera) {
  21333. return -1;
  21334. }
  21335. return 0;
  21336. };
  21337. /**
  21338. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21339. * are rendered front to back (prevent overdraw).
  21340. *
  21341. * @param a The first submesh
  21342. * @param b The second submesh
  21343. * @returns The result of the comparison
  21344. */
  21345. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21346. // Then distance to camera
  21347. if (a._distanceToCamera < b._distanceToCamera) {
  21348. return -1;
  21349. }
  21350. if (a._distanceToCamera > b._distanceToCamera) {
  21351. return 1;
  21352. }
  21353. return 0;
  21354. };
  21355. /**
  21356. * Resets the different lists of submeshes to prepare a new frame.
  21357. */
  21358. RenderingGroup.prototype.prepare = function () {
  21359. this._opaqueSubMeshes.reset();
  21360. this._transparentSubMeshes.reset();
  21361. this._alphaTestSubMeshes.reset();
  21362. this._depthOnlySubMeshes.reset();
  21363. this._particleSystems.reset();
  21364. this._spriteManagers.reset();
  21365. this._edgesRenderers.reset();
  21366. };
  21367. RenderingGroup.prototype.dispose = function () {
  21368. this._opaqueSubMeshes.dispose();
  21369. this._transparentSubMeshes.dispose();
  21370. this._alphaTestSubMeshes.dispose();
  21371. this._depthOnlySubMeshes.dispose();
  21372. this._particleSystems.dispose();
  21373. this._spriteManagers.dispose();
  21374. this._edgesRenderers.dispose();
  21375. };
  21376. /**
  21377. * Inserts the submesh in its correct queue depending on its material.
  21378. * @param subMesh The submesh to dispatch
  21379. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21380. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21381. */
  21382. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21383. // Get mesh and materials if not provided
  21384. if (mesh === undefined) {
  21385. mesh = subMesh.getMesh();
  21386. }
  21387. if (material === undefined) {
  21388. material = subMesh.getMaterial();
  21389. }
  21390. if (material === null || material === undefined) {
  21391. return;
  21392. }
  21393. if (material.needAlphaBlendingForMesh(mesh)) {
  21394. this._transparentSubMeshes.push(subMesh);
  21395. }
  21396. else if (material.needAlphaTesting()) {
  21397. if (material.needDepthPrePass) {
  21398. this._depthOnlySubMeshes.push(subMesh);
  21399. }
  21400. this._alphaTestSubMeshes.push(subMesh);
  21401. }
  21402. else {
  21403. if (material.needDepthPrePass) {
  21404. this._depthOnlySubMeshes.push(subMesh);
  21405. }
  21406. this._opaqueSubMeshes.push(subMesh); // Opaque
  21407. }
  21408. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21409. this._edgesRenderers.push(mesh._edgesRenderer);
  21410. }
  21411. };
  21412. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21413. this._spriteManagers.push(spriteManager);
  21414. };
  21415. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21416. this._particleSystems.push(particleSystem);
  21417. };
  21418. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21419. if (this._particleSystems.length === 0) {
  21420. return;
  21421. }
  21422. // Particles
  21423. var activeCamera = this._scene.activeCamera;
  21424. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21425. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21426. var particleSystem = this._particleSystems.data[particleIndex];
  21427. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21428. continue;
  21429. }
  21430. var emitter = particleSystem.emitter;
  21431. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21432. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21433. }
  21434. }
  21435. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21436. };
  21437. RenderingGroup.prototype._renderSprites = function () {
  21438. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21439. return;
  21440. }
  21441. // Sprites
  21442. var activeCamera = this._scene.activeCamera;
  21443. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21444. for (var id = 0; id < this._spriteManagers.length; id++) {
  21445. var spriteManager = this._spriteManagers.data[id];
  21446. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21447. spriteManager.render();
  21448. }
  21449. }
  21450. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21451. };
  21452. return RenderingGroup;
  21453. }());
  21454. BABYLON.RenderingGroup = RenderingGroup;
  21455. })(BABYLON || (BABYLON = {}));
  21456. //# sourceMappingURL=babylon.renderingGroup.js.map
  21457. "use strict";
  21458. var BABYLON;
  21459. (function (BABYLON) {
  21460. /** @ignore */
  21461. var ClickInfo = /** @class */ (function () {
  21462. function ClickInfo() {
  21463. this._singleClick = false;
  21464. this._doubleClick = false;
  21465. this._hasSwiped = false;
  21466. this._ignore = false;
  21467. }
  21468. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21469. get: function () {
  21470. return this._singleClick;
  21471. },
  21472. set: function (b) {
  21473. this._singleClick = b;
  21474. },
  21475. enumerable: true,
  21476. configurable: true
  21477. });
  21478. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21479. get: function () {
  21480. return this._doubleClick;
  21481. },
  21482. set: function (b) {
  21483. this._doubleClick = b;
  21484. },
  21485. enumerable: true,
  21486. configurable: true
  21487. });
  21488. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21489. get: function () {
  21490. return this._hasSwiped;
  21491. },
  21492. set: function (b) {
  21493. this._hasSwiped = b;
  21494. },
  21495. enumerable: true,
  21496. configurable: true
  21497. });
  21498. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21499. get: function () {
  21500. return this._ignore;
  21501. },
  21502. set: function (b) {
  21503. this._ignore = b;
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. return ClickInfo;
  21509. }());
  21510. /**
  21511. * This class is used by the onRenderingGroupObservable
  21512. */
  21513. var RenderingGroupInfo = /** @class */ (function () {
  21514. function RenderingGroupInfo() {
  21515. }
  21516. /**
  21517. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21518. * This stage will be fired no matter what
  21519. */
  21520. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21521. /**
  21522. * Called before opaque object are rendered.
  21523. * This stage will be fired only if there's 3D Opaque content to render
  21524. */
  21525. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21526. /**
  21527. * Called after the opaque objects are rendered and before the transparent ones
  21528. * This stage will be fired only if there's 3D transparent content to render
  21529. */
  21530. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21531. /**
  21532. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21533. * This stage will be fired no matter what
  21534. */
  21535. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21536. return RenderingGroupInfo;
  21537. }());
  21538. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21539. /**
  21540. * Represents a scene to be rendered by the engine.
  21541. * @see http://doc.babylonjs.com/features/scene
  21542. */
  21543. var Scene = /** @class */ (function () {
  21544. /**
  21545. * @constructor
  21546. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21547. */
  21548. function Scene(engine) {
  21549. // Members
  21550. /**
  21551. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  21552. */
  21553. this.autoClear = true;
  21554. /**
  21555. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  21556. */
  21557. this.autoClearDepthAndStencil = true;
  21558. /**
  21559. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  21560. */
  21561. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21562. /**
  21563. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  21564. */
  21565. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21566. this._forceWireframe = false;
  21567. this._forcePointsCloud = false;
  21568. /**
  21569. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  21570. */
  21571. this.forceShowBoundingBoxes = false;
  21572. this.animationsEnabled = true;
  21573. this.useConstantAnimationDeltaTime = false;
  21574. this.constantlyUpdateMeshUnderPointer = false;
  21575. this.hoverCursor = "pointer";
  21576. this.defaultCursor = "";
  21577. /**
  21578. * This is used to call preventDefault() on pointer down
  21579. * in order to block unwanted artifacts like system double clicks
  21580. */
  21581. this.preventDefaultOnPointerDown = true;
  21582. /**
  21583. * Gets a list of Animations associated with the node
  21584. */
  21585. this.animations = new Array();
  21586. // Metadata
  21587. this.metadata = null;
  21588. /**
  21589. * Use this array to add regular expressions used to disable offline support for specific urls
  21590. */
  21591. this.disableOfflineSupportExceptionRules = new Array();
  21592. /**
  21593. * An event triggered when the scene is disposed.
  21594. */
  21595. this.onDisposeObservable = new BABYLON.Observable();
  21596. this._onDisposeObserver = null;
  21597. /**
  21598. * An event triggered before rendering the scene (right after animations and physics)
  21599. */
  21600. this.onBeforeRenderObservable = new BABYLON.Observable();
  21601. this._onBeforeRenderObserver = null;
  21602. /**
  21603. * An event triggered after rendering the scene
  21604. */
  21605. this.onAfterRenderObservable = new BABYLON.Observable();
  21606. this._onAfterRenderObserver = null;
  21607. /**
  21608. * An event triggered before animating the scene
  21609. */
  21610. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21611. /**
  21612. * An event triggered after animations processing
  21613. */
  21614. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21615. /**
  21616. * An event triggered before draw calls are ready to be sent
  21617. */
  21618. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21619. /**
  21620. * An event triggered after draw calls have been sent
  21621. */
  21622. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21623. /**
  21624. * An event triggered when physic simulation is about to be run
  21625. */
  21626. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21627. /**
  21628. * An event triggered when physic simulation has been done
  21629. */
  21630. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21631. /**
  21632. * An event triggered when the scene is ready
  21633. */
  21634. this.onReadyObservable = new BABYLON.Observable();
  21635. /**
  21636. * An event triggered before rendering a camera
  21637. */
  21638. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21639. this._onBeforeCameraRenderObserver = null;
  21640. /**
  21641. * An event triggered after rendering a camera
  21642. */
  21643. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21644. this._onAfterCameraRenderObserver = null;
  21645. /**
  21646. * An event triggered when active meshes evaluation is about to start
  21647. */
  21648. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21649. /**
  21650. * An event triggered when active meshes evaluation is done
  21651. */
  21652. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21653. /**
  21654. * An event triggered when particles rendering is about to start
  21655. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21656. */
  21657. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21658. /**
  21659. * An event triggered when particles rendering is done
  21660. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21661. */
  21662. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21663. /**
  21664. * An event triggered when sprites rendering is about to start
  21665. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21666. */
  21667. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21668. /**
  21669. * An event triggered when sprites rendering is done
  21670. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21671. */
  21672. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21673. /**
  21674. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21675. */
  21676. this.onDataLoadedObservable = new BABYLON.Observable();
  21677. /**
  21678. * An event triggered when a camera is created
  21679. */
  21680. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21681. /**
  21682. * An event triggered when a camera is removed
  21683. */
  21684. this.onCameraRemovedObservable = new BABYLON.Observable();
  21685. /**
  21686. * An event triggered when a light is created
  21687. */
  21688. this.onNewLightAddedObservable = new BABYLON.Observable();
  21689. /**
  21690. * An event triggered when a light is removed
  21691. */
  21692. this.onLightRemovedObservable = new BABYLON.Observable();
  21693. /**
  21694. * An event triggered when a geometry is created
  21695. */
  21696. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21697. /**
  21698. * An event triggered when a geometry is removed
  21699. */
  21700. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21701. /**
  21702. * An event triggered when a transform node is created
  21703. */
  21704. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21705. /**
  21706. * An event triggered when a transform node is removed
  21707. */
  21708. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21709. /**
  21710. * An event triggered when a mesh is created
  21711. */
  21712. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21713. /**
  21714. * An event triggered when a mesh is removed
  21715. */
  21716. this.onMeshRemovedObservable = new BABYLON.Observable();
  21717. /**
  21718. * An event triggered when render targets are about to be rendered
  21719. * Can happen multiple times per frame.
  21720. */
  21721. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered when render targets were rendered.
  21724. * Can happen multiple times per frame.
  21725. */
  21726. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21727. /**
  21728. * An event triggered before calculating deterministic simulation step
  21729. */
  21730. this.onBeforeStepObservable = new BABYLON.Observable();
  21731. /**
  21732. * An event triggered after calculating deterministic simulation step
  21733. */
  21734. this.onAfterStepObservable = new BABYLON.Observable();
  21735. /**
  21736. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21737. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21738. * 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)
  21739. */
  21740. this.onRenderingGroupObservable = new BABYLON.Observable();
  21741. // Animations
  21742. this.animations = [];
  21743. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21744. /**
  21745. * 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).
  21746. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21747. */
  21748. this.onPrePointerObservable = new BABYLON.Observable();
  21749. /**
  21750. * Observable event triggered each time an input event is received from the rendering canvas
  21751. */
  21752. this.onPointerObservable = new BABYLON.Observable();
  21753. this._meshPickProceed = false;
  21754. this._currentPickResult = null;
  21755. this._previousPickResult = null;
  21756. this._totalPointersPressed = 0;
  21757. this._doubleClickOccured = false;
  21758. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21759. this.cameraToUseForPointers = null;
  21760. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21761. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21762. this._startingPointerTime = 0;
  21763. this._previousStartingPointerTime = 0;
  21764. // Deterministic lockstep
  21765. this._timeAccumulator = 0;
  21766. this._currentStepId = 0;
  21767. this._currentInternalStep = 0;
  21768. // Keyboard
  21769. /**
  21770. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21771. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21772. */
  21773. this.onPreKeyboardObservable = new BABYLON.Observable();
  21774. /**
  21775. * Observable event triggered each time an keyboard event is received from the hosting window
  21776. */
  21777. this.onKeyboardObservable = new BABYLON.Observable();
  21778. // Coordinate system
  21779. /**
  21780. * use right-handed coordinate system on this scene.
  21781. */
  21782. this._useRightHandedSystem = false;
  21783. // Fog
  21784. this._fogEnabled = true;
  21785. this._fogMode = Scene.FOGMODE_NONE;
  21786. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21787. this.fogDensity = 0.1;
  21788. this.fogStart = 0;
  21789. this.fogEnd = 1000.0;
  21790. // Lights
  21791. /**
  21792. * is shadow enabled on this scene.
  21793. */
  21794. this._shadowsEnabled = true;
  21795. /**
  21796. * is light enabled on this scene.
  21797. */
  21798. this._lightsEnabled = true;
  21799. /**
  21800. * All of the lights added to this scene.
  21801. */
  21802. this.lights = new Array();
  21803. // Cameras
  21804. /** All of the cameras added to this scene. */
  21805. this.cameras = new Array();
  21806. /** All of the active cameras added to this scene. */
  21807. this.activeCameras = new Array();
  21808. // Meshes
  21809. /**
  21810. * All of the tranform nodes added to this scene.
  21811. */
  21812. this.transformNodes = new Array();
  21813. /**
  21814. * All of the (abstract) meshes added to this scene.
  21815. */
  21816. this.meshes = new Array();
  21817. /**
  21818. * All of the animation groups added to this scene.
  21819. */
  21820. this.animationGroups = new Array();
  21821. // Geometries
  21822. this._geometries = new Array();
  21823. this.materials = new Array();
  21824. this.multiMaterials = new Array();
  21825. // Textures
  21826. this._texturesEnabled = true;
  21827. this.textures = new Array();
  21828. // Particles
  21829. this.particlesEnabled = true;
  21830. this.particleSystems = new Array();
  21831. // Sprites
  21832. this.spritesEnabled = true;
  21833. this.spriteManagers = new Array();
  21834. /**
  21835. * The list of layers (background and foreground) of the scene.
  21836. */
  21837. this.layers = new Array();
  21838. /**
  21839. * The list of effect layers (highlights/glow) contained in the scene.
  21840. */
  21841. this.effectLayers = new Array();
  21842. // Skeletons
  21843. this._skeletonsEnabled = true;
  21844. this.skeletons = new Array();
  21845. // Morph targets
  21846. this.morphTargetManagers = new Array();
  21847. // Lens flares
  21848. this.lensFlaresEnabled = true;
  21849. this.lensFlareSystems = new Array();
  21850. // Collisions
  21851. this.collisionsEnabled = true;
  21852. /** Defines the gravity applied to this scene */
  21853. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21854. // Postprocesses
  21855. this.postProcesses = new Array();
  21856. this.postProcessesEnabled = true;
  21857. // Customs render targets
  21858. this.renderTargetsEnabled = true;
  21859. this.dumpNextRenderTargets = false;
  21860. this.customRenderTargets = new Array();
  21861. // Imported meshes
  21862. this.importedMeshesFiles = new Array();
  21863. // Probes
  21864. this.probesEnabled = true;
  21865. this.reflectionProbes = new Array();
  21866. this._actionManagers = new Array();
  21867. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21868. // Procedural textures
  21869. this.proceduralTexturesEnabled = true;
  21870. this._proceduralTextures = new Array();
  21871. this.soundTracks = new Array();
  21872. this._audioEnabled = true;
  21873. this._headphone = false;
  21874. // Performance counters
  21875. this._totalVertices = new BABYLON.PerfCounter();
  21876. this._activeIndices = new BABYLON.PerfCounter();
  21877. this._activeParticles = new BABYLON.PerfCounter();
  21878. this._activeBones = new BABYLON.PerfCounter();
  21879. this._animationTime = 0;
  21880. this.animationTimeScale = 1;
  21881. this._renderId = 0;
  21882. this._executeWhenReadyTimeoutId = -1;
  21883. this._intermediateRendering = false;
  21884. this._viewUpdateFlag = -1;
  21885. this._projectionUpdateFlag = -1;
  21886. this._alternateViewUpdateFlag = -1;
  21887. this._alternateProjectionUpdateFlag = -1;
  21888. this._toBeDisposed = new BABYLON.SmartArray(256);
  21889. this._activeRequests = new Array();
  21890. this._pendingData = new Array();
  21891. this._isDisposed = false;
  21892. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21893. this._activeMeshes = new BABYLON.SmartArray(256);
  21894. this._processedMaterials = new BABYLON.SmartArray(256);
  21895. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21896. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21897. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21898. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21899. this._activeAnimatables = new Array();
  21900. this._transformMatrix = BABYLON.Matrix.Zero();
  21901. this._useAlternateCameraConfiguration = false;
  21902. this._alternateRendering = false;
  21903. this.requireLightSorting = false;
  21904. this._depthRenderer = {};
  21905. this._activeMeshesFrozen = false;
  21906. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21907. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21908. this._engine.scenes.push(this);
  21909. this._uid = null;
  21910. this._renderingManager = new BABYLON.RenderingManager(this);
  21911. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21912. if (BABYLON.OutlineRenderer) {
  21913. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21914. }
  21915. if (BABYLON.Tools.IsWindowObjectExist()) {
  21916. this.attachControl();
  21917. }
  21918. //simplification queue
  21919. if (BABYLON.SimplificationQueue) {
  21920. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21921. }
  21922. //collision coordinator initialization. For now legacy per default.
  21923. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21924. // Uniform Buffer
  21925. this._createUbo();
  21926. // Default Image processing definition.
  21927. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21928. }
  21929. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21930. /** The fog is deactivated */
  21931. get: function () {
  21932. return Scene._FOGMODE_NONE;
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21938. /** The fog density is following an exponential function */
  21939. get: function () {
  21940. return Scene._FOGMODE_EXP;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21946. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21947. get: function () {
  21948. return Scene._FOGMODE_EXP2;
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21954. /** The fog density is following a linear function. */
  21955. get: function () {
  21956. return Scene._FOGMODE_LINEAR;
  21957. },
  21958. enumerable: true,
  21959. configurable: true
  21960. });
  21961. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21962. /**
  21963. * Texture used in all pbr material as the reflection texture.
  21964. * As in the majority of the scene they are the same (exception for multi room and so on),
  21965. * this is easier to reference from here than from all the materials.
  21966. */
  21967. get: function () {
  21968. return this._environmentTexture;
  21969. },
  21970. /**
  21971. * Texture used in all pbr material as the reflection texture.
  21972. * As in the majority of the scene they are the same (exception for multi room and so on),
  21973. * this is easier to set here than in all the materials.
  21974. */
  21975. set: function (value) {
  21976. if (this._environmentTexture === value) {
  21977. return;
  21978. }
  21979. this._environmentTexture = value;
  21980. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21981. },
  21982. enumerable: true,
  21983. configurable: true
  21984. });
  21985. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21986. /**
  21987. * Default image processing configuration used either in the rendering
  21988. * Forward main pass or through the imageProcessingPostProcess if present.
  21989. * As in the majority of the scene they are the same (exception for multi camera),
  21990. * this is easier to reference from here than from all the materials and post process.
  21991. *
  21992. * No setter as we it is a shared configuration, you can set the values instead.
  21993. */
  21994. get: function () {
  21995. return this._imageProcessingConfiguration;
  21996. },
  21997. enumerable: true,
  21998. configurable: true
  21999. });
  22000. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22001. get: function () {
  22002. return this._forceWireframe;
  22003. },
  22004. /**
  22005. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  22006. */
  22007. set: function (value) {
  22008. if (this._forceWireframe === value) {
  22009. return;
  22010. }
  22011. this._forceWireframe = value;
  22012. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22013. },
  22014. enumerable: true,
  22015. configurable: true
  22016. });
  22017. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22018. get: function () {
  22019. return this._forcePointsCloud;
  22020. },
  22021. /**
  22022. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  22023. */
  22024. set: function (value) {
  22025. if (this._forcePointsCloud === value) {
  22026. return;
  22027. }
  22028. this._forcePointsCloud = value;
  22029. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22030. },
  22031. enumerable: true,
  22032. configurable: true
  22033. });
  22034. Object.defineProperty(Scene.prototype, "onDispose", {
  22035. /** A function to be executed when this scene is disposed. */
  22036. set: function (callback) {
  22037. if (this._onDisposeObserver) {
  22038. this.onDisposeObservable.remove(this._onDisposeObserver);
  22039. }
  22040. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Object.defineProperty(Scene.prototype, "beforeRender", {
  22046. /** A function to be executed before rendering this scene */
  22047. set: function (callback) {
  22048. if (this._onBeforeRenderObserver) {
  22049. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22050. }
  22051. if (callback) {
  22052. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22053. }
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Object.defineProperty(Scene.prototype, "afterRender", {
  22059. /** A function to be executed after rendering this scene */
  22060. set: function (callback) {
  22061. if (this._onAfterRenderObserver) {
  22062. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22063. }
  22064. if (callback) {
  22065. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22066. }
  22067. },
  22068. enumerable: true,
  22069. configurable: true
  22070. });
  22071. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22072. set: function (callback) {
  22073. if (this._onBeforeCameraRenderObserver) {
  22074. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22075. }
  22076. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22077. },
  22078. enumerable: true,
  22079. configurable: true
  22080. });
  22081. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22082. set: function (callback) {
  22083. if (this._onAfterCameraRenderObserver) {
  22084. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22085. }
  22086. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22092. get: function () {
  22093. if (!this._gamepadManager) {
  22094. this._gamepadManager = new BABYLON.GamepadManager(this);
  22095. }
  22096. return this._gamepadManager;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22102. get: function () {
  22103. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22104. },
  22105. enumerable: true,
  22106. configurable: true
  22107. });
  22108. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22109. get: function () {
  22110. return this._useRightHandedSystem;
  22111. },
  22112. set: function (value) {
  22113. if (this._useRightHandedSystem === value) {
  22114. return;
  22115. }
  22116. this._useRightHandedSystem = value;
  22117. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22118. },
  22119. enumerable: true,
  22120. configurable: true
  22121. });
  22122. Scene.prototype.setStepId = function (newStepId) {
  22123. this._currentStepId = newStepId;
  22124. };
  22125. ;
  22126. Scene.prototype.getStepId = function () {
  22127. return this._currentStepId;
  22128. };
  22129. ;
  22130. Scene.prototype.getInternalStep = function () {
  22131. return this._currentInternalStep;
  22132. };
  22133. ;
  22134. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22135. get: function () {
  22136. return this._fogEnabled;
  22137. },
  22138. /**
  22139. * is fog enabled on this scene.
  22140. */
  22141. set: function (value) {
  22142. if (this._fogEnabled === value) {
  22143. return;
  22144. }
  22145. this._fogEnabled = value;
  22146. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22147. },
  22148. enumerable: true,
  22149. configurable: true
  22150. });
  22151. Object.defineProperty(Scene.prototype, "fogMode", {
  22152. get: function () {
  22153. return this._fogMode;
  22154. },
  22155. set: function (value) {
  22156. if (this._fogMode === value) {
  22157. return;
  22158. }
  22159. this._fogMode = value;
  22160. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22161. },
  22162. enumerable: true,
  22163. configurable: true
  22164. });
  22165. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22166. get: function () {
  22167. return this._shadowsEnabled;
  22168. },
  22169. set: function (value) {
  22170. if (this._shadowsEnabled === value) {
  22171. return;
  22172. }
  22173. this._shadowsEnabled = value;
  22174. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22175. },
  22176. enumerable: true,
  22177. configurable: true
  22178. });
  22179. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22180. get: function () {
  22181. return this._lightsEnabled;
  22182. },
  22183. set: function (value) {
  22184. if (this._lightsEnabled === value) {
  22185. return;
  22186. }
  22187. this._lightsEnabled = value;
  22188. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22189. },
  22190. enumerable: true,
  22191. configurable: true
  22192. });
  22193. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22194. /** The default material used on meshes when no material is affected */
  22195. get: function () {
  22196. if (!this._defaultMaterial) {
  22197. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22198. }
  22199. return this._defaultMaterial;
  22200. },
  22201. /** The default material used on meshes when no material is affected */
  22202. set: function (value) {
  22203. this._defaultMaterial = value;
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22209. get: function () {
  22210. return this._texturesEnabled;
  22211. },
  22212. set: function (value) {
  22213. if (this._texturesEnabled === value) {
  22214. return;
  22215. }
  22216. this._texturesEnabled = value;
  22217. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22223. get: function () {
  22224. return this._skeletonsEnabled;
  22225. },
  22226. set: function (value) {
  22227. if (this._skeletonsEnabled === value) {
  22228. return;
  22229. }
  22230. this._skeletonsEnabled = value;
  22231. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22232. },
  22233. enumerable: true,
  22234. configurable: true
  22235. });
  22236. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22237. get: function () {
  22238. if (!this._postProcessRenderPipelineManager) {
  22239. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22240. }
  22241. return this._postProcessRenderPipelineManager;
  22242. },
  22243. enumerable: true,
  22244. configurable: true
  22245. });
  22246. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22247. get: function () {
  22248. if (!this._mainSoundTrack) {
  22249. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22250. }
  22251. return this._mainSoundTrack;
  22252. },
  22253. enumerable: true,
  22254. configurable: true
  22255. });
  22256. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22257. get: function () {
  22258. return this._alternateRendering;
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22264. get: function () {
  22265. return this._frustumPlanes;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22271. /**
  22272. * Gets the current geometry buffer associated to the scene.
  22273. */
  22274. get: function () {
  22275. return this._geometryBufferRenderer;
  22276. },
  22277. /**
  22278. * Sets the current geometry buffer for the scene.
  22279. */
  22280. set: function (geometryBufferRenderer) {
  22281. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22282. this._geometryBufferRenderer = geometryBufferRenderer;
  22283. }
  22284. },
  22285. enumerable: true,
  22286. configurable: true
  22287. });
  22288. Object.defineProperty(Scene.prototype, "debugLayer", {
  22289. // Properties
  22290. get: function () {
  22291. if (!this._debugLayer) {
  22292. this._debugLayer = new BABYLON.DebugLayer(this);
  22293. }
  22294. return this._debugLayer;
  22295. },
  22296. enumerable: true,
  22297. configurable: true
  22298. });
  22299. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22300. get: function () {
  22301. return this._workerCollisions;
  22302. },
  22303. set: function (enabled) {
  22304. if (!BABYLON.CollisionCoordinatorLegacy) {
  22305. return;
  22306. }
  22307. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22308. this._workerCollisions = enabled;
  22309. if (this.collisionCoordinator) {
  22310. this.collisionCoordinator.destroy();
  22311. }
  22312. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22313. this.collisionCoordinator.init(this);
  22314. },
  22315. enumerable: true,
  22316. configurable: true
  22317. });
  22318. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22319. get: function () {
  22320. return this._selectionOctree;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22326. /**
  22327. * The mesh that is currently under the pointer.
  22328. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22329. */
  22330. get: function () {
  22331. return this._pointerOverMesh;
  22332. },
  22333. enumerable: true,
  22334. configurable: true
  22335. });
  22336. Object.defineProperty(Scene.prototype, "pointerX", {
  22337. /**
  22338. * Current on-screen X position of the pointer
  22339. * @return {number} X position of the pointer
  22340. */
  22341. get: function () {
  22342. return this._pointerX;
  22343. },
  22344. enumerable: true,
  22345. configurable: true
  22346. });
  22347. Object.defineProperty(Scene.prototype, "pointerY", {
  22348. /**
  22349. * Current on-screen Y position of the pointer
  22350. * @return {number} Y position of the pointer
  22351. */
  22352. get: function () {
  22353. return this._pointerY;
  22354. },
  22355. enumerable: true,
  22356. configurable: true
  22357. });
  22358. Scene.prototype.getCachedMaterial = function () {
  22359. return this._cachedMaterial;
  22360. };
  22361. Scene.prototype.getCachedEffect = function () {
  22362. return this._cachedEffect;
  22363. };
  22364. Scene.prototype.getCachedVisibility = function () {
  22365. return this._cachedVisibility;
  22366. };
  22367. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22368. if (visibility === void 0) { visibility = 1; }
  22369. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22370. };
  22371. Scene.prototype.getBoundingBoxRenderer = function () {
  22372. if (!this._boundingBoxRenderer) {
  22373. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22374. }
  22375. return this._boundingBoxRenderer;
  22376. };
  22377. Scene.prototype.getOutlineRenderer = function () {
  22378. return this._outlineRenderer;
  22379. };
  22380. Scene.prototype.getEngine = function () {
  22381. return this._engine;
  22382. };
  22383. Scene.prototype.getTotalVertices = function () {
  22384. return this._totalVertices.current;
  22385. };
  22386. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22387. get: function () {
  22388. return this._totalVertices;
  22389. },
  22390. enumerable: true,
  22391. configurable: true
  22392. });
  22393. Scene.prototype.getActiveIndices = function () {
  22394. return this._activeIndices.current;
  22395. };
  22396. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22397. get: function () {
  22398. return this._activeIndices;
  22399. },
  22400. enumerable: true,
  22401. configurable: true
  22402. });
  22403. Scene.prototype.getActiveParticles = function () {
  22404. return this._activeParticles.current;
  22405. };
  22406. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22407. get: function () {
  22408. return this._activeParticles;
  22409. },
  22410. enumerable: true,
  22411. configurable: true
  22412. });
  22413. Scene.prototype.getActiveBones = function () {
  22414. return this._activeBones.current;
  22415. };
  22416. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22417. get: function () {
  22418. return this._activeBones;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. // Stats
  22424. Scene.prototype.getInterFramePerfCounter = function () {
  22425. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22426. return 0;
  22427. };
  22428. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22429. get: function () {
  22430. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22431. return null;
  22432. },
  22433. enumerable: true,
  22434. configurable: true
  22435. });
  22436. Scene.prototype.getLastFrameDuration = function () {
  22437. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22438. return 0;
  22439. };
  22440. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22441. get: function () {
  22442. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22443. return null;
  22444. },
  22445. enumerable: true,
  22446. configurable: true
  22447. });
  22448. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22449. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22450. return 0;
  22451. };
  22452. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22453. get: function () {
  22454. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22455. return null;
  22456. },
  22457. enumerable: true,
  22458. configurable: true
  22459. });
  22460. Scene.prototype.getActiveMeshes = function () {
  22461. return this._activeMeshes;
  22462. };
  22463. Scene.prototype.getRenderTargetsDuration = function () {
  22464. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22465. return 0;
  22466. };
  22467. Scene.prototype.getRenderDuration = function () {
  22468. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22469. return 0;
  22470. };
  22471. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22472. get: function () {
  22473. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22474. return null;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. Scene.prototype.getParticlesDuration = function () {
  22480. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22481. return 0;
  22482. };
  22483. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22484. get: function () {
  22485. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22486. return null;
  22487. },
  22488. enumerable: true,
  22489. configurable: true
  22490. });
  22491. Scene.prototype.getSpritesDuration = function () {
  22492. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22493. return 0;
  22494. };
  22495. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22496. get: function () {
  22497. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22498. return null;
  22499. },
  22500. enumerable: true,
  22501. configurable: true
  22502. });
  22503. Scene.prototype.getAnimationRatio = function () {
  22504. return this._animationRatio;
  22505. };
  22506. Scene.prototype.getRenderId = function () {
  22507. return this._renderId;
  22508. };
  22509. Scene.prototype.incrementRenderId = function () {
  22510. this._renderId++;
  22511. };
  22512. Scene.prototype._updatePointerPosition = function (evt) {
  22513. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22514. if (!canvasRect) {
  22515. return;
  22516. }
  22517. this._pointerX = evt.clientX - canvasRect.left;
  22518. this._pointerY = evt.clientY - canvasRect.top;
  22519. this._unTranslatedPointerX = this._pointerX;
  22520. this._unTranslatedPointerY = this._pointerY;
  22521. };
  22522. Scene.prototype._createUbo = function () {
  22523. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22524. this._sceneUbo.addUniform("viewProjection", 16);
  22525. this._sceneUbo.addUniform("view", 16);
  22526. };
  22527. Scene.prototype._createAlternateUbo = function () {
  22528. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22529. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22530. this._alternateSceneUbo.addUniform("view", 16);
  22531. };
  22532. // Pointers handling
  22533. /**
  22534. * Use this method to simulate a pointer move on a mesh
  22535. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22536. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22537. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22538. */
  22539. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22540. var evt = new PointerEvent("pointermove", pointerEventInit);
  22541. return this._processPointerMove(pickResult, evt);
  22542. };
  22543. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22544. var canvas = this._engine.getRenderingCanvas();
  22545. if (!canvas) {
  22546. return this;
  22547. }
  22548. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22549. this.setPointerOverSprite(null);
  22550. this.setPointerOverMesh(pickResult.pickedMesh);
  22551. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22552. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22553. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22554. }
  22555. else {
  22556. canvas.style.cursor = this.hoverCursor;
  22557. }
  22558. }
  22559. else {
  22560. canvas.style.cursor = this.defaultCursor;
  22561. }
  22562. }
  22563. else {
  22564. this.setPointerOverMesh(null);
  22565. // Sprites
  22566. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22567. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22568. this.setPointerOverSprite(pickResult.pickedSprite);
  22569. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22570. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22571. }
  22572. else {
  22573. canvas.style.cursor = this.hoverCursor;
  22574. }
  22575. }
  22576. else {
  22577. this.setPointerOverSprite(null);
  22578. // Restore pointer
  22579. canvas.style.cursor = this.defaultCursor;
  22580. }
  22581. }
  22582. if (pickResult) {
  22583. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22584. if (this.onPointerMove) {
  22585. this.onPointerMove(evt, pickResult, type);
  22586. }
  22587. if (this.onPointerObservable.hasObservers()) {
  22588. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22589. this.onPointerObservable.notifyObservers(pi, type);
  22590. }
  22591. }
  22592. return this;
  22593. };
  22594. /**
  22595. * Use this method to simulate a pointer down on a mesh
  22596. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22597. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22598. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22599. */
  22600. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22601. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22602. return this._processPointerDown(pickResult, evt);
  22603. };
  22604. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22605. var _this = this;
  22606. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22607. this._pickedDownMesh = pickResult.pickedMesh;
  22608. var actionManager = pickResult.pickedMesh.actionManager;
  22609. if (actionManager) {
  22610. if (actionManager.hasPickTriggers) {
  22611. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22612. switch (evt.button) {
  22613. case 0:
  22614. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22615. break;
  22616. case 1:
  22617. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22618. break;
  22619. case 2:
  22620. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22621. break;
  22622. }
  22623. }
  22624. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22625. window.setTimeout(function () {
  22626. 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);
  22627. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22628. if (_this._totalPointersPressed !== 0 &&
  22629. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22630. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22631. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22632. _this._startingPointerTime = 0;
  22633. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22634. }
  22635. }
  22636. }, Scene.LongPressDelay);
  22637. }
  22638. }
  22639. }
  22640. if (pickResult) {
  22641. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22642. if (this.onPointerDown) {
  22643. this.onPointerDown(evt, pickResult, type);
  22644. }
  22645. if (this.onPointerObservable.hasObservers()) {
  22646. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22647. this.onPointerObservable.notifyObservers(pi, type);
  22648. }
  22649. }
  22650. return this;
  22651. };
  22652. /**
  22653. * Use this method to simulate a pointer up on a mesh
  22654. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22655. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22656. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22657. */
  22658. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22659. var evt = new PointerEvent("pointerup", pointerEventInit);
  22660. var clickInfo = new ClickInfo();
  22661. clickInfo.singleClick = true;
  22662. clickInfo.ignore = true;
  22663. return this._processPointerUp(pickResult, evt, clickInfo);
  22664. };
  22665. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22666. if (pickResult && pickResult && pickResult.pickedMesh) {
  22667. this._pickedUpMesh = pickResult.pickedMesh;
  22668. if (this._pickedDownMesh === this._pickedUpMesh) {
  22669. if (this.onPointerPick) {
  22670. this.onPointerPick(evt, pickResult);
  22671. }
  22672. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22673. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22674. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22675. this.onPointerObservable.notifyObservers(pi, type_1);
  22676. }
  22677. }
  22678. if (pickResult.pickedMesh.actionManager) {
  22679. if (clickInfo.ignore) {
  22680. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22681. }
  22682. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22683. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22684. }
  22685. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22686. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22687. }
  22688. }
  22689. }
  22690. if (this._pickedDownMesh &&
  22691. this._pickedDownMesh.actionManager &&
  22692. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22693. this._pickedDownMesh !== this._pickedUpMesh) {
  22694. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22695. }
  22696. var type = BABYLON.PointerEventTypes.POINTERUP;
  22697. if (this.onPointerObservable.hasObservers()) {
  22698. if (!clickInfo.ignore) {
  22699. if (!clickInfo.hasSwiped) {
  22700. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22701. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22702. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22703. this.onPointerObservable.notifyObservers(pi, type_2);
  22704. }
  22705. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22706. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22707. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22708. this.onPointerObservable.notifyObservers(pi, type_3);
  22709. }
  22710. }
  22711. }
  22712. else {
  22713. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22714. this.onPointerObservable.notifyObservers(pi, type);
  22715. }
  22716. }
  22717. if (this.onPointerUp) {
  22718. this.onPointerUp(evt, pickResult, type);
  22719. }
  22720. return this;
  22721. };
  22722. /**
  22723. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22724. * @param attachUp defines if you want to attach events to pointerup
  22725. * @param attachDown defines if you want to attach events to pointerdown
  22726. * @param attachMove defines if you want to attach events to pointermove
  22727. */
  22728. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22729. var _this = this;
  22730. if (attachUp === void 0) { attachUp = true; }
  22731. if (attachDown === void 0) { attachDown = true; }
  22732. if (attachMove === void 0) { attachMove = true; }
  22733. this._initActionManager = function (act, clickInfo) {
  22734. if (!_this._meshPickProceed) {
  22735. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22736. _this._currentPickResult = pickResult;
  22737. if (pickResult) {
  22738. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22739. }
  22740. _this._meshPickProceed = true;
  22741. }
  22742. return act;
  22743. };
  22744. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22745. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22746. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22747. btn !== _this._previousButtonPressed) {
  22748. _this._doubleClickOccured = false;
  22749. clickInfo.singleClick = true;
  22750. clickInfo.ignore = false;
  22751. cb(clickInfo, _this._currentPickResult);
  22752. }
  22753. };
  22754. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22755. var clickInfo = new ClickInfo();
  22756. _this._currentPickResult = null;
  22757. var act = null;
  22758. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22759. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22760. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22761. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22762. act = _this._initActionManager(act, clickInfo);
  22763. if (act)
  22764. checkPicking = act.hasPickTriggers;
  22765. }
  22766. if (checkPicking) {
  22767. var btn = evt.button;
  22768. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22769. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22770. if (!clickInfo.hasSwiped) {
  22771. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22772. if (!checkSingleClickImmediately) {
  22773. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22774. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22775. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22776. act = _this._initActionManager(act, clickInfo);
  22777. if (act)
  22778. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22779. }
  22780. }
  22781. if (checkSingleClickImmediately) {
  22782. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22783. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22784. btn !== _this._previousButtonPressed) {
  22785. clickInfo.singleClick = true;
  22786. cb(clickInfo, _this._currentPickResult);
  22787. }
  22788. }
  22789. else {
  22790. // wait that no double click has been raised during the double click delay
  22791. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22792. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22793. }
  22794. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22795. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22796. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22797. act = _this._initActionManager(act, clickInfo);
  22798. if (act)
  22799. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22800. }
  22801. if (checkDoubleClick) {
  22802. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22803. if (btn === _this._previousButtonPressed &&
  22804. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22805. !_this._doubleClickOccured) {
  22806. // pointer has not moved for 2 clicks, it's a double click
  22807. if (!clickInfo.hasSwiped &&
  22808. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22809. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22810. _this._previousStartingPointerTime = 0;
  22811. _this._doubleClickOccured = true;
  22812. clickInfo.doubleClick = true;
  22813. clickInfo.ignore = false;
  22814. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22815. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22816. }
  22817. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22818. cb(clickInfo, _this._currentPickResult);
  22819. }
  22820. else {
  22821. _this._doubleClickOccured = false;
  22822. _this._previousStartingPointerTime = _this._startingPointerTime;
  22823. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22824. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22825. _this._previousButtonPressed = btn;
  22826. if (Scene.ExclusiveDoubleClickMode) {
  22827. if (_this._previousDelayedSimpleClickTimeout) {
  22828. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22829. }
  22830. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22831. cb(clickInfo, _this._previousPickResult);
  22832. }
  22833. else {
  22834. cb(clickInfo, _this._currentPickResult);
  22835. }
  22836. }
  22837. }
  22838. else {
  22839. _this._doubleClickOccured = false;
  22840. _this._previousStartingPointerTime = _this._startingPointerTime;
  22841. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22842. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22843. _this._previousButtonPressed = btn;
  22844. }
  22845. }
  22846. }
  22847. }
  22848. clickInfo.ignore = true;
  22849. cb(clickInfo, _this._currentPickResult);
  22850. };
  22851. this._spritePredicate = function (sprite) {
  22852. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22853. };
  22854. this._onPointerMove = function (evt) {
  22855. _this._updatePointerPosition(evt);
  22856. // PreObservable support
  22857. if (_this.onPrePointerObservable.hasObservers()) {
  22858. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22859. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22860. _this.onPrePointerObservable.notifyObservers(pi, type);
  22861. if (pi.skipOnPointerObservable) {
  22862. return;
  22863. }
  22864. }
  22865. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22866. return;
  22867. }
  22868. if (!_this.pointerMovePredicate) {
  22869. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22870. }
  22871. // Meshes
  22872. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22873. _this._processPointerMove(pickResult, evt);
  22874. };
  22875. this._onPointerDown = function (evt) {
  22876. _this._totalPointersPressed++;
  22877. _this._pickedDownMesh = null;
  22878. _this._meshPickProceed = false;
  22879. _this._updatePointerPosition(evt);
  22880. if (_this.preventDefaultOnPointerDown && canvas) {
  22881. evt.preventDefault();
  22882. canvas.focus();
  22883. }
  22884. // PreObservable support
  22885. if (_this.onPrePointerObservable.hasObservers()) {
  22886. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22887. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22888. _this.onPrePointerObservable.notifyObservers(pi, type);
  22889. if (pi.skipOnPointerObservable) {
  22890. return;
  22891. }
  22892. }
  22893. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22894. return;
  22895. }
  22896. _this._startingPointerPosition.x = _this._pointerX;
  22897. _this._startingPointerPosition.y = _this._pointerY;
  22898. _this._startingPointerTime = new Date().getTime();
  22899. if (!_this.pointerDownPredicate) {
  22900. _this.pointerDownPredicate = function (mesh) {
  22901. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22902. };
  22903. }
  22904. // Meshes
  22905. _this._pickedDownMesh = null;
  22906. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22907. _this._processPointerDown(pickResult, evt);
  22908. // Sprites
  22909. _this._pickedDownSprite = null;
  22910. if (_this.spriteManagers.length > 0) {
  22911. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22912. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22913. if (pickResult.pickedSprite.actionManager) {
  22914. _this._pickedDownSprite = pickResult.pickedSprite;
  22915. switch (evt.button) {
  22916. case 0:
  22917. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22918. break;
  22919. case 1:
  22920. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22921. break;
  22922. case 2:
  22923. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22924. break;
  22925. }
  22926. if (pickResult.pickedSprite.actionManager) {
  22927. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22928. }
  22929. }
  22930. }
  22931. }
  22932. };
  22933. this._onPointerUp = function (evt) {
  22934. if (_this._totalPointersPressed === 0) {
  22935. return; // So we need to test it the pointer down was pressed before.
  22936. }
  22937. _this._totalPointersPressed--;
  22938. _this._pickedUpMesh = null;
  22939. _this._meshPickProceed = false;
  22940. _this._updatePointerPosition(evt);
  22941. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22942. // PreObservable support
  22943. if (_this.onPrePointerObservable.hasObservers()) {
  22944. if (!clickInfo.ignore) {
  22945. if (!clickInfo.hasSwiped) {
  22946. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22947. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22948. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22949. _this.onPrePointerObservable.notifyObservers(pi, type);
  22950. if (pi.skipOnPointerObservable) {
  22951. return;
  22952. }
  22953. }
  22954. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22955. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22956. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22957. _this.onPrePointerObservable.notifyObservers(pi, type);
  22958. if (pi.skipOnPointerObservable) {
  22959. return;
  22960. }
  22961. }
  22962. }
  22963. }
  22964. else {
  22965. var type = BABYLON.PointerEventTypes.POINTERUP;
  22966. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22967. _this.onPrePointerObservable.notifyObservers(pi, type);
  22968. if (pi.skipOnPointerObservable) {
  22969. return;
  22970. }
  22971. }
  22972. }
  22973. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22974. return;
  22975. }
  22976. if (!_this.pointerUpPredicate) {
  22977. _this.pointerUpPredicate = function (mesh) {
  22978. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22979. };
  22980. }
  22981. // Meshes
  22982. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22983. _this._initActionManager(null, clickInfo);
  22984. }
  22985. if (!pickResult) {
  22986. pickResult = _this._currentPickResult;
  22987. }
  22988. _this._processPointerUp(pickResult, evt, clickInfo);
  22989. // Sprites
  22990. if (_this.spriteManagers.length > 0) {
  22991. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22992. if (spritePickResult) {
  22993. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22994. if (spritePickResult.pickedSprite.actionManager) {
  22995. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22996. if (spritePickResult.pickedSprite.actionManager) {
  22997. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22998. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22999. }
  23000. }
  23001. }
  23002. }
  23003. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23004. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23005. }
  23006. }
  23007. }
  23008. _this._previousPickResult = _this._currentPickResult;
  23009. });
  23010. };
  23011. this._onKeyDown = function (evt) {
  23012. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23013. if (_this.onPreKeyboardObservable.hasObservers()) {
  23014. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23015. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23016. if (pi.skipOnPointerObservable) {
  23017. return;
  23018. }
  23019. }
  23020. if (_this.onKeyboardObservable.hasObservers()) {
  23021. var pi = new BABYLON.KeyboardInfo(type, evt);
  23022. _this.onKeyboardObservable.notifyObservers(pi, type);
  23023. }
  23024. if (_this.actionManager) {
  23025. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23026. }
  23027. };
  23028. this._onKeyUp = function (evt) {
  23029. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23030. if (_this.onPreKeyboardObservable.hasObservers()) {
  23031. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23032. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23033. if (pi.skipOnPointerObservable) {
  23034. return;
  23035. }
  23036. }
  23037. if (_this.onKeyboardObservable.hasObservers()) {
  23038. var pi = new BABYLON.KeyboardInfo(type, evt);
  23039. _this.onKeyboardObservable.notifyObservers(pi, type);
  23040. }
  23041. if (_this.actionManager) {
  23042. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23043. }
  23044. };
  23045. var engine = this.getEngine();
  23046. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23047. if (!canvas) {
  23048. return;
  23049. }
  23050. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23051. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23052. });
  23053. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23054. if (!canvas) {
  23055. return;
  23056. }
  23057. canvas.removeEventListener("keydown", _this._onKeyDown);
  23058. canvas.removeEventListener("keyup", _this._onKeyUp);
  23059. });
  23060. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23061. var canvas = this._engine.getRenderingCanvas();
  23062. if (!canvas) {
  23063. return;
  23064. }
  23065. if (attachMove) {
  23066. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23067. // Wheel
  23068. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23069. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23070. }
  23071. if (attachDown) {
  23072. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23073. }
  23074. if (attachUp) {
  23075. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23076. }
  23077. canvas.tabIndex = 1;
  23078. };
  23079. Scene.prototype.detachControl = function () {
  23080. var engine = this.getEngine();
  23081. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23082. var canvas = engine.getRenderingCanvas();
  23083. if (!canvas) {
  23084. return;
  23085. }
  23086. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23087. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23088. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23089. if (this._onCanvasBlurObserver) {
  23090. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23091. }
  23092. if (this._onCanvasFocusObserver) {
  23093. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23094. }
  23095. // Wheel
  23096. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23097. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23098. // Keyboard
  23099. canvas.removeEventListener("keydown", this._onKeyDown);
  23100. canvas.removeEventListener("keyup", this._onKeyUp);
  23101. // Observables
  23102. this.onKeyboardObservable.clear();
  23103. this.onPreKeyboardObservable.clear();
  23104. this.onPointerObservable.clear();
  23105. this.onPrePointerObservable.clear();
  23106. };
  23107. /**
  23108. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23109. * Delay loaded resources are not taking in account
  23110. * @return true if all required resources are ready
  23111. */
  23112. Scene.prototype.isReady = function () {
  23113. if (this._isDisposed) {
  23114. return false;
  23115. }
  23116. if (this._pendingData.length > 0) {
  23117. return false;
  23118. }
  23119. var index;
  23120. var engine = this.getEngine();
  23121. // Geometries
  23122. for (index = 0; index < this._geometries.length; index++) {
  23123. var geometry = this._geometries[index];
  23124. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23125. return false;
  23126. }
  23127. }
  23128. // Meshes
  23129. for (index = 0; index < this.meshes.length; index++) {
  23130. var mesh = this.meshes[index];
  23131. if (!mesh.isEnabled()) {
  23132. continue;
  23133. }
  23134. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23135. continue;
  23136. }
  23137. if (!mesh.isReady(true)) {
  23138. return false;
  23139. }
  23140. // Effect layers
  23141. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23142. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23143. var layer = _a[_i];
  23144. if (!layer.hasMesh(mesh)) {
  23145. continue;
  23146. }
  23147. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23148. var subMesh = _c[_b];
  23149. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23150. return false;
  23151. }
  23152. }
  23153. }
  23154. }
  23155. // Post-processes
  23156. if (this.activeCameras && this.activeCameras.length > 0) {
  23157. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  23158. var camera = _e[_d];
  23159. if (!camera.isReady(true)) {
  23160. return false;
  23161. }
  23162. }
  23163. }
  23164. else if (this.activeCamera) {
  23165. if (!this.activeCamera.isReady(true)) {
  23166. return false;
  23167. }
  23168. }
  23169. // Particles
  23170. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  23171. var particleSystem = _g[_f];
  23172. if (!particleSystem.isReady()) {
  23173. return false;
  23174. }
  23175. }
  23176. return true;
  23177. };
  23178. Scene.prototype.resetCachedMaterial = function () {
  23179. this._cachedMaterial = null;
  23180. this._cachedEffect = null;
  23181. this._cachedVisibility = null;
  23182. };
  23183. Scene.prototype.registerBeforeRender = function (func) {
  23184. this.onBeforeRenderObservable.add(func);
  23185. };
  23186. Scene.prototype.unregisterBeforeRender = function (func) {
  23187. this.onBeforeRenderObservable.removeCallback(func);
  23188. };
  23189. Scene.prototype.registerAfterRender = function (func) {
  23190. this.onAfterRenderObservable.add(func);
  23191. };
  23192. Scene.prototype.unregisterAfterRender = function (func) {
  23193. this.onAfterRenderObservable.removeCallback(func);
  23194. };
  23195. Scene.prototype._executeOnceBeforeRender = function (func) {
  23196. var _this = this;
  23197. var execFunc = function () {
  23198. func();
  23199. setTimeout(function () {
  23200. _this.unregisterBeforeRender(execFunc);
  23201. });
  23202. };
  23203. this.registerBeforeRender(execFunc);
  23204. };
  23205. /**
  23206. * The provided function will run before render once and will be disposed afterwards.
  23207. * A timeout delay can be provided so that the function will be executed in N ms.
  23208. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23209. * @param func The function to be executed.
  23210. * @param timeout optional delay in ms
  23211. */
  23212. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23213. var _this = this;
  23214. if (timeout !== undefined) {
  23215. setTimeout(function () {
  23216. _this._executeOnceBeforeRender(func);
  23217. }, timeout);
  23218. }
  23219. else {
  23220. this._executeOnceBeforeRender(func);
  23221. }
  23222. };
  23223. Scene.prototype._addPendingData = function (data) {
  23224. this._pendingData.push(data);
  23225. };
  23226. Scene.prototype._removePendingData = function (data) {
  23227. var wasLoading = this.isLoading;
  23228. var index = this._pendingData.indexOf(data);
  23229. if (index !== -1) {
  23230. this._pendingData.splice(index, 1);
  23231. }
  23232. if (wasLoading && !this.isLoading) {
  23233. this.onDataLoadedObservable.notifyObservers(this);
  23234. }
  23235. };
  23236. Scene.prototype.getWaitingItemsCount = function () {
  23237. return this._pendingData.length;
  23238. };
  23239. Object.defineProperty(Scene.prototype, "isLoading", {
  23240. get: function () {
  23241. return this._pendingData.length > 0;
  23242. },
  23243. enumerable: true,
  23244. configurable: true
  23245. });
  23246. /**
  23247. * Registers a function to be executed when the scene is ready.
  23248. * @param {Function} func - the function to be executed.
  23249. */
  23250. Scene.prototype.executeWhenReady = function (func) {
  23251. var _this = this;
  23252. this.onReadyObservable.add(func);
  23253. if (this._executeWhenReadyTimeoutId !== -1) {
  23254. return;
  23255. }
  23256. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23257. _this._checkIsReady();
  23258. }, 150);
  23259. };
  23260. /**
  23261. * Returns a promise that resolves when the scene is ready.
  23262. * @returns A promise that resolves when the scene is ready.
  23263. */
  23264. Scene.prototype.whenReadyAsync = function () {
  23265. var _this = this;
  23266. return new Promise(function (resolve) {
  23267. _this.executeWhenReady(function () {
  23268. resolve();
  23269. });
  23270. });
  23271. };
  23272. Scene.prototype._checkIsReady = function () {
  23273. var _this = this;
  23274. if (this.isReady()) {
  23275. this.onReadyObservable.notifyObservers(this);
  23276. this.onReadyObservable.clear();
  23277. this._executeWhenReadyTimeoutId = -1;
  23278. return;
  23279. }
  23280. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23281. _this._checkIsReady();
  23282. }, 150);
  23283. };
  23284. // Animations
  23285. /**
  23286. * Will start the animation sequence of a given target
  23287. * @param target defines the target
  23288. * @param from defines from which frame should animation start
  23289. * @param to defines until which frame should animation run.
  23290. * @param weight defines the weight to apply to the animation (1.0 by default)
  23291. * @param loop defines if the animation loops
  23292. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23293. * @param onAnimationEnd defines the function to be executed when the animation ends
  23294. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23295. * @returns the animatable object created for this animation
  23296. */
  23297. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23298. if (weight === void 0) { weight = 1.0; }
  23299. if (speedRatio === void 0) { speedRatio = 1.0; }
  23300. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23301. returnedAnimatable.weight = weight;
  23302. return returnedAnimatable;
  23303. };
  23304. /**
  23305. * Will start the animation sequence of a given target
  23306. * @param target defines the target
  23307. * @param from defines from which frame should animation start
  23308. * @param to defines until which frame should animation run.
  23309. * @param loop defines if the animation loops
  23310. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23311. * @param onAnimationEnd defines the function to be executed when the animation ends
  23312. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23313. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23314. * @returns the animatable object created for this animation
  23315. */
  23316. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23317. if (speedRatio === void 0) { speedRatio = 1.0; }
  23318. if (stopCurrent === void 0) { stopCurrent = true; }
  23319. if (from > to && speedRatio > 0) {
  23320. speedRatio *= -1;
  23321. }
  23322. if (stopCurrent) {
  23323. this.stopAnimation(target);
  23324. }
  23325. if (!animatable) {
  23326. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23327. }
  23328. // Local animations
  23329. if (target.animations) {
  23330. animatable.appendAnimations(target, target.animations);
  23331. }
  23332. // Children animations
  23333. if (target.getAnimatables) {
  23334. var animatables = target.getAnimatables();
  23335. for (var index = 0; index < animatables.length; index++) {
  23336. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23337. }
  23338. }
  23339. animatable.reset();
  23340. return animatable;
  23341. };
  23342. /**
  23343. * Begin a new animation on a given node
  23344. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23345. * @param {BABYLON.Animation[]} defines the list of animations to start
  23346. * @param {number} from defines the initial value
  23347. * @param {number} to defines the final value
  23348. * @param {boolean} loop defines if you want animation to loop (off by default)
  23349. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23350. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23351. * @returns the list of created animatables
  23352. */
  23353. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23354. if (speedRatio === undefined) {
  23355. speedRatio = 1.0;
  23356. }
  23357. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23358. return animatable;
  23359. };
  23360. /**
  23361. * Begin a new animation on a given node and its hierarchy
  23362. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23363. * @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.
  23364. * @param {BABYLON.Animation[]} defines the list of animations to start
  23365. * @param {number} from defines the initial value
  23366. * @param {number} to defines the final value
  23367. * @param {boolean} loop defines if you want animation to loop (off by default)
  23368. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23369. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23370. * @returns the list of animatables created for all nodes
  23371. */
  23372. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23373. var children = target.getDescendants(directDescendantsOnly);
  23374. var result = [];
  23375. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23376. var child = children_1[_i];
  23377. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23378. }
  23379. return result;
  23380. };
  23381. Scene.prototype.getAnimatableByTarget = function (target) {
  23382. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23383. if (this._activeAnimatables[index].target === target) {
  23384. return this._activeAnimatables[index];
  23385. }
  23386. }
  23387. return null;
  23388. };
  23389. /**
  23390. * Gets all animatables associated with a given target
  23391. * @param target defines the target to look animatables for
  23392. * @returns an array of Animatables
  23393. */
  23394. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23395. var result = [];
  23396. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23397. if (this._activeAnimatables[index].target === target) {
  23398. result.push(this._activeAnimatables[index]);
  23399. }
  23400. }
  23401. return result;
  23402. };
  23403. Object.defineProperty(Scene.prototype, "animatables", {
  23404. get: function () {
  23405. return this._activeAnimatables;
  23406. },
  23407. enumerable: true,
  23408. configurable: true
  23409. });
  23410. /**
  23411. * Will stop the animation of the given target
  23412. * @param target - the target
  23413. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23414. */
  23415. Scene.prototype.stopAnimation = function (target, animationName) {
  23416. var animatables = this.getAllAnimatablesByTarget(target);
  23417. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23418. var animatable = animatables_1[_i];
  23419. animatable.stop(animationName);
  23420. }
  23421. };
  23422. /**
  23423. * Stops and removes all animations that have been applied to the scene
  23424. */
  23425. Scene.prototype.stopAllAnimations = function () {
  23426. if (this._activeAnimatables) {
  23427. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23428. this._activeAnimatables[i].stop();
  23429. }
  23430. this._activeAnimatables = [];
  23431. }
  23432. };
  23433. Scene.prototype._animate = function () {
  23434. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23435. return;
  23436. }
  23437. // Getting time
  23438. var now = BABYLON.Tools.Now;
  23439. if (!this._animationTimeLast) {
  23440. if (this._pendingData.length > 0) {
  23441. return;
  23442. }
  23443. this._animationTimeLast = now;
  23444. }
  23445. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23446. this._animationTime += deltaTime;
  23447. this._animationTimeLast = now;
  23448. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23449. this._activeAnimatables[index]._animate(this._animationTime);
  23450. }
  23451. // Late animation bindings
  23452. this._processLateAnimationBindings();
  23453. };
  23454. /** @ignore */
  23455. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23456. var target = runtimeAnimation.target;
  23457. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23458. if (!target._lateAnimationHolders) {
  23459. target._lateAnimationHolders = {};
  23460. }
  23461. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23462. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23463. totalWeight: 0,
  23464. animations: []
  23465. };
  23466. }
  23467. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23468. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23469. };
  23470. Scene.prototype._processLateAnimationBindings = function () {
  23471. if (!this._registeredForLateAnimationBindings.length) {
  23472. return;
  23473. }
  23474. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23475. var target = this._registeredForLateAnimationBindings.data[index];
  23476. for (var path in target._lateAnimationHolders) {
  23477. var holder = target._lateAnimationHolders[path];
  23478. // Sanity check
  23479. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23480. continue;
  23481. }
  23482. var normalizer = 1.0;
  23483. var finalValue = void 0;
  23484. if (holder.totalWeight < 1.0) {
  23485. // We need to mix the original value in
  23486. var originalValue = holder.animations[0].originalValue;
  23487. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23488. }
  23489. else {
  23490. // We need to normalize the weights
  23491. normalizer = holder.totalWeight;
  23492. }
  23493. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23494. var runtimeAnimation = holder.animations[animIndex];
  23495. if (finalValue) {
  23496. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23497. }
  23498. else {
  23499. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23500. }
  23501. }
  23502. runtimeAnimation.target[path] = finalValue;
  23503. }
  23504. target._lateAnimationHolders = {};
  23505. }
  23506. this._registeredForLateAnimationBindings.reset();
  23507. };
  23508. // Matrix
  23509. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23510. this._useAlternateCameraConfiguration = active;
  23511. };
  23512. Scene.prototype.getViewMatrix = function () {
  23513. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23514. };
  23515. Scene.prototype.getProjectionMatrix = function () {
  23516. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23517. };
  23518. Scene.prototype.getTransformMatrix = function () {
  23519. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23520. };
  23521. Scene.prototype.setTransformMatrix = function (view, projection) {
  23522. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23523. return;
  23524. }
  23525. this._viewUpdateFlag = view.updateFlag;
  23526. this._projectionUpdateFlag = projection.updateFlag;
  23527. this._viewMatrix = view;
  23528. this._projectionMatrix = projection;
  23529. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23530. // Update frustum
  23531. if (!this._frustumPlanes) {
  23532. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23533. }
  23534. else {
  23535. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23536. }
  23537. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23538. var otherCamera = this.activeCamera._alternateCamera;
  23539. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23540. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23541. }
  23542. if (this._sceneUbo.useUbo) {
  23543. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23544. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23545. this._sceneUbo.update();
  23546. }
  23547. };
  23548. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23549. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23550. return;
  23551. }
  23552. this._alternateViewUpdateFlag = view.updateFlag;
  23553. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23554. this._alternateViewMatrix = view;
  23555. this._alternateProjectionMatrix = projection;
  23556. if (!this._alternateTransformMatrix) {
  23557. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23558. }
  23559. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23560. if (!this._alternateSceneUbo) {
  23561. this._createAlternateUbo();
  23562. }
  23563. if (this._alternateSceneUbo.useUbo) {
  23564. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23565. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23566. this._alternateSceneUbo.update();
  23567. }
  23568. };
  23569. Scene.prototype.getSceneUniformBuffer = function () {
  23570. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23571. };
  23572. // Methods
  23573. Scene.prototype.getUniqueId = function () {
  23574. var result = Scene._uniqueIdCounter;
  23575. Scene._uniqueIdCounter++;
  23576. return result;
  23577. };
  23578. Scene.prototype.addMesh = function (newMesh) {
  23579. this.meshes.push(newMesh);
  23580. //notify the collision coordinator
  23581. if (this.collisionCoordinator) {
  23582. this.collisionCoordinator.onMeshAdded(newMesh);
  23583. }
  23584. newMesh._resyncLightSources();
  23585. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23586. };
  23587. Scene.prototype.removeMesh = function (toRemove) {
  23588. var index = this.meshes.indexOf(toRemove);
  23589. if (index !== -1) {
  23590. // Remove from the scene if mesh found
  23591. this.meshes.splice(index, 1);
  23592. }
  23593. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23594. return index;
  23595. };
  23596. Scene.prototype.addTransformNode = function (newTransformNode) {
  23597. this.transformNodes.push(newTransformNode);
  23598. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23599. };
  23600. Scene.prototype.removeTransformNode = function (toRemove) {
  23601. var index = this.transformNodes.indexOf(toRemove);
  23602. if (index !== -1) {
  23603. // Remove from the scene if found
  23604. this.transformNodes.splice(index, 1);
  23605. }
  23606. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23607. return index;
  23608. };
  23609. Scene.prototype.removeSkeleton = function (toRemove) {
  23610. var index = this.skeletons.indexOf(toRemove);
  23611. if (index !== -1) {
  23612. // Remove from the scene if found
  23613. this.skeletons.splice(index, 1);
  23614. }
  23615. return index;
  23616. };
  23617. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23618. var index = this.morphTargetManagers.indexOf(toRemove);
  23619. if (index !== -1) {
  23620. // Remove from the scene if found
  23621. this.morphTargetManagers.splice(index, 1);
  23622. }
  23623. return index;
  23624. };
  23625. Scene.prototype.removeLight = function (toRemove) {
  23626. var index = this.lights.indexOf(toRemove);
  23627. if (index !== -1) {
  23628. // Remove from meshes
  23629. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23630. var mesh = _a[_i];
  23631. mesh._removeLightSource(toRemove);
  23632. }
  23633. // Remove from the scene if mesh found
  23634. this.lights.splice(index, 1);
  23635. this.sortLightsByPriority();
  23636. }
  23637. this.onLightRemovedObservable.notifyObservers(toRemove);
  23638. return index;
  23639. };
  23640. Scene.prototype.removeCamera = function (toRemove) {
  23641. var index = this.cameras.indexOf(toRemove);
  23642. if (index !== -1) {
  23643. // Remove from the scene if mesh found
  23644. this.cameras.splice(index, 1);
  23645. }
  23646. // Remove from activeCameras
  23647. var index2 = this.activeCameras.indexOf(toRemove);
  23648. if (index2 !== -1) {
  23649. // Remove from the scene if mesh found
  23650. this.activeCameras.splice(index2, 1);
  23651. }
  23652. // Reset the activeCamera
  23653. if (this.activeCamera === toRemove) {
  23654. if (this.cameras.length > 0) {
  23655. this.activeCamera = this.cameras[0];
  23656. }
  23657. else {
  23658. this.activeCamera = null;
  23659. }
  23660. }
  23661. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23662. return index;
  23663. };
  23664. Scene.prototype.removeParticleSystem = function (toRemove) {
  23665. var index = this.particleSystems.indexOf(toRemove);
  23666. if (index !== -1) {
  23667. this.particleSystems.splice(index, 1);
  23668. }
  23669. return index;
  23670. };
  23671. Scene.prototype.removeAnimation = function (toRemove) {
  23672. var index = this.animations.indexOf(toRemove);
  23673. if (index !== -1) {
  23674. this.animations.splice(index, 1);
  23675. }
  23676. return index;
  23677. };
  23678. /**
  23679. * Removes the given animation group from this scene.
  23680. * @param toRemove The animation group to remove
  23681. * @returns The index of the removed animation group
  23682. */
  23683. Scene.prototype.removeAnimationGroup = function (toRemove) {
  23684. var index = this.animationGroups.indexOf(toRemove);
  23685. if (index !== -1) {
  23686. this.animationGroups.splice(index, 1);
  23687. }
  23688. return index;
  23689. };
  23690. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23691. var index = this.multiMaterials.indexOf(toRemove);
  23692. if (index !== -1) {
  23693. this.multiMaterials.splice(index, 1);
  23694. }
  23695. return index;
  23696. };
  23697. Scene.prototype.removeMaterial = function (toRemove) {
  23698. var index = this.materials.indexOf(toRemove);
  23699. if (index !== -1) {
  23700. this.materials.splice(index, 1);
  23701. }
  23702. return index;
  23703. };
  23704. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23705. var index = this.lensFlareSystems.indexOf(toRemove);
  23706. if (index !== -1) {
  23707. this.lensFlareSystems.splice(index, 1);
  23708. }
  23709. return index;
  23710. };
  23711. Scene.prototype.removeActionManager = function (toRemove) {
  23712. var index = this._actionManagers.indexOf(toRemove);
  23713. if (index !== -1) {
  23714. this._actionManagers.splice(index, 1);
  23715. }
  23716. return index;
  23717. };
  23718. /**
  23719. * Removes the given texture from this scene.
  23720. * @param toRemove The texture to remove
  23721. * @returns The index of the removed texture
  23722. */
  23723. Scene.prototype.removeTexture = function (toRemove) {
  23724. var index = this.textures.indexOf(toRemove);
  23725. if (index !== -1) {
  23726. this.textures.splice(index, 1);
  23727. }
  23728. return index;
  23729. };
  23730. Scene.prototype.addLight = function (newLight) {
  23731. this.lights.push(newLight);
  23732. this.sortLightsByPriority();
  23733. // Add light to all meshes (To support if the light is removed and then readded)
  23734. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23735. var mesh = _a[_i];
  23736. if (mesh._lightSources.indexOf(newLight) === -1) {
  23737. mesh._lightSources.push(newLight);
  23738. mesh._resyncLightSources();
  23739. }
  23740. }
  23741. this.onNewLightAddedObservable.notifyObservers(newLight);
  23742. };
  23743. Scene.prototype.sortLightsByPriority = function () {
  23744. if (this.requireLightSorting) {
  23745. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23746. }
  23747. };
  23748. Scene.prototype.addCamera = function (newCamera) {
  23749. this.cameras.push(newCamera);
  23750. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23751. };
  23752. Scene.prototype.addSkeleton = function (newSkeleton) {
  23753. this.skeletons.push(newSkeleton);
  23754. };
  23755. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23756. this.particleSystems.push(newParticleSystem);
  23757. };
  23758. Scene.prototype.addAnimation = function (newAnimation) {
  23759. this.animations.push(newAnimation);
  23760. };
  23761. /**
  23762. * Adds the given animation group to this scene.
  23763. * @param newAnimationGroup The animation group to add
  23764. */
  23765. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  23766. this.animationGroups.push(newAnimationGroup);
  23767. };
  23768. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23769. this.multiMaterials.push(newMultiMaterial);
  23770. };
  23771. Scene.prototype.addMaterial = function (newMaterial) {
  23772. this.materials.push(newMaterial);
  23773. };
  23774. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23775. this.morphTargetManagers.push(newMorphTargetManager);
  23776. };
  23777. Scene.prototype.addGeometry = function (newGeometrie) {
  23778. this._geometries.push(newGeometrie);
  23779. };
  23780. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23781. this.lensFlareSystems.push(newLensFlareSystem);
  23782. };
  23783. Scene.prototype.addActionManager = function (newActionManager) {
  23784. this._actionManagers.push(newActionManager);
  23785. };
  23786. /**
  23787. * Adds the given texture to this scene.
  23788. * @param newTexture The texture to add
  23789. */
  23790. Scene.prototype.addTexture = function (newTexture) {
  23791. this.textures.push(newTexture);
  23792. };
  23793. /**
  23794. * Switch active camera
  23795. * @param {Camera} newCamera - new active camera
  23796. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23797. */
  23798. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23799. if (attachControl === void 0) { attachControl = true; }
  23800. var canvas = this._engine.getRenderingCanvas();
  23801. if (!canvas) {
  23802. return;
  23803. }
  23804. if (this.activeCamera) {
  23805. this.activeCamera.detachControl(canvas);
  23806. }
  23807. this.activeCamera = newCamera;
  23808. if (attachControl) {
  23809. newCamera.attachControl(canvas);
  23810. }
  23811. };
  23812. /**
  23813. * sets the active camera of the scene using its ID
  23814. * @param {string} id - the camera's ID
  23815. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23816. */
  23817. Scene.prototype.setActiveCameraByID = function (id) {
  23818. var camera = this.getCameraByID(id);
  23819. if (camera) {
  23820. this.activeCamera = camera;
  23821. return camera;
  23822. }
  23823. return null;
  23824. };
  23825. /**
  23826. * sets the active camera of the scene using its name
  23827. * @param {string} name - the camera's name
  23828. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23829. */
  23830. Scene.prototype.setActiveCameraByName = function (name) {
  23831. var camera = this.getCameraByName(name);
  23832. if (camera) {
  23833. this.activeCamera = camera;
  23834. return camera;
  23835. }
  23836. return null;
  23837. };
  23838. /**
  23839. * get an animation group using its name
  23840. * @param {string} the material's name
  23841. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23842. */
  23843. Scene.prototype.getAnimationGroupByName = function (name) {
  23844. for (var index = 0; index < this.animationGroups.length; index++) {
  23845. if (this.animationGroups[index].name === name) {
  23846. return this.animationGroups[index];
  23847. }
  23848. }
  23849. return null;
  23850. };
  23851. /**
  23852. * get a material using its id
  23853. * @param {string} the material's ID
  23854. * @return {BABYLON.Material|null} the material or null if none found.
  23855. */
  23856. Scene.prototype.getMaterialByID = function (id) {
  23857. for (var index = 0; index < this.materials.length; index++) {
  23858. if (this.materials[index].id === id) {
  23859. return this.materials[index];
  23860. }
  23861. }
  23862. return null;
  23863. };
  23864. /**
  23865. * get a material using its name
  23866. * @param {string} the material's name
  23867. * @return {BABYLON.Material|null} the material or null if none found.
  23868. */
  23869. Scene.prototype.getMaterialByName = function (name) {
  23870. for (var index = 0; index < this.materials.length; index++) {
  23871. if (this.materials[index].name === name) {
  23872. return this.materials[index];
  23873. }
  23874. }
  23875. return null;
  23876. };
  23877. Scene.prototype.getLensFlareSystemByName = function (name) {
  23878. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23879. if (this.lensFlareSystems[index].name === name) {
  23880. return this.lensFlareSystems[index];
  23881. }
  23882. }
  23883. return null;
  23884. };
  23885. Scene.prototype.getLensFlareSystemByID = function (id) {
  23886. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23887. if (this.lensFlareSystems[index].id === id) {
  23888. return this.lensFlareSystems[index];
  23889. }
  23890. }
  23891. return null;
  23892. };
  23893. Scene.prototype.getCameraByID = function (id) {
  23894. for (var index = 0; index < this.cameras.length; index++) {
  23895. if (this.cameras[index].id === id) {
  23896. return this.cameras[index];
  23897. }
  23898. }
  23899. return null;
  23900. };
  23901. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23902. for (var index = 0; index < this.cameras.length; index++) {
  23903. if (this.cameras[index].uniqueId === uniqueId) {
  23904. return this.cameras[index];
  23905. }
  23906. }
  23907. return null;
  23908. };
  23909. /**
  23910. * get a camera using its name
  23911. * @param {string} the camera's name
  23912. * @return {BABYLON.Camera|null} the camera or null if none found.
  23913. */
  23914. Scene.prototype.getCameraByName = function (name) {
  23915. for (var index = 0; index < this.cameras.length; index++) {
  23916. if (this.cameras[index].name === name) {
  23917. return this.cameras[index];
  23918. }
  23919. }
  23920. return null;
  23921. };
  23922. /**
  23923. * get a bone using its id
  23924. * @param {string} the bone's id
  23925. * @return {BABYLON.Bone|null} the bone or null if not found
  23926. */
  23927. Scene.prototype.getBoneByID = function (id) {
  23928. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23929. var skeleton = this.skeletons[skeletonIndex];
  23930. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23931. if (skeleton.bones[boneIndex].id === id) {
  23932. return skeleton.bones[boneIndex];
  23933. }
  23934. }
  23935. }
  23936. return null;
  23937. };
  23938. /**
  23939. * get a bone using its id
  23940. * @param {string} the bone's name
  23941. * @return {BABYLON.Bone|null} the bone or null if not found
  23942. */
  23943. Scene.prototype.getBoneByName = function (name) {
  23944. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23945. var skeleton = this.skeletons[skeletonIndex];
  23946. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23947. if (skeleton.bones[boneIndex].name === name) {
  23948. return skeleton.bones[boneIndex];
  23949. }
  23950. }
  23951. }
  23952. return null;
  23953. };
  23954. /**
  23955. * get a light node using its name
  23956. * @param {string} the light's name
  23957. * @return {BABYLON.Light|null} the light or null if none found.
  23958. */
  23959. Scene.prototype.getLightByName = function (name) {
  23960. for (var index = 0; index < this.lights.length; index++) {
  23961. if (this.lights[index].name === name) {
  23962. return this.lights[index];
  23963. }
  23964. }
  23965. return null;
  23966. };
  23967. /**
  23968. * get a light node using its ID
  23969. * @param {string} the light's id
  23970. * @return {BABYLON.Light|null} the light or null if none found.
  23971. */
  23972. Scene.prototype.getLightByID = function (id) {
  23973. for (var index = 0; index < this.lights.length; index++) {
  23974. if (this.lights[index].id === id) {
  23975. return this.lights[index];
  23976. }
  23977. }
  23978. return null;
  23979. };
  23980. /**
  23981. * get a light node using its scene-generated unique ID
  23982. * @param {number} the light's unique id
  23983. * @return {BABYLON.Light|null} the light or null if none found.
  23984. */
  23985. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23986. for (var index = 0; index < this.lights.length; index++) {
  23987. if (this.lights[index].uniqueId === uniqueId) {
  23988. return this.lights[index];
  23989. }
  23990. }
  23991. return null;
  23992. };
  23993. /**
  23994. * get a particle system by id
  23995. * @param id {number} the particle system id
  23996. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23997. */
  23998. Scene.prototype.getParticleSystemByID = function (id) {
  23999. for (var index = 0; index < this.particleSystems.length; index++) {
  24000. if (this.particleSystems[index].id === id) {
  24001. return this.particleSystems[index];
  24002. }
  24003. }
  24004. return null;
  24005. };
  24006. /**
  24007. * get a geometry using its ID
  24008. * @param {string} the geometry's id
  24009. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24010. */
  24011. Scene.prototype.getGeometryByID = function (id) {
  24012. for (var index = 0; index < this._geometries.length; index++) {
  24013. if (this._geometries[index].id === id) {
  24014. return this._geometries[index];
  24015. }
  24016. }
  24017. return null;
  24018. };
  24019. /**
  24020. * add a new geometry to this scene.
  24021. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24022. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24023. * @return {boolean} was the geometry added or not
  24024. */
  24025. Scene.prototype.pushGeometry = function (geometry, force) {
  24026. if (!force && this.getGeometryByID(geometry.id)) {
  24027. return false;
  24028. }
  24029. this._geometries.push(geometry);
  24030. //notify the collision coordinator
  24031. if (this.collisionCoordinator) {
  24032. this.collisionCoordinator.onGeometryAdded(geometry);
  24033. }
  24034. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24035. return true;
  24036. };
  24037. /**
  24038. * Removes an existing geometry
  24039. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24040. * @return {boolean} was the geometry removed or not
  24041. */
  24042. Scene.prototype.removeGeometry = function (geometry) {
  24043. var index = this._geometries.indexOf(geometry);
  24044. if (index > -1) {
  24045. this._geometries.splice(index, 1);
  24046. //notify the collision coordinator
  24047. if (this.collisionCoordinator) {
  24048. this.collisionCoordinator.onGeometryDeleted(geometry);
  24049. }
  24050. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24051. return true;
  24052. }
  24053. return false;
  24054. };
  24055. Scene.prototype.getGeometries = function () {
  24056. return this._geometries;
  24057. };
  24058. /**
  24059. * Get the first added mesh found of a given ID
  24060. * @param {string} id - the id to search for
  24061. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24062. */
  24063. Scene.prototype.getMeshByID = function (id) {
  24064. for (var index = 0; index < this.meshes.length; index++) {
  24065. if (this.meshes[index].id === id) {
  24066. return this.meshes[index];
  24067. }
  24068. }
  24069. return null;
  24070. };
  24071. Scene.prototype.getMeshesByID = function (id) {
  24072. return this.meshes.filter(function (m) {
  24073. return m.id === id;
  24074. });
  24075. };
  24076. /**
  24077. * Get the first added transform node found of a given ID
  24078. * @param {string} id - the id to search for
  24079. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24080. */
  24081. Scene.prototype.getTransformNodeByID = function (id) {
  24082. for (var index = 0; index < this.transformNodes.length; index++) {
  24083. if (this.transformNodes[index].id === id) {
  24084. return this.transformNodes[index];
  24085. }
  24086. }
  24087. return null;
  24088. };
  24089. Scene.prototype.getTransformNodesByID = function (id) {
  24090. return this.transformNodes.filter(function (m) {
  24091. return m.id === id;
  24092. });
  24093. };
  24094. /**
  24095. * Get a mesh with its auto-generated unique id
  24096. * @param {number} uniqueId - the unique id to search for
  24097. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24098. */
  24099. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24100. for (var index = 0; index < this.meshes.length; index++) {
  24101. if (this.meshes[index].uniqueId === uniqueId) {
  24102. return this.meshes[index];
  24103. }
  24104. }
  24105. return null;
  24106. };
  24107. /**
  24108. * Get a the last added mesh found of a given ID
  24109. * @param {string} id - the id to search for
  24110. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24111. */
  24112. Scene.prototype.getLastMeshByID = function (id) {
  24113. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24114. if (this.meshes[index].id === id) {
  24115. return this.meshes[index];
  24116. }
  24117. }
  24118. return null;
  24119. };
  24120. /**
  24121. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24122. * @param {string} id - the id to search for
  24123. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24124. */
  24125. Scene.prototype.getLastEntryByID = function (id) {
  24126. var index;
  24127. for (index = this.meshes.length - 1; index >= 0; index--) {
  24128. if (this.meshes[index].id === id) {
  24129. return this.meshes[index];
  24130. }
  24131. }
  24132. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24133. if (this.transformNodes[index].id === id) {
  24134. return this.transformNodes[index];
  24135. }
  24136. }
  24137. for (index = this.cameras.length - 1; index >= 0; index--) {
  24138. if (this.cameras[index].id === id) {
  24139. return this.cameras[index];
  24140. }
  24141. }
  24142. for (index = this.lights.length - 1; index >= 0; index--) {
  24143. if (this.lights[index].id === id) {
  24144. return this.lights[index];
  24145. }
  24146. }
  24147. return null;
  24148. };
  24149. Scene.prototype.getNodeByID = function (id) {
  24150. var mesh = this.getMeshByID(id);
  24151. if (mesh) {
  24152. return mesh;
  24153. }
  24154. var light = this.getLightByID(id);
  24155. if (light) {
  24156. return light;
  24157. }
  24158. var camera = this.getCameraByID(id);
  24159. if (camera) {
  24160. return camera;
  24161. }
  24162. var bone = this.getBoneByID(id);
  24163. return bone;
  24164. };
  24165. Scene.prototype.getNodeByName = function (name) {
  24166. var mesh = this.getMeshByName(name);
  24167. if (mesh) {
  24168. return mesh;
  24169. }
  24170. var light = this.getLightByName(name);
  24171. if (light) {
  24172. return light;
  24173. }
  24174. var camera = this.getCameraByName(name);
  24175. if (camera) {
  24176. return camera;
  24177. }
  24178. var bone = this.getBoneByName(name);
  24179. return bone;
  24180. };
  24181. Scene.prototype.getMeshByName = function (name) {
  24182. for (var index = 0; index < this.meshes.length; index++) {
  24183. if (this.meshes[index].name === name) {
  24184. return this.meshes[index];
  24185. }
  24186. }
  24187. return null;
  24188. };
  24189. Scene.prototype.getTransformNodeByName = function (name) {
  24190. for (var index = 0; index < this.transformNodes.length; index++) {
  24191. if (this.transformNodes[index].name === name) {
  24192. return this.transformNodes[index];
  24193. }
  24194. }
  24195. return null;
  24196. };
  24197. Scene.prototype.getSoundByName = function (name) {
  24198. var index;
  24199. if (BABYLON.AudioEngine) {
  24200. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24201. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24202. return this.mainSoundTrack.soundCollection[index];
  24203. }
  24204. }
  24205. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24206. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24207. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24208. return this.soundTracks[sdIndex].soundCollection[index];
  24209. }
  24210. }
  24211. }
  24212. }
  24213. return null;
  24214. };
  24215. Scene.prototype.getLastSkeletonByID = function (id) {
  24216. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24217. if (this.skeletons[index].id === id) {
  24218. return this.skeletons[index];
  24219. }
  24220. }
  24221. return null;
  24222. };
  24223. Scene.prototype.getSkeletonById = function (id) {
  24224. for (var index = 0; index < this.skeletons.length; index++) {
  24225. if (this.skeletons[index].id === id) {
  24226. return this.skeletons[index];
  24227. }
  24228. }
  24229. return null;
  24230. };
  24231. Scene.prototype.getSkeletonByName = function (name) {
  24232. for (var index = 0; index < this.skeletons.length; index++) {
  24233. if (this.skeletons[index].name === name) {
  24234. return this.skeletons[index];
  24235. }
  24236. }
  24237. return null;
  24238. };
  24239. Scene.prototype.getMorphTargetManagerById = function (id) {
  24240. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24241. if (this.morphTargetManagers[index].uniqueId === id) {
  24242. return this.morphTargetManagers[index];
  24243. }
  24244. }
  24245. return null;
  24246. };
  24247. Scene.prototype.isActiveMesh = function (mesh) {
  24248. return (this._activeMeshes.indexOf(mesh) !== -1);
  24249. };
  24250. /**
  24251. * Return a the first highlight layer of the scene with a given name.
  24252. * @param name The name of the highlight layer to look for.
  24253. * @return The highlight layer if found otherwise null.
  24254. */
  24255. Scene.prototype.getHighlightLayerByName = function (name) {
  24256. for (var index = 0; index < this.effectLayers.length; index++) {
  24257. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24258. return this.effectLayers[index];
  24259. }
  24260. }
  24261. return null;
  24262. };
  24263. /**
  24264. * Return a the first highlight layer of the scene with a given name.
  24265. * @param name The name of the highlight layer to look for.
  24266. * @return The highlight layer if found otherwise null.
  24267. */
  24268. Scene.prototype.getGlowLayerByName = function (name) {
  24269. for (var index = 0; index < this.effectLayers.length; index++) {
  24270. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24271. return this.effectLayers[index];
  24272. }
  24273. }
  24274. return null;
  24275. };
  24276. Object.defineProperty(Scene.prototype, "uid", {
  24277. /**
  24278. * Return a unique id as a string which can serve as an identifier for the scene
  24279. */
  24280. get: function () {
  24281. if (!this._uid) {
  24282. this._uid = BABYLON.Tools.RandomId();
  24283. }
  24284. return this._uid;
  24285. },
  24286. enumerable: true,
  24287. configurable: true
  24288. });
  24289. /**
  24290. * Add an externaly attached data from its key.
  24291. * This method call will fail and return false, if such key already exists.
  24292. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24293. * @param key the unique key that identifies the data
  24294. * @param data the data object to associate to the key for this Engine instance
  24295. * @return true if no such key were already present and the data was added successfully, false otherwise
  24296. */
  24297. Scene.prototype.addExternalData = function (key, data) {
  24298. if (!this._externalData) {
  24299. this._externalData = new BABYLON.StringDictionary();
  24300. }
  24301. return this._externalData.add(key, data);
  24302. };
  24303. /**
  24304. * Get an externaly attached data from its key
  24305. * @param key the unique key that identifies the data
  24306. * @return the associated data, if present (can be null), or undefined if not present
  24307. */
  24308. Scene.prototype.getExternalData = function (key) {
  24309. if (!this._externalData) {
  24310. return null;
  24311. }
  24312. return this._externalData.get(key);
  24313. };
  24314. /**
  24315. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24316. * @param key the unique key that identifies the data
  24317. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24318. * @return the associated data, can be null if the factory returned null.
  24319. */
  24320. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24321. if (!this._externalData) {
  24322. this._externalData = new BABYLON.StringDictionary();
  24323. }
  24324. return this._externalData.getOrAddWithFactory(key, factory);
  24325. };
  24326. /**
  24327. * Remove an externaly attached data from the Engine instance
  24328. * @param key the unique key that identifies the data
  24329. * @return true if the data was successfully removed, false if it doesn't exist
  24330. */
  24331. Scene.prototype.removeExternalData = function (key) {
  24332. return this._externalData.remove(key);
  24333. };
  24334. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24335. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24336. if (mesh.showSubMeshesBoundingBox) {
  24337. var boundingInfo = subMesh.getBoundingInfo();
  24338. if (boundingInfo !== null && boundingInfo !== undefined) {
  24339. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24340. }
  24341. }
  24342. var material = subMesh.getMaterial();
  24343. if (material !== null && material !== undefined) {
  24344. // Render targets
  24345. if (material.getRenderTargetTextures !== undefined) {
  24346. if (this._processedMaterials.indexOf(material) === -1) {
  24347. this._processedMaterials.push(material);
  24348. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24349. }
  24350. }
  24351. // Dispatch
  24352. this._activeIndices.addCount(subMesh.indexCount, false);
  24353. this._renderingManager.dispatch(subMesh, mesh, material);
  24354. }
  24355. }
  24356. };
  24357. /**
  24358. * Clear the processed materials smart array preventing retention point in material dispose.
  24359. */
  24360. Scene.prototype.freeProcessedMaterials = function () {
  24361. this._processedMaterials.dispose();
  24362. };
  24363. /**
  24364. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24365. */
  24366. Scene.prototype.freeActiveMeshes = function () {
  24367. this._activeMeshes.dispose();
  24368. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24369. this.activeCamera._activeMeshes.dispose();
  24370. }
  24371. if (this.activeCameras) {
  24372. for (var i = 0; i < this.activeCameras.length; i++) {
  24373. var activeCamera = this.activeCameras[i];
  24374. if (activeCamera && activeCamera._activeMeshes) {
  24375. activeCamera._activeMeshes.dispose();
  24376. }
  24377. }
  24378. }
  24379. };
  24380. /**
  24381. * Clear the info related to rendering groups preventing retention points during dispose.
  24382. */
  24383. Scene.prototype.freeRenderingGroups = function () {
  24384. if (this._renderingManager) {
  24385. this._renderingManager.freeRenderingGroups();
  24386. }
  24387. if (this.textures) {
  24388. for (var i = 0; i < this.textures.length; i++) {
  24389. var texture = this.textures[i];
  24390. if (texture && texture.renderList) {
  24391. texture.freeRenderingGroups();
  24392. }
  24393. }
  24394. }
  24395. };
  24396. Scene.prototype._isInIntermediateRendering = function () {
  24397. return this._intermediateRendering;
  24398. };
  24399. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24400. this._activeMeshCandidateProvider = provider;
  24401. };
  24402. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24403. return this._activeMeshCandidateProvider;
  24404. };
  24405. /**
  24406. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24407. */
  24408. Scene.prototype.freezeActiveMeshes = function () {
  24409. if (!this.activeCamera) {
  24410. return this;
  24411. }
  24412. if (!this._frustumPlanes) {
  24413. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24414. }
  24415. this._evaluateActiveMeshes();
  24416. this._activeMeshesFrozen = true;
  24417. return this;
  24418. };
  24419. /**
  24420. * Use this function to restart evaluating active meshes on every frame
  24421. */
  24422. Scene.prototype.unfreezeActiveMeshes = function () {
  24423. this._activeMeshesFrozen = false;
  24424. return this;
  24425. };
  24426. Scene.prototype._evaluateActiveMeshes = function () {
  24427. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24428. return;
  24429. }
  24430. if (!this.activeCamera) {
  24431. return;
  24432. }
  24433. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24434. this.activeCamera._activeMeshes.reset();
  24435. this._activeMeshes.reset();
  24436. this._renderingManager.reset();
  24437. this._processedMaterials.reset();
  24438. this._activeParticleSystems.reset();
  24439. this._activeSkeletons.reset();
  24440. this._softwareSkinnedMeshes.reset();
  24441. if (this._boundingBoxRenderer) {
  24442. this._boundingBoxRenderer.reset();
  24443. }
  24444. // Meshes
  24445. var meshes;
  24446. var len;
  24447. var checkIsEnabled = true;
  24448. // Determine mesh candidates
  24449. if (this._activeMeshCandidateProvider !== undefined) {
  24450. // Use _activeMeshCandidateProvider
  24451. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24452. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24453. if (meshes !== undefined) {
  24454. len = meshes.length;
  24455. }
  24456. else {
  24457. len = 0;
  24458. }
  24459. }
  24460. else if (this._selectionOctree !== undefined) {
  24461. // Octree
  24462. var selection = this._selectionOctree.select(this._frustumPlanes);
  24463. meshes = selection.data;
  24464. len = selection.length;
  24465. }
  24466. else {
  24467. // Full scene traversal
  24468. len = this.meshes.length;
  24469. meshes = this.meshes;
  24470. }
  24471. // Check each mesh
  24472. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24473. mesh = meshes[meshIndex];
  24474. if (mesh.isBlocked) {
  24475. continue;
  24476. }
  24477. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24478. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24479. continue;
  24480. }
  24481. mesh.computeWorldMatrix();
  24482. // Intersections
  24483. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24484. this._meshesForIntersections.pushNoDuplicate(mesh);
  24485. }
  24486. // Switch to current LOD
  24487. meshLOD = mesh.getLOD(this.activeCamera);
  24488. if (meshLOD === undefined || meshLOD === null) {
  24489. continue;
  24490. }
  24491. mesh._preActivate();
  24492. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24493. this._activeMeshes.push(mesh);
  24494. this.activeCamera._activeMeshes.push(mesh);
  24495. mesh._activate(this._renderId);
  24496. if (meshLOD !== mesh) {
  24497. meshLOD._activate(this._renderId);
  24498. }
  24499. this._activeMesh(mesh, meshLOD);
  24500. }
  24501. }
  24502. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24503. // Particle systems
  24504. if (this.particlesEnabled) {
  24505. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24506. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24507. var particleSystem = this.particleSystems[particleIndex];
  24508. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24509. continue;
  24510. }
  24511. var emitter = particleSystem.emitter;
  24512. if (!emitter.position || emitter.isEnabled()) {
  24513. this._activeParticleSystems.push(particleSystem);
  24514. particleSystem.animate();
  24515. this._renderingManager.dispatchParticles(particleSystem);
  24516. }
  24517. }
  24518. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24519. }
  24520. };
  24521. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24522. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24523. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24524. mesh.skeleton.prepare();
  24525. }
  24526. if (!mesh.computeBonesUsingShaders) {
  24527. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24528. }
  24529. }
  24530. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24531. var boundingInfo = sourceMesh.getBoundingInfo();
  24532. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24533. }
  24534. if (mesh !== undefined && mesh !== null
  24535. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24536. // Submeshes Octrees
  24537. var len;
  24538. var subMeshes;
  24539. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24540. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24541. len = intersections.length;
  24542. subMeshes = intersections.data;
  24543. }
  24544. else {
  24545. subMeshes = mesh.subMeshes;
  24546. len = subMeshes.length;
  24547. }
  24548. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24549. subMesh = subMeshes[subIndex];
  24550. this._evaluateSubMesh(subMesh, mesh);
  24551. }
  24552. }
  24553. };
  24554. Scene.prototype.updateTransformMatrix = function (force) {
  24555. if (!this.activeCamera) {
  24556. return;
  24557. }
  24558. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24559. };
  24560. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24561. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24562. };
  24563. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24564. if (camera && camera._skipRendering) {
  24565. return;
  24566. }
  24567. var engine = this._engine;
  24568. this.activeCamera = camera;
  24569. if (!this.activeCamera)
  24570. throw new Error("Active camera not set");
  24571. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24572. // Viewport
  24573. engine.setViewport(this.activeCamera.viewport);
  24574. // Camera
  24575. this.resetCachedMaterial();
  24576. this._renderId++;
  24577. this.updateTransformMatrix();
  24578. if (camera._alternateCamera) {
  24579. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24580. this._alternateRendering = true;
  24581. }
  24582. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24583. // Meshes
  24584. this._evaluateActiveMeshes();
  24585. // Software skinning
  24586. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24587. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24588. mesh.applySkeleton(mesh.skeleton);
  24589. }
  24590. // Render targets
  24591. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24592. var needsRestoreFrameBuffer = false;
  24593. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24594. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24595. }
  24596. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24597. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24598. }
  24599. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24600. this._intermediateRendering = true;
  24601. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24602. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24603. var renderTarget = this._renderTargets.data[renderIndex];
  24604. if (renderTarget._shouldRender()) {
  24605. this._renderId++;
  24606. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24607. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24608. }
  24609. }
  24610. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24611. this._intermediateRendering = false;
  24612. this._renderId++;
  24613. needsRestoreFrameBuffer = true; // Restore back buffer
  24614. }
  24615. // Render EffecttLayer Texture
  24616. var stencilState = this._engine.getStencilBuffer();
  24617. var renderEffects = false;
  24618. var needStencil = false;
  24619. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24620. this._intermediateRendering = true;
  24621. for (var i = 0; i < this.effectLayers.length; i++) {
  24622. var effectLayer = this.effectLayers[i];
  24623. if (effectLayer.shouldRender() &&
  24624. (!effectLayer.camera ||
  24625. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24626. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24627. renderEffects = true;
  24628. needStencil = needStencil || effectLayer.needStencil();
  24629. var renderTarget = effectLayer._mainTexture;
  24630. if (renderTarget._shouldRender()) {
  24631. this._renderId++;
  24632. renderTarget.render(false, false);
  24633. needsRestoreFrameBuffer = true;
  24634. }
  24635. }
  24636. }
  24637. this._intermediateRendering = false;
  24638. this._renderId++;
  24639. }
  24640. if (needsRestoreFrameBuffer) {
  24641. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24642. }
  24643. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24644. // Prepare Frame
  24645. this.postProcessManager._prepareFrame();
  24646. // Backgrounds
  24647. var layerIndex;
  24648. var layer;
  24649. if (this.layers.length) {
  24650. engine.setDepthBuffer(false);
  24651. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24652. layer = this.layers[layerIndex];
  24653. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24654. layer.render();
  24655. }
  24656. }
  24657. engine.setDepthBuffer(true);
  24658. }
  24659. // Activate effect Layer stencil
  24660. if (needStencil) {
  24661. this._engine.setStencilBuffer(true);
  24662. }
  24663. // Render
  24664. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24665. this._renderingManager.render(null, null, true, true);
  24666. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24667. // Restore effect Layer stencil
  24668. if (needStencil) {
  24669. this._engine.setStencilBuffer(stencilState);
  24670. }
  24671. // Bounding boxes
  24672. if (this._boundingBoxRenderer) {
  24673. this._boundingBoxRenderer.render();
  24674. }
  24675. // Lens flares
  24676. if (this.lensFlaresEnabled) {
  24677. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24678. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24679. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24680. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24681. lensFlareSystem.render();
  24682. }
  24683. }
  24684. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24685. }
  24686. // Foregrounds
  24687. if (this.layers.length) {
  24688. engine.setDepthBuffer(false);
  24689. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24690. layer = this.layers[layerIndex];
  24691. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24692. layer.render();
  24693. }
  24694. }
  24695. engine.setDepthBuffer(true);
  24696. }
  24697. // Effect Layer
  24698. if (renderEffects) {
  24699. engine.setDepthBuffer(false);
  24700. for (var i = 0; i < this.effectLayers.length; i++) {
  24701. if (this.effectLayers[i].shouldRender()) {
  24702. this.effectLayers[i].render();
  24703. }
  24704. }
  24705. engine.setDepthBuffer(true);
  24706. }
  24707. // Finalize frame
  24708. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24709. // Reset some special arrays
  24710. this._renderTargets.reset();
  24711. this._alternateRendering = false;
  24712. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24713. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24714. };
  24715. Scene.prototype._processSubCameras = function (camera) {
  24716. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24717. this._renderForCamera(camera);
  24718. return;
  24719. }
  24720. // rig cameras
  24721. for (var index = 0; index < camera._rigCameras.length; index++) {
  24722. this._renderForCamera(camera._rigCameras[index], camera);
  24723. }
  24724. this.activeCamera = camera;
  24725. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24726. };
  24727. Scene.prototype._checkIntersections = function () {
  24728. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24729. var sourceMesh = this._meshesForIntersections.data[index];
  24730. if (!sourceMesh.actionManager) {
  24731. continue;
  24732. }
  24733. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24734. var action = sourceMesh.actionManager.actions[actionIndex];
  24735. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24736. var parameters = action.getTriggerParameter();
  24737. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24738. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24739. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24740. if (areIntersecting && currentIntersectionInProgress === -1) {
  24741. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24742. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24743. sourceMesh._intersectionsInProgress.push(otherMesh);
  24744. }
  24745. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24746. sourceMesh._intersectionsInProgress.push(otherMesh);
  24747. }
  24748. }
  24749. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24750. //They intersected, and now they don't.
  24751. //is this trigger an exit trigger? execute an event.
  24752. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24753. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24754. }
  24755. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24756. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24757. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24758. }
  24759. }
  24760. }
  24761. }
  24762. }
  24763. };
  24764. Scene.prototype.render = function () {
  24765. if (this.isDisposed) {
  24766. return;
  24767. }
  24768. this._activeParticles.fetchNewFrame();
  24769. this._totalVertices.fetchNewFrame();
  24770. this._activeIndices.fetchNewFrame();
  24771. this._activeBones.fetchNewFrame();
  24772. this._meshesForIntersections.reset();
  24773. this.resetCachedMaterial();
  24774. this.onBeforeAnimationsObservable.notifyObservers(this);
  24775. // Actions
  24776. if (this.actionManager) {
  24777. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24778. }
  24779. //Simplification Queue
  24780. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24781. this.simplificationQueue.executeNext();
  24782. }
  24783. if (this._engine.isDeterministicLockStep()) {
  24784. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24785. var defaultFPS = (60.0 / 1000.0);
  24786. var defaultFrameTime = 1000 / 60; // frame time in MS
  24787. if (this._physicsEngine) {
  24788. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24789. }
  24790. var stepsTaken = 0;
  24791. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24792. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24793. internalSteps = Math.min(internalSteps, maxSubSteps);
  24794. do {
  24795. this.onBeforeStepObservable.notifyObservers(this);
  24796. // Animations
  24797. this._animationRatio = defaultFrameTime * defaultFPS;
  24798. this._animate();
  24799. this.onAfterAnimationsObservable.notifyObservers(this);
  24800. // Physics
  24801. if (this._physicsEngine) {
  24802. this.onBeforePhysicsObservable.notifyObservers(this);
  24803. this._physicsEngine._step(defaultFrameTime / 1000);
  24804. this.onAfterPhysicsObservable.notifyObservers(this);
  24805. }
  24806. this.onAfterStepObservable.notifyObservers(this);
  24807. this._currentStepId++;
  24808. stepsTaken++;
  24809. deltaTime -= defaultFrameTime;
  24810. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24811. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24812. }
  24813. else {
  24814. // Animations
  24815. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24816. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24817. this._animate();
  24818. this.onAfterAnimationsObservable.notifyObservers(this);
  24819. // Physics
  24820. if (this._physicsEngine) {
  24821. this.onBeforePhysicsObservable.notifyObservers(this);
  24822. this._physicsEngine._step(deltaTime / 1000.0);
  24823. this.onAfterPhysicsObservable.notifyObservers(this);
  24824. }
  24825. }
  24826. // update gamepad manager
  24827. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24828. this._gamepadManager._checkGamepadsStatus();
  24829. }
  24830. // Update Cameras
  24831. if (this.activeCameras.length > 0) {
  24832. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24833. var camera = this.activeCameras[cameraIndex];
  24834. camera.update();
  24835. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24836. // rig cameras
  24837. for (var index = 0; index < camera._rigCameras.length; index++) {
  24838. camera._rigCameras[index].update();
  24839. }
  24840. }
  24841. }
  24842. }
  24843. else if (this.activeCamera) {
  24844. this.activeCamera.update();
  24845. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24846. // rig cameras
  24847. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24848. this.activeCamera._rigCameras[index].update();
  24849. }
  24850. }
  24851. }
  24852. // Before render
  24853. this.onBeforeRenderObservable.notifyObservers(this);
  24854. // Customs render targets
  24855. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24856. var engine = this.getEngine();
  24857. var currentActiveCamera = this.activeCamera;
  24858. if (this.renderTargetsEnabled) {
  24859. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24860. this._intermediateRendering = true;
  24861. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24862. var renderTarget = this.customRenderTargets[customIndex];
  24863. if (renderTarget._shouldRender()) {
  24864. this._renderId++;
  24865. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24866. if (!this.activeCamera)
  24867. throw new Error("Active camera not set");
  24868. // Viewport
  24869. engine.setViewport(this.activeCamera.viewport);
  24870. // Camera
  24871. this.updateTransformMatrix();
  24872. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24873. }
  24874. }
  24875. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24876. this._intermediateRendering = false;
  24877. this._renderId++;
  24878. }
  24879. // Restore back buffer
  24880. if (this.customRenderTargets.length > 0) {
  24881. engine.restoreDefaultFramebuffer();
  24882. }
  24883. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24884. this.activeCamera = currentActiveCamera;
  24885. // Procedural textures
  24886. if (this.proceduralTexturesEnabled) {
  24887. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24888. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24889. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24890. if (proceduralTexture._shouldRender()) {
  24891. proceduralTexture.render();
  24892. }
  24893. }
  24894. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24895. }
  24896. // Clear
  24897. if (this.autoClearDepthAndStencil || this.autoClear) {
  24898. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24899. }
  24900. // Shadows
  24901. if (this.shadowsEnabled) {
  24902. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24903. var light = this.lights[lightIndex];
  24904. var shadowGenerator = light.getShadowGenerator();
  24905. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24906. var shadowMap = (shadowGenerator.getShadowMap());
  24907. if (this.textures.indexOf(shadowMap) !== -1) {
  24908. this._renderTargets.push(shadowMap);
  24909. }
  24910. }
  24911. }
  24912. }
  24913. // Depth renderer
  24914. for (var key in this._depthRenderer) {
  24915. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24916. }
  24917. // Geometry renderer
  24918. if (this._geometryBufferRenderer) {
  24919. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24920. }
  24921. // RenderPipeline
  24922. if (this._postProcessRenderPipelineManager) {
  24923. this._postProcessRenderPipelineManager.update();
  24924. }
  24925. // Multi-cameras?
  24926. if (this.activeCameras.length > 0) {
  24927. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24928. if (cameraIndex > 0) {
  24929. this._engine.clear(null, false, true, true);
  24930. }
  24931. this._processSubCameras(this.activeCameras[cameraIndex]);
  24932. }
  24933. }
  24934. else {
  24935. if (!this.activeCamera) {
  24936. throw new Error("No camera defined");
  24937. }
  24938. this._processSubCameras(this.activeCamera);
  24939. }
  24940. // Intersection checks
  24941. this._checkIntersections();
  24942. // Update the audio listener attached to the camera
  24943. if (BABYLON.AudioEngine) {
  24944. this._updateAudioParameters();
  24945. }
  24946. // After render
  24947. if (this.afterRender) {
  24948. this.afterRender();
  24949. }
  24950. this.onAfterRenderObservable.notifyObservers(this);
  24951. // Cleaning
  24952. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24953. var data = this._toBeDisposed.data[index];
  24954. if (data) {
  24955. data.dispose();
  24956. }
  24957. this._toBeDisposed[index] = null;
  24958. }
  24959. this._toBeDisposed.reset();
  24960. if (this.dumpNextRenderTargets) {
  24961. this.dumpNextRenderTargets = false;
  24962. }
  24963. this._activeBones.addCount(0, true);
  24964. this._activeIndices.addCount(0, true);
  24965. this._activeParticles.addCount(0, true);
  24966. };
  24967. Scene.prototype._updateAudioParameters = function () {
  24968. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24969. return;
  24970. }
  24971. var listeningCamera;
  24972. var audioEngine = BABYLON.Engine.audioEngine;
  24973. if (this.activeCameras.length > 0) {
  24974. listeningCamera = this.activeCameras[0];
  24975. }
  24976. else {
  24977. listeningCamera = this.activeCamera;
  24978. }
  24979. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24980. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24981. // for VR cameras
  24982. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24983. listeningCamera = listeningCamera.rigCameras[0];
  24984. }
  24985. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24986. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24987. cameraDirection.normalize();
  24988. // To avoid some errors on GearVR
  24989. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24990. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24991. }
  24992. var i;
  24993. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24994. var sound = this.mainSoundTrack.soundCollection[i];
  24995. if (sound.useCustomAttenuation) {
  24996. sound.updateDistanceFromListener();
  24997. }
  24998. }
  24999. for (i = 0; i < this.soundTracks.length; i++) {
  25000. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25001. sound = this.soundTracks[i].soundCollection[j];
  25002. if (sound.useCustomAttenuation) {
  25003. sound.updateDistanceFromListener();
  25004. }
  25005. }
  25006. }
  25007. }
  25008. };
  25009. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25010. // Audio
  25011. get: function () {
  25012. return this._audioEnabled;
  25013. },
  25014. set: function (value) {
  25015. this._audioEnabled = value;
  25016. if (BABYLON.AudioEngine) {
  25017. if (this._audioEnabled) {
  25018. this._enableAudio();
  25019. }
  25020. else {
  25021. this._disableAudio();
  25022. }
  25023. }
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. Scene.prototype._disableAudio = function () {
  25029. var i;
  25030. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25031. this.mainSoundTrack.soundCollection[i].pause();
  25032. }
  25033. for (i = 0; i < this.soundTracks.length; i++) {
  25034. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25035. this.soundTracks[i].soundCollection[j].pause();
  25036. }
  25037. }
  25038. };
  25039. Scene.prototype._enableAudio = function () {
  25040. var i;
  25041. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25042. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25043. this.mainSoundTrack.soundCollection[i].play();
  25044. }
  25045. }
  25046. for (i = 0; i < this.soundTracks.length; i++) {
  25047. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25048. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25049. this.soundTracks[i].soundCollection[j].play();
  25050. }
  25051. }
  25052. }
  25053. };
  25054. Object.defineProperty(Scene.prototype, "headphone", {
  25055. get: function () {
  25056. return this._headphone;
  25057. },
  25058. set: function (value) {
  25059. this._headphone = value;
  25060. if (BABYLON.AudioEngine) {
  25061. if (this._headphone) {
  25062. this._switchAudioModeForHeadphones();
  25063. }
  25064. else {
  25065. this._switchAudioModeForNormalSpeakers();
  25066. }
  25067. }
  25068. },
  25069. enumerable: true,
  25070. configurable: true
  25071. });
  25072. Scene.prototype._switchAudioModeForHeadphones = function () {
  25073. this.mainSoundTrack.switchPanningModelToHRTF();
  25074. for (var i = 0; i < this.soundTracks.length; i++) {
  25075. this.soundTracks[i].switchPanningModelToHRTF();
  25076. }
  25077. };
  25078. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25079. this.mainSoundTrack.switchPanningModelToEqualPower();
  25080. for (var i = 0; i < this.soundTracks.length; i++) {
  25081. this.soundTracks[i].switchPanningModelToEqualPower();
  25082. }
  25083. };
  25084. /**
  25085. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25086. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25087. * @returns the created depth renderer
  25088. */
  25089. Scene.prototype.enableDepthRenderer = function (camera) {
  25090. camera = camera || this.activeCamera;
  25091. if (!camera) {
  25092. throw "No camera available to enable depth renderer";
  25093. }
  25094. if (!this._depthRenderer[camera.id]) {
  25095. var textureType = 0;
  25096. if (this._engine.getCaps().textureHalfFloatRender) {
  25097. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  25098. }
  25099. else if (this._engine.getCaps().textureFloatRender) {
  25100. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  25101. }
  25102. else {
  25103. throw "Depth renderer does not support int texture type";
  25104. }
  25105. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  25106. }
  25107. return this._depthRenderer[camera.id];
  25108. };
  25109. /**
  25110. * Disables a depth renderer for a given camera
  25111. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25112. */
  25113. Scene.prototype.disableDepthRenderer = function (camera) {
  25114. camera = camera || this.activeCamera;
  25115. if (!camera || !this._depthRenderer[camera.id]) {
  25116. return;
  25117. }
  25118. this._depthRenderer[camera.id].dispose();
  25119. delete this._depthRenderer[camera.id];
  25120. };
  25121. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25122. if (ratio === void 0) { ratio = 1; }
  25123. if (this._geometryBufferRenderer) {
  25124. return this._geometryBufferRenderer;
  25125. }
  25126. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25127. if (!this._geometryBufferRenderer.isSupported) {
  25128. this._geometryBufferRenderer = null;
  25129. }
  25130. return this._geometryBufferRenderer;
  25131. };
  25132. Scene.prototype.disableGeometryBufferRenderer = function () {
  25133. if (!this._geometryBufferRenderer) {
  25134. return;
  25135. }
  25136. this._geometryBufferRenderer.dispose();
  25137. this._geometryBufferRenderer = null;
  25138. };
  25139. Scene.prototype.freezeMaterials = function () {
  25140. for (var i = 0; i < this.materials.length; i++) {
  25141. this.materials[i].freeze();
  25142. }
  25143. };
  25144. Scene.prototype.unfreezeMaterials = function () {
  25145. for (var i = 0; i < this.materials.length; i++) {
  25146. this.materials[i].unfreeze();
  25147. }
  25148. };
  25149. Scene.prototype.dispose = function () {
  25150. this.beforeRender = null;
  25151. this.afterRender = null;
  25152. this.skeletons = [];
  25153. this.morphTargetManagers = [];
  25154. this.importedMeshesFiles = new Array();
  25155. this.stopAllAnimations();
  25156. this.resetCachedMaterial();
  25157. for (var key in this._depthRenderer) {
  25158. this._depthRenderer[key].dispose();
  25159. }
  25160. if (this._gamepadManager) {
  25161. this._gamepadManager.dispose();
  25162. this._gamepadManager = null;
  25163. }
  25164. // Smart arrays
  25165. if (this.activeCamera) {
  25166. this.activeCamera._activeMeshes.dispose();
  25167. this.activeCamera = null;
  25168. }
  25169. this._activeMeshes.dispose();
  25170. this._renderingManager.dispose();
  25171. this._processedMaterials.dispose();
  25172. this._activeParticleSystems.dispose();
  25173. this._activeSkeletons.dispose();
  25174. this._softwareSkinnedMeshes.dispose();
  25175. this._renderTargets.dispose();
  25176. this._registeredForLateAnimationBindings.dispose();
  25177. if (this._boundingBoxRenderer) {
  25178. this._boundingBoxRenderer.dispose();
  25179. }
  25180. this._meshesForIntersections.dispose();
  25181. this._toBeDisposed.dispose();
  25182. // Abort active requests
  25183. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25184. var request = _a[_i];
  25185. request.abort();
  25186. }
  25187. // Debug layer
  25188. if (this._debugLayer) {
  25189. this._debugLayer.hide();
  25190. }
  25191. // Events
  25192. this.onDisposeObservable.notifyObservers(this);
  25193. this.onDisposeObservable.clear();
  25194. this.onBeforeRenderObservable.clear();
  25195. this.onAfterRenderObservable.clear();
  25196. this.OnBeforeRenderTargetsRenderObservable.clear();
  25197. this.OnAfterRenderTargetsRenderObservable.clear();
  25198. this.onAfterStepObservable.clear();
  25199. this.onBeforeStepObservable.clear();
  25200. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25201. this.onAfterActiveMeshesEvaluationObservable.clear();
  25202. this.onBeforeParticlesRenderingObservable.clear();
  25203. this.onAfterParticlesRenderingObservable.clear();
  25204. this.onBeforeSpritesRenderingObservable.clear();
  25205. this.onAfterSpritesRenderingObservable.clear();
  25206. this.onBeforeDrawPhaseObservable.clear();
  25207. this.onAfterDrawPhaseObservable.clear();
  25208. this.onBeforePhysicsObservable.clear();
  25209. this.onAfterPhysicsObservable.clear();
  25210. this.onBeforeAnimationsObservable.clear();
  25211. this.onAfterAnimationsObservable.clear();
  25212. this.onDataLoadedObservable.clear();
  25213. this.detachControl();
  25214. // Release sounds & sounds tracks
  25215. if (BABYLON.AudioEngine) {
  25216. this.disposeSounds();
  25217. }
  25218. // VR Helper
  25219. if (this.VRHelper) {
  25220. this.VRHelper.dispose();
  25221. }
  25222. // Detach cameras
  25223. var canvas = this._engine.getRenderingCanvas();
  25224. if (canvas) {
  25225. var index;
  25226. for (index = 0; index < this.cameras.length; index++) {
  25227. this.cameras[index].detachControl(canvas);
  25228. }
  25229. }
  25230. // Release animation groups
  25231. while (this.animationGroups.length) {
  25232. this.animationGroups[0].dispose();
  25233. }
  25234. // Release lights
  25235. while (this.lights.length) {
  25236. this.lights[0].dispose();
  25237. }
  25238. // Release meshes
  25239. while (this.meshes.length) {
  25240. this.meshes[0].dispose(true);
  25241. }
  25242. while (this.transformNodes.length) {
  25243. this.removeTransformNode(this.transformNodes[0]);
  25244. }
  25245. // Release cameras
  25246. while (this.cameras.length) {
  25247. this.cameras[0].dispose();
  25248. }
  25249. // Release materials
  25250. if (this.defaultMaterial) {
  25251. this.defaultMaterial.dispose();
  25252. }
  25253. while (this.multiMaterials.length) {
  25254. this.multiMaterials[0].dispose();
  25255. }
  25256. while (this.materials.length) {
  25257. this.materials[0].dispose();
  25258. }
  25259. // Release particles
  25260. while (this.particleSystems.length) {
  25261. this.particleSystems[0].dispose();
  25262. }
  25263. // Release sprites
  25264. while (this.spriteManagers.length) {
  25265. this.spriteManagers[0].dispose();
  25266. }
  25267. // Release postProcesses
  25268. while (this.postProcesses.length) {
  25269. this.postProcesses[0].dispose();
  25270. }
  25271. // Release layers
  25272. while (this.layers.length) {
  25273. this.layers[0].dispose();
  25274. }
  25275. while (this.effectLayers.length) {
  25276. this.effectLayers[0].dispose();
  25277. }
  25278. // Release textures
  25279. while (this.textures.length) {
  25280. this.textures[0].dispose();
  25281. }
  25282. // Release UBO
  25283. this._sceneUbo.dispose();
  25284. if (this._alternateSceneUbo) {
  25285. this._alternateSceneUbo.dispose();
  25286. }
  25287. // Post-processes
  25288. this.postProcessManager.dispose();
  25289. if (this._postProcessRenderPipelineManager) {
  25290. this._postProcessRenderPipelineManager.dispose();
  25291. }
  25292. // Physics
  25293. if (this._physicsEngine) {
  25294. this.disablePhysicsEngine();
  25295. }
  25296. // Remove from engine
  25297. index = this._engine.scenes.indexOf(this);
  25298. if (index > -1) {
  25299. this._engine.scenes.splice(index, 1);
  25300. }
  25301. this._engine.wipeCaches(true);
  25302. this._isDisposed = true;
  25303. };
  25304. Object.defineProperty(Scene.prototype, "isDisposed", {
  25305. get: function () {
  25306. return this._isDisposed;
  25307. },
  25308. enumerable: true,
  25309. configurable: true
  25310. });
  25311. // Release sounds & sounds tracks
  25312. Scene.prototype.disposeSounds = function () {
  25313. if (!this._mainSoundTrack) {
  25314. return;
  25315. }
  25316. this.mainSoundTrack.dispose();
  25317. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25318. this.soundTracks[scIndex].dispose();
  25319. }
  25320. };
  25321. // Octrees
  25322. /**
  25323. * Get the world extend vectors with an optional filter
  25324. *
  25325. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25326. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25327. */
  25328. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25329. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25330. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25331. filterPredicate = filterPredicate || (function () { return true; });
  25332. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25333. mesh.computeWorldMatrix(true);
  25334. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25335. return;
  25336. }
  25337. var boundingInfo = mesh.getBoundingInfo();
  25338. var minBox = boundingInfo.boundingBox.minimumWorld;
  25339. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25340. BABYLON.Tools.CheckExtends(minBox, min, max);
  25341. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25342. });
  25343. return {
  25344. min: min,
  25345. max: max
  25346. };
  25347. };
  25348. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25349. if (maxCapacity === void 0) { maxCapacity = 64; }
  25350. if (maxDepth === void 0) { maxDepth = 2; }
  25351. if (!this._selectionOctree) {
  25352. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25353. }
  25354. var worldExtends = this.getWorldExtends();
  25355. // Update octree
  25356. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25357. return this._selectionOctree;
  25358. };
  25359. // Picking
  25360. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25361. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25362. var result = BABYLON.Ray.Zero();
  25363. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25364. return result;
  25365. };
  25366. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25367. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25368. var engine = this._engine;
  25369. if (!camera) {
  25370. if (!this.activeCamera)
  25371. throw new Error("Active camera not set");
  25372. camera = this.activeCamera;
  25373. }
  25374. var cameraViewport = camera.viewport;
  25375. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25376. // Moving coordinates to local viewport world
  25377. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25378. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25379. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25380. return this;
  25381. };
  25382. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25383. var result = BABYLON.Ray.Zero();
  25384. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25385. return result;
  25386. };
  25387. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25388. if (!BABYLON.PickingInfo) {
  25389. return this;
  25390. }
  25391. var engine = this._engine;
  25392. if (!camera) {
  25393. if (!this.activeCamera)
  25394. throw new Error("Active camera not set");
  25395. camera = this.activeCamera;
  25396. }
  25397. var cameraViewport = camera.viewport;
  25398. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25399. var identity = BABYLON.Matrix.Identity();
  25400. // Moving coordinates to local viewport world
  25401. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25402. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25403. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25404. return this;
  25405. };
  25406. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25407. if (!BABYLON.PickingInfo) {
  25408. return null;
  25409. }
  25410. var pickingInfo = null;
  25411. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25412. var mesh = this.meshes[meshIndex];
  25413. if (predicate) {
  25414. if (!predicate(mesh)) {
  25415. continue;
  25416. }
  25417. }
  25418. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25419. continue;
  25420. }
  25421. var world = mesh.getWorldMatrix();
  25422. var ray = rayFunction(world);
  25423. var result = mesh.intersects(ray, fastCheck);
  25424. if (!result || !result.hit)
  25425. continue;
  25426. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25427. continue;
  25428. pickingInfo = result;
  25429. if (fastCheck) {
  25430. break;
  25431. }
  25432. }
  25433. return pickingInfo || new BABYLON.PickingInfo();
  25434. };
  25435. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25436. if (!BABYLON.PickingInfo) {
  25437. return null;
  25438. }
  25439. var pickingInfos = new Array();
  25440. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25441. var mesh = this.meshes[meshIndex];
  25442. if (predicate) {
  25443. if (!predicate(mesh)) {
  25444. continue;
  25445. }
  25446. }
  25447. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25448. continue;
  25449. }
  25450. var world = mesh.getWorldMatrix();
  25451. var ray = rayFunction(world);
  25452. var result = mesh.intersects(ray, false);
  25453. if (!result || !result.hit)
  25454. continue;
  25455. pickingInfos.push(result);
  25456. }
  25457. return pickingInfos;
  25458. };
  25459. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25460. if (!BABYLON.PickingInfo) {
  25461. return null;
  25462. }
  25463. var pickingInfo = null;
  25464. if (!camera) {
  25465. if (!this.activeCamera) {
  25466. return null;
  25467. }
  25468. camera = this.activeCamera;
  25469. }
  25470. if (this.spriteManagers.length > 0) {
  25471. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25472. var spriteManager = this.spriteManagers[spriteIndex];
  25473. if (!spriteManager.isPickable) {
  25474. continue;
  25475. }
  25476. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25477. if (!result || !result.hit)
  25478. continue;
  25479. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25480. continue;
  25481. pickingInfo = result;
  25482. if (fastCheck) {
  25483. break;
  25484. }
  25485. }
  25486. }
  25487. return pickingInfo || new BABYLON.PickingInfo();
  25488. };
  25489. /** Launch a ray to try to pick a mesh in the scene
  25490. * @param x position on screen
  25491. * @param y position on screen
  25492. * @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
  25493. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25494. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25495. */
  25496. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25497. var _this = this;
  25498. if (!BABYLON.PickingInfo) {
  25499. return null;
  25500. }
  25501. return this._internalPick(function (world) {
  25502. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25503. return _this._tempPickingRay;
  25504. }, predicate, fastCheck);
  25505. };
  25506. /** Launch a ray to try to pick a sprite in the scene
  25507. * @param x position on screen
  25508. * @param y position on screen
  25509. * @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
  25510. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25511. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25512. */
  25513. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25514. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25515. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25516. };
  25517. /** Use the given ray to pick a mesh in the scene
  25518. * @param ray The ray to use to pick meshes
  25519. * @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
  25520. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25521. */
  25522. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25523. var _this = this;
  25524. return this._internalPick(function (world) {
  25525. if (!_this._pickWithRayInverseMatrix) {
  25526. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25527. }
  25528. world.invertToRef(_this._pickWithRayInverseMatrix);
  25529. if (!_this._cachedRayForTransform) {
  25530. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25531. }
  25532. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25533. return _this._cachedRayForTransform;
  25534. }, predicate, fastCheck);
  25535. };
  25536. /**
  25537. * Launch a ray to try to pick a mesh in the scene
  25538. * @param x X position on screen
  25539. * @param y Y position on screen
  25540. * @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
  25541. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25542. */
  25543. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25544. var _this = this;
  25545. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25546. };
  25547. /**
  25548. * Launch a ray to try to pick a mesh in the scene
  25549. * @param ray Ray to use
  25550. * @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
  25551. */
  25552. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25553. var _this = this;
  25554. return this._internalMultiPick(function (world) {
  25555. if (!_this._pickWithRayInverseMatrix) {
  25556. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25557. }
  25558. world.invertToRef(_this._pickWithRayInverseMatrix);
  25559. if (!_this._cachedRayForTransform) {
  25560. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25561. }
  25562. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25563. return _this._cachedRayForTransform;
  25564. }, predicate);
  25565. };
  25566. Scene.prototype.setPointerOverMesh = function (mesh) {
  25567. if (this._pointerOverMesh === mesh) {
  25568. return;
  25569. }
  25570. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25571. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25572. }
  25573. this._pointerOverMesh = mesh;
  25574. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25575. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25576. }
  25577. };
  25578. Scene.prototype.getPointerOverMesh = function () {
  25579. return this._pointerOverMesh;
  25580. };
  25581. Scene.prototype.setPointerOverSprite = function (sprite) {
  25582. if (this._pointerOverSprite === sprite) {
  25583. return;
  25584. }
  25585. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25586. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25587. }
  25588. this._pointerOverSprite = sprite;
  25589. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25590. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25591. }
  25592. };
  25593. Scene.prototype.getPointerOverSprite = function () {
  25594. return this._pointerOverSprite;
  25595. };
  25596. // Physics
  25597. Scene.prototype.getPhysicsEngine = function () {
  25598. return this._physicsEngine;
  25599. };
  25600. /**
  25601. * Enables physics to the current scene
  25602. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25603. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25604. * @return {boolean} was the physics engine initialized
  25605. */
  25606. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25607. if (gravity === void 0) { gravity = null; }
  25608. if (this._physicsEngine) {
  25609. return true;
  25610. }
  25611. try {
  25612. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25613. return true;
  25614. }
  25615. catch (e) {
  25616. BABYLON.Tools.Error(e.message);
  25617. return false;
  25618. }
  25619. };
  25620. Scene.prototype.disablePhysicsEngine = function () {
  25621. if (!this._physicsEngine) {
  25622. return;
  25623. }
  25624. this._physicsEngine.dispose();
  25625. this._physicsEngine = null;
  25626. };
  25627. Scene.prototype.isPhysicsEnabled = function () {
  25628. return this._physicsEngine !== undefined;
  25629. };
  25630. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25631. var mesh = compound.parts[0].mesh;
  25632. if (mesh.physicsImpostor) {
  25633. mesh.physicsImpostor.dispose();
  25634. mesh.physicsImpostor = null;
  25635. }
  25636. };
  25637. // Misc.
  25638. Scene.prototype._rebuildGeometries = function () {
  25639. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25640. var geometry = _a[_i];
  25641. geometry._rebuild();
  25642. }
  25643. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25644. var mesh = _c[_b];
  25645. mesh._rebuild();
  25646. }
  25647. if (this.postProcessManager) {
  25648. this.postProcessManager._rebuild();
  25649. }
  25650. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25651. var layer = _e[_d];
  25652. layer._rebuild();
  25653. }
  25654. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25655. var effectLayer = _g[_f];
  25656. effectLayer._rebuild();
  25657. }
  25658. if (this._boundingBoxRenderer) {
  25659. this._boundingBoxRenderer._rebuild();
  25660. }
  25661. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25662. var system = _j[_h];
  25663. system.rebuild();
  25664. }
  25665. if (this._postProcessRenderPipelineManager) {
  25666. this._postProcessRenderPipelineManager._rebuild();
  25667. }
  25668. };
  25669. Scene.prototype._rebuildTextures = function () {
  25670. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25671. var texture = _a[_i];
  25672. texture._rebuild();
  25673. }
  25674. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25675. };
  25676. /**
  25677. * Creates a default light for the scene.
  25678. * @param replace Whether to replace the existing lights in the scene.
  25679. */
  25680. Scene.prototype.createDefaultLight = function (replace) {
  25681. if (replace === void 0) { replace = false; }
  25682. // Dispose existing light in replace mode.
  25683. if (replace) {
  25684. if (this.lights) {
  25685. for (var i = 0; i < this.lights.length; i++) {
  25686. this.lights[i].dispose();
  25687. }
  25688. }
  25689. }
  25690. // Light
  25691. if (this.lights.length === 0) {
  25692. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25693. }
  25694. };
  25695. /**
  25696. * Creates a default camera for the scene.
  25697. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25698. * @param replace Whether to replace the existing active camera in the scene.
  25699. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25700. */
  25701. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25702. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25703. if (replace === void 0) { replace = false; }
  25704. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25705. // Dispose existing camera in replace mode.
  25706. if (replace) {
  25707. if (this.activeCamera) {
  25708. this.activeCamera.dispose();
  25709. this.activeCamera = null;
  25710. }
  25711. }
  25712. // Camera
  25713. if (!this.activeCamera) {
  25714. var worldExtends = this.getWorldExtends();
  25715. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25716. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25717. var camera;
  25718. var radius = worldSize.length() * 1.5;
  25719. // empty scene scenario!
  25720. if (!isFinite(radius)) {
  25721. radius = 1;
  25722. worldCenter.copyFromFloats(0, 0, 0);
  25723. }
  25724. if (createArcRotateCamera) {
  25725. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25726. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25727. arcRotateCamera.wheelPrecision = 100 / radius;
  25728. camera = arcRotateCamera;
  25729. }
  25730. else {
  25731. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25732. freeCamera.setTarget(worldCenter);
  25733. camera = freeCamera;
  25734. }
  25735. camera.minZ = radius * 0.01;
  25736. camera.maxZ = radius * 1000;
  25737. camera.speed = radius * 0.2;
  25738. this.activeCamera = camera;
  25739. var canvas = this.getEngine().getRenderingCanvas();
  25740. if (attachCameraControls && canvas) {
  25741. camera.attachControl(canvas);
  25742. }
  25743. }
  25744. };
  25745. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25746. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25747. if (replace === void 0) { replace = false; }
  25748. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25749. this.createDefaultLight(replace);
  25750. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25751. };
  25752. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25753. if (pbr === void 0) { pbr = false; }
  25754. if (scale === void 0) { scale = 1000; }
  25755. if (blur === void 0) { blur = 0; }
  25756. if (environmentTexture) {
  25757. this.environmentTexture = environmentTexture;
  25758. }
  25759. if (!this.environmentTexture) {
  25760. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25761. return null;
  25762. }
  25763. // Skybox
  25764. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25765. if (pbr) {
  25766. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25767. hdrSkyboxMaterial.backFaceCulling = false;
  25768. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25769. if (hdrSkyboxMaterial.reflectionTexture) {
  25770. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25771. }
  25772. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25773. hdrSkyboxMaterial.disableLighting = true;
  25774. hdrSkyboxMaterial.twoSidedLighting = true;
  25775. hdrSkybox.infiniteDistance = true;
  25776. hdrSkybox.material = hdrSkyboxMaterial;
  25777. }
  25778. else {
  25779. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25780. skyboxMaterial.backFaceCulling = false;
  25781. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25782. if (skyboxMaterial.reflectionTexture) {
  25783. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25784. }
  25785. skyboxMaterial.disableLighting = true;
  25786. hdrSkybox.infiniteDistance = true;
  25787. hdrSkybox.material = skyboxMaterial;
  25788. }
  25789. return hdrSkybox;
  25790. };
  25791. Scene.prototype.createDefaultEnvironment = function (options) {
  25792. if (BABYLON.EnvironmentHelper) {
  25793. return new BABYLON.EnvironmentHelper(options, this);
  25794. }
  25795. return null;
  25796. };
  25797. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25798. if (webVROptions === void 0) { webVROptions = {}; }
  25799. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25800. };
  25801. // Tags
  25802. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25803. if (tagsQuery === undefined) {
  25804. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25805. return list;
  25806. }
  25807. var listByTags = [];
  25808. forEach = forEach || (function (item) { return; });
  25809. for (var i in list) {
  25810. var item = list[i];
  25811. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25812. listByTags.push(item);
  25813. forEach(item);
  25814. }
  25815. }
  25816. return listByTags;
  25817. };
  25818. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25819. return this._getByTags(this.meshes, tagsQuery, forEach);
  25820. };
  25821. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25822. return this._getByTags(this.cameras, tagsQuery, forEach);
  25823. };
  25824. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25825. return this._getByTags(this.lights, tagsQuery, forEach);
  25826. };
  25827. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25828. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25829. };
  25830. /**
  25831. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25832. * This allowed control for front to back rendering or reversly depending of the special needs.
  25833. *
  25834. * @param renderingGroupId The rendering group id corresponding to its index
  25835. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25836. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25837. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25838. */
  25839. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25840. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25841. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25842. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25843. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25844. };
  25845. /**
  25846. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25847. *
  25848. * @param renderingGroupId The rendering group id corresponding to its index
  25849. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25850. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25851. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25852. */
  25853. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25854. if (depth === void 0) { depth = true; }
  25855. if (stencil === void 0) { stencil = true; }
  25856. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25857. };
  25858. /**
  25859. * Will flag all materials as dirty to trigger new shader compilation
  25860. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25861. */
  25862. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25863. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25864. var material = _a[_i];
  25865. if (predicate && !predicate(material)) {
  25866. continue;
  25867. }
  25868. material.markAsDirty(flag);
  25869. }
  25870. };
  25871. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25872. var _this = this;
  25873. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25874. this._activeRequests.push(request);
  25875. request.onCompleteObservable.add(function (request) {
  25876. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25877. });
  25878. return request;
  25879. };
  25880. /** @ignore */
  25881. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25882. var _this = this;
  25883. return new Promise(function (resolve, reject) {
  25884. _this._loadFile(url, function (data) {
  25885. resolve(data);
  25886. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25887. reject(exception);
  25888. });
  25889. });
  25890. };
  25891. // Statics
  25892. Scene._FOGMODE_NONE = 0;
  25893. Scene._FOGMODE_EXP = 1;
  25894. Scene._FOGMODE_EXP2 = 2;
  25895. Scene._FOGMODE_LINEAR = 3;
  25896. Scene._uniqueIdCounter = 0;
  25897. /**
  25898. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  25899. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25900. */
  25901. Scene.MinDeltaTime = 1.0;
  25902. /**
  25903. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  25904. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25905. */
  25906. Scene.MaxDeltaTime = 1000.0;
  25907. /** The distance in pixel that you have to move to prevent some events */
  25908. Scene.DragMovementThreshold = 10; // in pixels
  25909. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25910. Scene.LongPressDelay = 500; // in milliseconds
  25911. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25912. Scene.DoubleClickDelay = 300; // in milliseconds
  25913. /** If you need to check double click without raising a single click at first click, enable this flag */
  25914. Scene.ExclusiveDoubleClickMode = false;
  25915. return Scene;
  25916. }());
  25917. BABYLON.Scene = Scene;
  25918. })(BABYLON || (BABYLON = {}));
  25919. //# sourceMappingURL=babylon.scene.js.map
  25920. "use strict";
  25921. var BABYLON;
  25922. (function (BABYLON) {
  25923. /**
  25924. * Set of assets to keep when moving a scene into an asset container.
  25925. */
  25926. var KeepAssets = /** @class */ (function () {
  25927. function KeepAssets() {
  25928. /**
  25929. * Cameras to keep.
  25930. */
  25931. this.cameras = new Array();
  25932. /**
  25933. * Lights to keep.
  25934. */
  25935. this.lights = new Array();
  25936. /**
  25937. * Meshes to keep.
  25938. */
  25939. this.meshes = new Array();
  25940. /**
  25941. * Skeletons to keep.
  25942. */
  25943. this.skeletons = new Array();
  25944. /**
  25945. * ParticleSystems to keep.
  25946. */
  25947. this.particleSystems = new Array();
  25948. /**
  25949. * Animations to keep.
  25950. */
  25951. this.animations = new Array();
  25952. /**
  25953. * AnimationGroups to keep.
  25954. */
  25955. this.animationGroups = new Array();
  25956. /**
  25957. * MultiMaterials to keep.
  25958. */
  25959. this.multiMaterials = new Array();
  25960. /**
  25961. * Materials to keep.
  25962. */
  25963. this.materials = new Array();
  25964. /**
  25965. * MorphTargetManagers to keep.
  25966. */
  25967. this.morphTargetManagers = new Array();
  25968. /**
  25969. * Geometries to keep.
  25970. */
  25971. this.geometries = new Array();
  25972. /**
  25973. * TransformNodes to keep.
  25974. */
  25975. this.transformNodes = new Array();
  25976. /**
  25977. * LensFlareSystems to keep.
  25978. */
  25979. this.lensFlareSystems = new Array();
  25980. /**
  25981. * ShadowGenerators to keep.
  25982. */
  25983. this.shadowGenerators = new Array();
  25984. /**
  25985. * ActionManagers to keep.
  25986. */
  25987. this.actionManagers = new Array();
  25988. /**
  25989. * Sounds to keep.
  25990. */
  25991. this.sounds = new Array();
  25992. /**
  25993. * Textures to keep.
  25994. */
  25995. this.textures = new Array();
  25996. }
  25997. return KeepAssets;
  25998. }());
  25999. BABYLON.KeepAssets = KeepAssets;
  26000. /**
  26001. * Container with a set of assets that can be added or removed from a scene.
  26002. */
  26003. var AssetContainer = /** @class */ (function () {
  26004. /**
  26005. * Instantiates an AssetContainer.
  26006. * @param scene The scene the AssetContainer belongs to.
  26007. */
  26008. function AssetContainer(scene) {
  26009. // Objects
  26010. /**
  26011. * Cameras populated in the container.
  26012. */
  26013. this.cameras = new Array();
  26014. /**
  26015. * Lights populated in the container.
  26016. */
  26017. this.lights = new Array();
  26018. /**
  26019. * Meshes populated in the container.
  26020. */
  26021. this.meshes = new Array();
  26022. /**
  26023. * Skeletons populated in the container.
  26024. */
  26025. this.skeletons = new Array();
  26026. /**
  26027. * ParticleSystems populated in the container.
  26028. */
  26029. this.particleSystems = new Array();
  26030. /**
  26031. * Animations populated in the container.
  26032. */
  26033. this.animations = new Array();
  26034. /**
  26035. * AnimationGroups populated in the container.
  26036. */
  26037. this.animationGroups = new Array();
  26038. /**
  26039. * MultiMaterials populated in the container.
  26040. */
  26041. this.multiMaterials = new Array();
  26042. /**
  26043. * Materials populated in the container.
  26044. */
  26045. this.materials = new Array();
  26046. /**
  26047. * MorphTargetManagers populated in the container.
  26048. */
  26049. this.morphTargetManagers = new Array();
  26050. /**
  26051. * Geometries populated in the container.
  26052. */
  26053. this.geometries = new Array();
  26054. /**
  26055. * TransformNodes populated in the container.
  26056. */
  26057. this.transformNodes = new Array();
  26058. /**
  26059. * LensFlareSystems populated in the container.
  26060. */
  26061. this.lensFlareSystems = new Array();
  26062. /**
  26063. * ShadowGenerators populated in the container.
  26064. */
  26065. this.shadowGenerators = new Array();
  26066. /**
  26067. * ActionManagers populated in the container.
  26068. */
  26069. this.actionManagers = new Array();
  26070. /**
  26071. * Sounds populated in the container.
  26072. */
  26073. this.sounds = new Array();
  26074. /**
  26075. * Textures populated in the container.
  26076. */
  26077. this.textures = new Array();
  26078. this.scene = scene;
  26079. }
  26080. /**
  26081. * Adds all the assets from the container to the scene.
  26082. */
  26083. AssetContainer.prototype.addAllToScene = function () {
  26084. var _this = this;
  26085. this.cameras.forEach(function (o) {
  26086. _this.scene.addCamera(o);
  26087. });
  26088. this.lights.forEach(function (o) {
  26089. _this.scene.addLight(o);
  26090. });
  26091. this.meshes.forEach(function (o) {
  26092. _this.scene.addMesh(o);
  26093. });
  26094. this.skeletons.forEach(function (o) {
  26095. _this.scene.addSkeleton(o);
  26096. });
  26097. this.particleSystems.forEach(function (o) {
  26098. _this.scene.addParticleSystem(o);
  26099. });
  26100. this.animations.forEach(function (o) {
  26101. _this.scene.addAnimation(o);
  26102. });
  26103. this.animationGroups.forEach(function (o) {
  26104. _this.scene.addAnimationGroup(o);
  26105. });
  26106. this.multiMaterials.forEach(function (o) {
  26107. _this.scene.addMultiMaterial(o);
  26108. });
  26109. this.materials.forEach(function (o) {
  26110. _this.scene.addMaterial(o);
  26111. });
  26112. this.morphTargetManagers.forEach(function (o) {
  26113. _this.scene.addMorphTargetManager(o);
  26114. });
  26115. this.geometries.forEach(function (o) {
  26116. _this.scene.addGeometry(o);
  26117. });
  26118. this.transformNodes.forEach(function (o) {
  26119. _this.scene.addTransformNode(o);
  26120. });
  26121. this.lensFlareSystems.forEach(function (o) {
  26122. _this.scene.addLensFlareSystem(o);
  26123. });
  26124. this.actionManagers.forEach(function (o) {
  26125. _this.scene.addActionManager(o);
  26126. });
  26127. this.sounds.forEach(function (o) {
  26128. o.play();
  26129. o.autoplay = true;
  26130. _this.scene.mainSoundTrack.AddSound(o);
  26131. });
  26132. this.textures.forEach(function (o) {
  26133. _this.scene.addTexture;
  26134. });
  26135. };
  26136. /**
  26137. * Removes all the assets in the container from the scene
  26138. */
  26139. AssetContainer.prototype.removeAllFromScene = function () {
  26140. var _this = this;
  26141. this.cameras.forEach(function (o) {
  26142. _this.scene.removeCamera(o);
  26143. });
  26144. this.lights.forEach(function (o) {
  26145. _this.scene.removeLight(o);
  26146. });
  26147. this.meshes.forEach(function (o) {
  26148. _this.scene.removeMesh(o);
  26149. });
  26150. this.skeletons.forEach(function (o) {
  26151. _this.scene.removeSkeleton(o);
  26152. });
  26153. this.particleSystems.forEach(function (o) {
  26154. _this.scene.removeParticleSystem(o);
  26155. });
  26156. this.animations.forEach(function (o) {
  26157. _this.scene.removeAnimation(o);
  26158. });
  26159. this.animationGroups.forEach(function (o) {
  26160. _this.scene.removeAnimationGroup(o);
  26161. });
  26162. this.multiMaterials.forEach(function (o) {
  26163. _this.scene.removeMultiMaterial(o);
  26164. });
  26165. this.materials.forEach(function (o) {
  26166. _this.scene.removeMaterial(o);
  26167. });
  26168. this.morphTargetManagers.forEach(function (o) {
  26169. _this.scene.removeMorphTargetManager(o);
  26170. });
  26171. this.geometries.forEach(function (o) {
  26172. _this.scene.removeGeometry(o);
  26173. });
  26174. this.transformNodes.forEach(function (o) {
  26175. _this.scene.removeTransformNode(o);
  26176. });
  26177. this.lensFlareSystems.forEach(function (o) {
  26178. _this.scene.removeLensFlareSystem(o);
  26179. });
  26180. this.actionManagers.forEach(function (o) {
  26181. _this.scene.removeActionManager(o);
  26182. });
  26183. this.sounds.forEach(function (o) {
  26184. o.stop();
  26185. o.autoplay = false;
  26186. _this.scene.mainSoundTrack.RemoveSound(o);
  26187. });
  26188. this.textures.forEach(function (o) {
  26189. _this.scene.removeTexture(o);
  26190. });
  26191. };
  26192. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26193. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26194. var asset = sourceAssets_1[_i];
  26195. var move = true;
  26196. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26197. var keepAsset = keepAssets_1[_a];
  26198. if (asset === keepAsset) {
  26199. move = false;
  26200. break;
  26201. }
  26202. }
  26203. if (move) {
  26204. targetAssets.push(asset);
  26205. }
  26206. }
  26207. };
  26208. /**
  26209. * Removes all the assets contained in the scene and adds them to the container.
  26210. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26211. */
  26212. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26213. if (keepAssets === undefined) {
  26214. keepAssets = new KeepAssets();
  26215. }
  26216. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26217. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26218. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26219. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26220. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26221. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26222. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  26223. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26224. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26225. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26226. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26227. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26228. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26229. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26230. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26231. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  26232. this.removeAllFromScene();
  26233. };
  26234. return AssetContainer;
  26235. }());
  26236. BABYLON.AssetContainer = AssetContainer;
  26237. })(BABYLON || (BABYLON = {}));
  26238. //# sourceMappingURL=babylon.assetContainer.js.map
  26239. "use strict";
  26240. var BABYLON;
  26241. (function (BABYLON) {
  26242. var Buffer = /** @class */ (function () {
  26243. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26244. if (instanced === void 0) { instanced = false; }
  26245. if (engine instanceof BABYLON.Mesh) {
  26246. this._engine = engine.getScene().getEngine();
  26247. }
  26248. else {
  26249. this._engine = engine;
  26250. }
  26251. this._updatable = updatable;
  26252. this._instanced = instanced;
  26253. this._data = data;
  26254. this._strideSize = stride;
  26255. if (!postponeInternalCreation) {
  26256. this.create();
  26257. }
  26258. }
  26259. /**
  26260. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26261. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26262. * @param offset defines offset in the buffer (0 by default)
  26263. * @param size defines the size in floats of attributes (position is 3 for instance)
  26264. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26265. * @param instanced defines if the vertex buffer contains indexed data
  26266. * @returns the new vertex buffer
  26267. */
  26268. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26269. // a lot of these parameters are ignored as they are overriden by the buffer
  26270. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26271. };
  26272. // Properties
  26273. Buffer.prototype.isUpdatable = function () {
  26274. return this._updatable;
  26275. };
  26276. Buffer.prototype.getData = function () {
  26277. return this._data;
  26278. };
  26279. Buffer.prototype.getBuffer = function () {
  26280. return this._buffer;
  26281. };
  26282. Buffer.prototype.getStrideSize = function () {
  26283. return this._strideSize;
  26284. };
  26285. // public getIsInstanced(): boolean {
  26286. // return this._instanced;
  26287. // }
  26288. // public get instanceDivisor(): number {
  26289. // return this._instanceDivisor;
  26290. // }
  26291. // public set instanceDivisor(value: number) {
  26292. // this._instanceDivisor = value;
  26293. // if (value == 0) {
  26294. // this._instanced = false;
  26295. // } else {
  26296. // this._instanced = true;
  26297. // }
  26298. // }
  26299. // Methods
  26300. Buffer.prototype.create = function (data) {
  26301. if (data === void 0) { data = null; }
  26302. if (!data && this._buffer) {
  26303. return; // nothing to do
  26304. }
  26305. data = data || this._data;
  26306. if (!data) {
  26307. return;
  26308. }
  26309. if (!this._buffer) {
  26310. if (this._updatable) {
  26311. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26312. this._data = data;
  26313. }
  26314. else {
  26315. this._buffer = this._engine.createVertexBuffer(data);
  26316. }
  26317. }
  26318. else if (this._updatable) {
  26319. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26320. this._data = data;
  26321. }
  26322. };
  26323. Buffer.prototype._rebuild = function () {
  26324. this._buffer = null;
  26325. this.create(this._data);
  26326. };
  26327. Buffer.prototype.update = function (data) {
  26328. this.create(data);
  26329. };
  26330. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26331. if (!this._buffer) {
  26332. return;
  26333. }
  26334. if (this._updatable) {
  26335. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26336. this._data = null;
  26337. }
  26338. };
  26339. Buffer.prototype.dispose = function () {
  26340. if (!this._buffer) {
  26341. return;
  26342. }
  26343. if (this._engine._releaseBuffer(this._buffer)) {
  26344. this._buffer = null;
  26345. }
  26346. };
  26347. return Buffer;
  26348. }());
  26349. BABYLON.Buffer = Buffer;
  26350. })(BABYLON || (BABYLON = {}));
  26351. //# sourceMappingURL=babylon.buffer.js.map
  26352. "use strict";
  26353. var BABYLON;
  26354. (function (BABYLON) {
  26355. var VertexBuffer = /** @class */ (function () {
  26356. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26357. if (data instanceof BABYLON.Buffer) {
  26358. if (!stride) {
  26359. stride = data.getStrideSize();
  26360. }
  26361. this._buffer = data;
  26362. this._ownsBuffer = false;
  26363. }
  26364. else {
  26365. if (!stride) {
  26366. stride = VertexBuffer.DeduceStride(kind);
  26367. }
  26368. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26369. this._ownsBuffer = true;
  26370. }
  26371. this._stride = stride;
  26372. this._instanced = instanced !== undefined ? instanced : false;
  26373. this._instanceDivisor = instanced ? 1 : 0;
  26374. this._offset = offset ? offset : 0;
  26375. this._size = size ? size : stride;
  26376. this._kind = kind;
  26377. }
  26378. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26379. /**
  26380. * Gets or sets the instance divisor when in instanced mode
  26381. */
  26382. get: function () {
  26383. return this._instanceDivisor;
  26384. },
  26385. set: function (value) {
  26386. this._instanceDivisor = value;
  26387. if (value == 0) {
  26388. this._instanced = false;
  26389. }
  26390. else {
  26391. this._instanced = true;
  26392. }
  26393. },
  26394. enumerable: true,
  26395. configurable: true
  26396. });
  26397. VertexBuffer.prototype._rebuild = function () {
  26398. if (!this._buffer) {
  26399. return;
  26400. }
  26401. this._buffer._rebuild();
  26402. };
  26403. /**
  26404. * Returns the kind of the VertexBuffer (string).
  26405. */
  26406. VertexBuffer.prototype.getKind = function () {
  26407. return this._kind;
  26408. };
  26409. // Properties
  26410. /**
  26411. * Boolean : is the VertexBuffer updatable ?
  26412. */
  26413. VertexBuffer.prototype.isUpdatable = function () {
  26414. return this._buffer.isUpdatable();
  26415. };
  26416. /**
  26417. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26418. */
  26419. VertexBuffer.prototype.getData = function () {
  26420. return this._buffer.getData();
  26421. };
  26422. /**
  26423. * Returns the WebGLBuffer associated to the VertexBuffer.
  26424. */
  26425. VertexBuffer.prototype.getBuffer = function () {
  26426. return this._buffer.getBuffer();
  26427. };
  26428. /**
  26429. * Returns the stride of the VertexBuffer (integer).
  26430. */
  26431. VertexBuffer.prototype.getStrideSize = function () {
  26432. return this._stride;
  26433. };
  26434. /**
  26435. * Returns the offset (integer).
  26436. */
  26437. VertexBuffer.prototype.getOffset = function () {
  26438. return this._offset;
  26439. };
  26440. /**
  26441. * Returns the VertexBuffer total size (integer).
  26442. */
  26443. VertexBuffer.prototype.getSize = function () {
  26444. return this._size;
  26445. };
  26446. /**
  26447. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26448. */
  26449. VertexBuffer.prototype.getIsInstanced = function () {
  26450. return this._instanced;
  26451. };
  26452. /**
  26453. * Returns the instancing divisor, zero for non-instanced (integer).
  26454. */
  26455. VertexBuffer.prototype.getInstanceDivisor = function () {
  26456. return this._instanceDivisor;
  26457. };
  26458. // Methods
  26459. /**
  26460. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26461. * Returns the created WebGLBuffer.
  26462. */
  26463. VertexBuffer.prototype.create = function (data) {
  26464. return this._buffer.create(data);
  26465. };
  26466. /**
  26467. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26468. * This function will create a new buffer if the current one is not updatable
  26469. * Returns the updated WebGLBuffer.
  26470. */
  26471. VertexBuffer.prototype.update = function (data) {
  26472. return this._buffer.update(data);
  26473. };
  26474. /**
  26475. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26476. * Returns the directly updated WebGLBuffer.
  26477. */
  26478. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26479. return this._buffer.updateDirectly(data, offset);
  26480. };
  26481. /**
  26482. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26483. */
  26484. VertexBuffer.prototype.dispose = function () {
  26485. if (this._ownsBuffer) {
  26486. this._buffer.dispose();
  26487. }
  26488. };
  26489. Object.defineProperty(VertexBuffer, "PositionKind", {
  26490. get: function () {
  26491. return VertexBuffer._PositionKind;
  26492. },
  26493. enumerable: true,
  26494. configurable: true
  26495. });
  26496. Object.defineProperty(VertexBuffer, "NormalKind", {
  26497. get: function () {
  26498. return VertexBuffer._NormalKind;
  26499. },
  26500. enumerable: true,
  26501. configurable: true
  26502. });
  26503. Object.defineProperty(VertexBuffer, "TangentKind", {
  26504. get: function () {
  26505. return VertexBuffer._TangentKind;
  26506. },
  26507. enumerable: true,
  26508. configurable: true
  26509. });
  26510. Object.defineProperty(VertexBuffer, "UVKind", {
  26511. get: function () {
  26512. return VertexBuffer._UVKind;
  26513. },
  26514. enumerable: true,
  26515. configurable: true
  26516. });
  26517. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26518. get: function () {
  26519. return VertexBuffer._UV2Kind;
  26520. },
  26521. enumerable: true,
  26522. configurable: true
  26523. });
  26524. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26525. get: function () {
  26526. return VertexBuffer._UV3Kind;
  26527. },
  26528. enumerable: true,
  26529. configurable: true
  26530. });
  26531. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26532. get: function () {
  26533. return VertexBuffer._UV4Kind;
  26534. },
  26535. enumerable: true,
  26536. configurable: true
  26537. });
  26538. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26539. get: function () {
  26540. return VertexBuffer._UV5Kind;
  26541. },
  26542. enumerable: true,
  26543. configurable: true
  26544. });
  26545. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26546. get: function () {
  26547. return VertexBuffer._UV6Kind;
  26548. },
  26549. enumerable: true,
  26550. configurable: true
  26551. });
  26552. Object.defineProperty(VertexBuffer, "ColorKind", {
  26553. get: function () {
  26554. return VertexBuffer._ColorKind;
  26555. },
  26556. enumerable: true,
  26557. configurable: true
  26558. });
  26559. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26560. get: function () {
  26561. return VertexBuffer._MatricesIndicesKind;
  26562. },
  26563. enumerable: true,
  26564. configurable: true
  26565. });
  26566. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26567. get: function () {
  26568. return VertexBuffer._MatricesWeightsKind;
  26569. },
  26570. enumerable: true,
  26571. configurable: true
  26572. });
  26573. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26574. get: function () {
  26575. return VertexBuffer._MatricesIndicesExtraKind;
  26576. },
  26577. enumerable: true,
  26578. configurable: true
  26579. });
  26580. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26581. get: function () {
  26582. return VertexBuffer._MatricesWeightsExtraKind;
  26583. },
  26584. enumerable: true,
  26585. configurable: true
  26586. });
  26587. /**
  26588. * Deduces the stride given a kind.
  26589. * @param kind The kind string to deduce
  26590. * @returns The deduced stride
  26591. */
  26592. VertexBuffer.DeduceStride = function (kind) {
  26593. switch (kind) {
  26594. case VertexBuffer.UVKind:
  26595. case VertexBuffer.UV2Kind:
  26596. case VertexBuffer.UV3Kind:
  26597. case VertexBuffer.UV4Kind:
  26598. case VertexBuffer.UV5Kind:
  26599. case VertexBuffer.UV6Kind:
  26600. return 2;
  26601. case VertexBuffer.NormalKind:
  26602. case VertexBuffer.PositionKind:
  26603. return 3;
  26604. case VertexBuffer.ColorKind:
  26605. case VertexBuffer.MatricesIndicesKind:
  26606. case VertexBuffer.MatricesIndicesExtraKind:
  26607. case VertexBuffer.MatricesWeightsKind:
  26608. case VertexBuffer.MatricesWeightsExtraKind:
  26609. case VertexBuffer.TangentKind:
  26610. return 4;
  26611. default:
  26612. throw new Error("Invalid kind '" + kind + "'");
  26613. }
  26614. };
  26615. // Enums
  26616. VertexBuffer._PositionKind = "position";
  26617. VertexBuffer._NormalKind = "normal";
  26618. VertexBuffer._TangentKind = "tangent";
  26619. VertexBuffer._UVKind = "uv";
  26620. VertexBuffer._UV2Kind = "uv2";
  26621. VertexBuffer._UV3Kind = "uv3";
  26622. VertexBuffer._UV4Kind = "uv4";
  26623. VertexBuffer._UV5Kind = "uv5";
  26624. VertexBuffer._UV6Kind = "uv6";
  26625. VertexBuffer._ColorKind = "color";
  26626. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26627. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26628. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26629. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26630. return VertexBuffer;
  26631. }());
  26632. BABYLON.VertexBuffer = VertexBuffer;
  26633. })(BABYLON || (BABYLON = {}));
  26634. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26635. "use strict";
  26636. var BABYLON;
  26637. (function (BABYLON) {
  26638. /**
  26639. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26640. */
  26641. var DummyInternalTextureTracker = /** @class */ (function () {
  26642. function DummyInternalTextureTracker() {
  26643. /**
  26644. * Gets or set the previous tracker in the list
  26645. */
  26646. this.previous = null;
  26647. /**
  26648. * Gets or set the next tracker in the list
  26649. */
  26650. this.next = null;
  26651. }
  26652. return DummyInternalTextureTracker;
  26653. }());
  26654. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26655. })(BABYLON || (BABYLON = {}));
  26656. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26657. "use strict";
  26658. var BABYLON;
  26659. (function (BABYLON) {
  26660. /**
  26661. * Class used to store data associated with WebGL texture data for the engine
  26662. * This class should not be used directly
  26663. */
  26664. var InternalTexture = /** @class */ (function () {
  26665. /**
  26666. * Creates a new InternalTexture
  26667. * @param engine defines the engine to use
  26668. * @param dataSource defines the type of data that will be used
  26669. */
  26670. function InternalTexture(engine, dataSource) {
  26671. /**
  26672. * Observable called when the texture is loaded
  26673. */
  26674. this.onLoadedObservable = new BABYLON.Observable();
  26675. /**
  26676. * Gets or set the previous tracker in the list
  26677. */
  26678. this.previous = null;
  26679. /**
  26680. * Gets or set the next tracker in the list
  26681. */
  26682. this.next = null;
  26683. // Private
  26684. /** @ignore */
  26685. this._initialSlot = -1;
  26686. /** @ignore */
  26687. this._designatedSlot = -1;
  26688. /** @ignore */
  26689. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26690. /** @ignore */
  26691. this._comparisonFunction = 0;
  26692. /** @ignore */
  26693. this._references = 1;
  26694. this._engine = engine;
  26695. this._dataSource = dataSource;
  26696. this._webGLTexture = engine._createTexture();
  26697. }
  26698. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26699. /**
  26700. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26701. */
  26702. get: function () {
  26703. return this._dataSource;
  26704. },
  26705. enumerable: true,
  26706. configurable: true
  26707. });
  26708. /**
  26709. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26710. */
  26711. InternalTexture.prototype.incrementReferences = function () {
  26712. this._references++;
  26713. };
  26714. /**
  26715. * Change the size of the texture (not the size of the content)
  26716. * @param width defines the new width
  26717. * @param height defines the new height
  26718. * @param depth defines the new depth (1 by default)
  26719. */
  26720. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26721. if (depth === void 0) { depth = 1; }
  26722. this.width = width;
  26723. this.height = height;
  26724. this.depth = depth;
  26725. this.baseWidth = width;
  26726. this.baseHeight = height;
  26727. this.baseDepth = depth;
  26728. this._size = width * height * depth;
  26729. };
  26730. /** @ignore */
  26731. InternalTexture.prototype._rebuild = function () {
  26732. var _this = this;
  26733. var proxy;
  26734. this.isReady = false;
  26735. this._cachedCoordinatesMode = null;
  26736. this._cachedWrapU = null;
  26737. this._cachedWrapV = null;
  26738. this._cachedAnisotropicFilteringLevel = null;
  26739. switch (this._dataSource) {
  26740. case InternalTexture.DATASOURCE_TEMP:
  26741. return;
  26742. case InternalTexture.DATASOURCE_URL:
  26743. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26744. _this.isReady = true;
  26745. }, null, this._buffer, undefined, this.format);
  26746. proxy._swapAndDie(this);
  26747. return;
  26748. case InternalTexture.DATASOURCE_RAW:
  26749. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26750. proxy._swapAndDie(this);
  26751. this.isReady = true;
  26752. return;
  26753. case InternalTexture.DATASOURCE_RAW3D:
  26754. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26755. proxy._swapAndDie(this);
  26756. this.isReady = true;
  26757. return;
  26758. case InternalTexture.DATASOURCE_DYNAMIC:
  26759. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26760. proxy._swapAndDie(this);
  26761. // The engine will make sure to update content so no need to flag it as isReady = true
  26762. return;
  26763. case InternalTexture.DATASOURCE_RENDERTARGET:
  26764. var options = new BABYLON.RenderTargetCreationOptions();
  26765. options.generateDepthBuffer = this._generateDepthBuffer;
  26766. options.generateMipMaps = this.generateMipMaps;
  26767. options.generateStencilBuffer = this._generateStencilBuffer;
  26768. options.samplingMode = this.samplingMode;
  26769. options.type = this.type;
  26770. if (this.isCube) {
  26771. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26772. }
  26773. else {
  26774. var size = {
  26775. width: this.width,
  26776. height: this.height
  26777. };
  26778. proxy = this._engine.createRenderTargetTexture(size, options);
  26779. }
  26780. proxy._swapAndDie(this);
  26781. this.isReady = true;
  26782. return;
  26783. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26784. var depthTextureOptions = {
  26785. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26786. comparisonFunction: this._comparisonFunction,
  26787. generateStencil: this._generateStencilBuffer,
  26788. isCube: this.isCube
  26789. };
  26790. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26791. proxy._swapAndDie(this);
  26792. this.isReady = true;
  26793. return;
  26794. case InternalTexture.DATASOURCE_CUBE:
  26795. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26796. _this.isReady = true;
  26797. }, null, this.format, this._extension);
  26798. proxy._swapAndDie(this);
  26799. return;
  26800. case InternalTexture.DATASOURCE_CUBERAW:
  26801. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26802. proxy._swapAndDie(this);
  26803. this.isReady = true;
  26804. return;
  26805. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26806. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26807. if (proxy) {
  26808. proxy._swapAndDie(_this);
  26809. }
  26810. _this.isReady = true;
  26811. }, null, this.format, this._extension);
  26812. return;
  26813. }
  26814. };
  26815. InternalTexture.prototype._swapAndDie = function (target) {
  26816. target._webGLTexture = this._webGLTexture;
  26817. if (this._framebuffer) {
  26818. target._framebuffer = this._framebuffer;
  26819. }
  26820. if (this._depthStencilBuffer) {
  26821. target._depthStencilBuffer = this._depthStencilBuffer;
  26822. }
  26823. if (this._lodTextureHigh) {
  26824. if (target._lodTextureHigh) {
  26825. target._lodTextureHigh.dispose();
  26826. }
  26827. target._lodTextureHigh = this._lodTextureHigh;
  26828. }
  26829. if (this._lodTextureMid) {
  26830. if (target._lodTextureMid) {
  26831. target._lodTextureMid.dispose();
  26832. }
  26833. target._lodTextureMid = this._lodTextureMid;
  26834. }
  26835. if (this._lodTextureLow) {
  26836. if (target._lodTextureLow) {
  26837. target._lodTextureLow.dispose();
  26838. }
  26839. target._lodTextureLow = this._lodTextureLow;
  26840. }
  26841. var cache = this._engine.getLoadedTexturesCache();
  26842. var index = cache.indexOf(this);
  26843. if (index !== -1) {
  26844. cache.splice(index, 1);
  26845. }
  26846. };
  26847. /**
  26848. * Dispose the current allocated resources
  26849. */
  26850. InternalTexture.prototype.dispose = function () {
  26851. if (!this._webGLTexture) {
  26852. return;
  26853. }
  26854. this._references--;
  26855. if (this._references === 0) {
  26856. this._engine._releaseTexture(this);
  26857. this._webGLTexture = null;
  26858. this.previous = null;
  26859. this.next = null;
  26860. }
  26861. };
  26862. /**
  26863. * The source of the texture data is unknown
  26864. */
  26865. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26866. /**
  26867. * Texture data comes from an URL
  26868. */
  26869. InternalTexture.DATASOURCE_URL = 1;
  26870. /**
  26871. * Texture data is only used for temporary storage
  26872. */
  26873. InternalTexture.DATASOURCE_TEMP = 2;
  26874. /**
  26875. * Texture data comes from raw data (ArrayBuffer)
  26876. */
  26877. InternalTexture.DATASOURCE_RAW = 3;
  26878. /**
  26879. * Texture content is dynamic (video or dynamic texture)
  26880. */
  26881. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26882. /**
  26883. * Texture content is generated by rendering to it
  26884. */
  26885. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26886. /**
  26887. * Texture content is part of a multi render target process
  26888. */
  26889. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26890. /**
  26891. * Texture data comes from a cube data file
  26892. */
  26893. InternalTexture.DATASOURCE_CUBE = 7;
  26894. /**
  26895. * Texture data comes from a raw cube data
  26896. */
  26897. InternalTexture.DATASOURCE_CUBERAW = 8;
  26898. /**
  26899. * Texture data come from a prefiltered cube data file
  26900. */
  26901. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26902. /**
  26903. * Texture content is raw 3D data
  26904. */
  26905. InternalTexture.DATASOURCE_RAW3D = 10;
  26906. /**
  26907. * Texture content is a depth texture
  26908. */
  26909. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26910. return InternalTexture;
  26911. }());
  26912. BABYLON.InternalTexture = InternalTexture;
  26913. })(BABYLON || (BABYLON = {}));
  26914. //# sourceMappingURL=babylon.internalTexture.js.map
  26915. "use strict";
  26916. var BABYLON;
  26917. (function (BABYLON) {
  26918. var BaseTexture = /** @class */ (function () {
  26919. function BaseTexture(scene) {
  26920. this._hasAlpha = false;
  26921. this.getAlphaFromRGB = false;
  26922. this.level = 1;
  26923. this.coordinatesIndex = 0;
  26924. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26925. /**
  26926. * | Value | Type | Description |
  26927. * | ----- | ------------------ | ----------- |
  26928. * | 0 | CLAMP_ADDRESSMODE | |
  26929. * | 1 | WRAP_ADDRESSMODE | |
  26930. * | 2 | MIRROR_ADDRESSMODE | |
  26931. */
  26932. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26933. /**
  26934. * | Value | Type | Description |
  26935. * | ----- | ------------------ | ----------- |
  26936. * | 0 | CLAMP_ADDRESSMODE | |
  26937. * | 1 | WRAP_ADDRESSMODE | |
  26938. * | 2 | MIRROR_ADDRESSMODE | |
  26939. */
  26940. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26941. /**
  26942. * | Value | Type | Description |
  26943. * | ----- | ------------------ | ----------- |
  26944. * | 0 | CLAMP_ADDRESSMODE | |
  26945. * | 1 | WRAP_ADDRESSMODE | |
  26946. * | 2 | MIRROR_ADDRESSMODE | |
  26947. */
  26948. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26949. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26950. this.isCube = false;
  26951. this.is3D = false;
  26952. this.gammaSpace = true;
  26953. this.invertZ = false;
  26954. this.lodLevelInAlpha = false;
  26955. this.lodGenerationOffset = 0.0;
  26956. this.lodGenerationScale = 0.8;
  26957. this.isRenderTarget = false;
  26958. this.animations = new Array();
  26959. /**
  26960. * An event triggered when the texture is disposed.
  26961. */
  26962. this.onDisposeObservable = new BABYLON.Observable();
  26963. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26964. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26965. if (this._scene) {
  26966. this._scene.textures.push(this);
  26967. }
  26968. this._uid = null;
  26969. }
  26970. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26971. get: function () {
  26972. return this._hasAlpha;
  26973. },
  26974. set: function (value) {
  26975. if (this._hasAlpha === value) {
  26976. return;
  26977. }
  26978. this._hasAlpha = value;
  26979. if (this._scene) {
  26980. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26981. }
  26982. },
  26983. enumerable: true,
  26984. configurable: true
  26985. });
  26986. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26987. get: function () {
  26988. return this._coordinatesMode;
  26989. },
  26990. /**
  26991. * How a texture is mapped.
  26992. *
  26993. * | Value | Type | Description |
  26994. * | ----- | ----------------------------------- | ----------- |
  26995. * | 0 | EXPLICIT_MODE | |
  26996. * | 1 | SPHERICAL_MODE | |
  26997. * | 2 | PLANAR_MODE | |
  26998. * | 3 | CUBIC_MODE | |
  26999. * | 4 | PROJECTION_MODE | |
  27000. * | 5 | SKYBOX_MODE | |
  27001. * | 6 | INVCUBIC_MODE | |
  27002. * | 7 | EQUIRECTANGULAR_MODE | |
  27003. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  27004. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  27005. */
  27006. set: function (value) {
  27007. if (this._coordinatesMode === value) {
  27008. return;
  27009. }
  27010. this._coordinatesMode = value;
  27011. if (this._scene) {
  27012. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27013. }
  27014. },
  27015. enumerable: true,
  27016. configurable: true
  27017. });
  27018. Object.defineProperty(BaseTexture.prototype, "uid", {
  27019. get: function () {
  27020. if (!this._uid) {
  27021. this._uid = BABYLON.Tools.RandomId();
  27022. }
  27023. return this._uid;
  27024. },
  27025. enumerable: true,
  27026. configurable: true
  27027. });
  27028. BaseTexture.prototype.toString = function () {
  27029. return this.name;
  27030. };
  27031. BaseTexture.prototype.getClassName = function () {
  27032. return "BaseTexture";
  27033. };
  27034. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27035. set: function (callback) {
  27036. if (this._onDisposeObserver) {
  27037. this.onDisposeObservable.remove(this._onDisposeObserver);
  27038. }
  27039. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27040. },
  27041. enumerable: true,
  27042. configurable: true
  27043. });
  27044. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27045. get: function () {
  27046. return true;
  27047. },
  27048. enumerable: true,
  27049. configurable: true
  27050. });
  27051. BaseTexture.prototype.getScene = function () {
  27052. return this._scene;
  27053. };
  27054. BaseTexture.prototype.getTextureMatrix = function () {
  27055. return BABYLON.Matrix.IdentityReadOnly;
  27056. };
  27057. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27058. return BABYLON.Matrix.IdentityReadOnly;
  27059. };
  27060. BaseTexture.prototype.getInternalTexture = function () {
  27061. return this._texture;
  27062. };
  27063. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27064. return !this.isBlocking || this.isReady();
  27065. };
  27066. BaseTexture.prototype.isReady = function () {
  27067. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27068. this.delayLoad();
  27069. return false;
  27070. }
  27071. if (this._texture) {
  27072. return this._texture.isReady;
  27073. }
  27074. return false;
  27075. };
  27076. BaseTexture.prototype.getSize = function () {
  27077. if (this._texture && this._texture.width) {
  27078. return new BABYLON.Size(this._texture.width, this._texture.height);
  27079. }
  27080. if (this._texture && this._texture._size) {
  27081. return new BABYLON.Size(this._texture._size, this._texture._size);
  27082. }
  27083. return BABYLON.Size.Zero();
  27084. };
  27085. BaseTexture.prototype.getBaseSize = function () {
  27086. if (!this.isReady() || !this._texture)
  27087. return BABYLON.Size.Zero();
  27088. if (this._texture._size) {
  27089. return new BABYLON.Size(this._texture._size, this._texture._size);
  27090. }
  27091. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27092. };
  27093. BaseTexture.prototype.scale = function (ratio) {
  27094. };
  27095. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27096. get: function () {
  27097. return false;
  27098. },
  27099. enumerable: true,
  27100. configurable: true
  27101. });
  27102. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27103. if (!this._scene) {
  27104. return null;
  27105. }
  27106. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27107. for (var index = 0; index < texturesCache.length; index++) {
  27108. var texturesCacheEntry = texturesCache[index];
  27109. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27110. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27111. texturesCacheEntry.incrementReferences();
  27112. return texturesCacheEntry;
  27113. }
  27114. }
  27115. }
  27116. return null;
  27117. };
  27118. BaseTexture.prototype._rebuild = function () {
  27119. };
  27120. BaseTexture.prototype.delayLoad = function () {
  27121. };
  27122. BaseTexture.prototype.clone = function () {
  27123. return null;
  27124. };
  27125. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27126. get: function () {
  27127. if (!this._texture) {
  27128. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27129. }
  27130. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27131. },
  27132. enumerable: true,
  27133. configurable: true
  27134. });
  27135. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27136. get: function () {
  27137. if (!this._texture) {
  27138. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27139. }
  27140. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27141. },
  27142. enumerable: true,
  27143. configurable: true
  27144. });
  27145. BaseTexture.prototype.readPixels = function (faceIndex) {
  27146. if (faceIndex === void 0) { faceIndex = 0; }
  27147. if (!this._texture) {
  27148. return null;
  27149. }
  27150. var size = this.getSize();
  27151. var scene = this.getScene();
  27152. if (!scene) {
  27153. return null;
  27154. }
  27155. var engine = scene.getEngine();
  27156. if (this._texture.isCube) {
  27157. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27158. }
  27159. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27160. };
  27161. BaseTexture.prototype.releaseInternalTexture = function () {
  27162. if (this._texture) {
  27163. this._texture.dispose();
  27164. this._texture = null;
  27165. }
  27166. };
  27167. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27168. get: function () {
  27169. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27170. return null;
  27171. }
  27172. if (!this._texture._sphericalPolynomial) {
  27173. this._texture._sphericalPolynomial =
  27174. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27175. }
  27176. return this._texture._sphericalPolynomial;
  27177. },
  27178. set: function (value) {
  27179. if (this._texture) {
  27180. this._texture._sphericalPolynomial = value;
  27181. }
  27182. },
  27183. enumerable: true,
  27184. configurable: true
  27185. });
  27186. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27187. get: function () {
  27188. if (this._texture) {
  27189. return this._texture._lodTextureHigh;
  27190. }
  27191. return null;
  27192. },
  27193. enumerable: true,
  27194. configurable: true
  27195. });
  27196. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27197. get: function () {
  27198. if (this._texture) {
  27199. return this._texture._lodTextureMid;
  27200. }
  27201. return null;
  27202. },
  27203. enumerable: true,
  27204. configurable: true
  27205. });
  27206. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27207. get: function () {
  27208. if (this._texture) {
  27209. return this._texture._lodTextureLow;
  27210. }
  27211. return null;
  27212. },
  27213. enumerable: true,
  27214. configurable: true
  27215. });
  27216. BaseTexture.prototype.dispose = function () {
  27217. if (!this._scene) {
  27218. return;
  27219. }
  27220. // Animations
  27221. this._scene.stopAnimation(this);
  27222. // Remove from scene
  27223. this._scene._removePendingData(this);
  27224. var index = this._scene.textures.indexOf(this);
  27225. if (index >= 0) {
  27226. this._scene.textures.splice(index, 1);
  27227. }
  27228. if (this._texture === undefined) {
  27229. return;
  27230. }
  27231. // Release
  27232. this.releaseInternalTexture();
  27233. // Callback
  27234. this.onDisposeObservable.notifyObservers(this);
  27235. this.onDisposeObservable.clear();
  27236. };
  27237. BaseTexture.prototype.serialize = function () {
  27238. if (!this.name) {
  27239. return null;
  27240. }
  27241. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27242. // Animations
  27243. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27244. return serializationObject;
  27245. };
  27246. BaseTexture.WhenAllReady = function (textures, callback) {
  27247. var numRemaining = textures.length;
  27248. if (numRemaining === 0) {
  27249. callback();
  27250. return;
  27251. }
  27252. var _loop_1 = function () {
  27253. texture = textures[i];
  27254. if (texture.isReady()) {
  27255. if (--numRemaining === 0) {
  27256. callback();
  27257. }
  27258. }
  27259. else {
  27260. onLoadObservable = texture.onLoadObservable;
  27261. var onLoadCallback_1 = function () {
  27262. onLoadObservable.removeCallback(onLoadCallback_1);
  27263. if (--numRemaining === 0) {
  27264. callback();
  27265. }
  27266. };
  27267. onLoadObservable.add(onLoadCallback_1);
  27268. }
  27269. };
  27270. var texture, onLoadObservable;
  27271. for (var i = 0; i < textures.length; i++) {
  27272. _loop_1();
  27273. }
  27274. };
  27275. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27276. __decorate([
  27277. BABYLON.serialize()
  27278. ], BaseTexture.prototype, "name", void 0);
  27279. __decorate([
  27280. BABYLON.serialize("hasAlpha")
  27281. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27282. __decorate([
  27283. BABYLON.serialize()
  27284. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27285. __decorate([
  27286. BABYLON.serialize()
  27287. ], BaseTexture.prototype, "level", void 0);
  27288. __decorate([
  27289. BABYLON.serialize()
  27290. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27291. __decorate([
  27292. BABYLON.serialize("coordinatesMode")
  27293. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27294. __decorate([
  27295. BABYLON.serialize()
  27296. ], BaseTexture.prototype, "wrapU", void 0);
  27297. __decorate([
  27298. BABYLON.serialize()
  27299. ], BaseTexture.prototype, "wrapV", void 0);
  27300. __decorate([
  27301. BABYLON.serialize()
  27302. ], BaseTexture.prototype, "wrapR", void 0);
  27303. __decorate([
  27304. BABYLON.serialize()
  27305. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27306. __decorate([
  27307. BABYLON.serialize()
  27308. ], BaseTexture.prototype, "isCube", void 0);
  27309. __decorate([
  27310. BABYLON.serialize()
  27311. ], BaseTexture.prototype, "is3D", void 0);
  27312. __decorate([
  27313. BABYLON.serialize()
  27314. ], BaseTexture.prototype, "gammaSpace", void 0);
  27315. __decorate([
  27316. BABYLON.serialize()
  27317. ], BaseTexture.prototype, "invertZ", void 0);
  27318. __decorate([
  27319. BABYLON.serialize()
  27320. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27321. __decorate([
  27322. BABYLON.serialize()
  27323. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27324. __decorate([
  27325. BABYLON.serialize()
  27326. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27327. __decorate([
  27328. BABYLON.serialize()
  27329. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27330. return BaseTexture;
  27331. }());
  27332. BABYLON.BaseTexture = BaseTexture;
  27333. })(BABYLON || (BABYLON = {}));
  27334. //# sourceMappingURL=babylon.baseTexture.js.map
  27335. "use strict";
  27336. var BABYLON;
  27337. (function (BABYLON) {
  27338. var Texture = /** @class */ (function (_super) {
  27339. __extends(Texture, _super);
  27340. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27341. if (noMipmap === void 0) { noMipmap = false; }
  27342. if (invertY === void 0) { invertY = true; }
  27343. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27344. if (onLoad === void 0) { onLoad = null; }
  27345. if (onError === void 0) { onError = null; }
  27346. if (buffer === void 0) { buffer = null; }
  27347. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27348. var _this = _super.call(this, scene) || this;
  27349. _this.uOffset = 0;
  27350. _this.vOffset = 0;
  27351. _this.uScale = 1.0;
  27352. _this.vScale = 1.0;
  27353. _this.uAng = 0;
  27354. _this.vAng = 0;
  27355. _this.wAng = 0;
  27356. _this._isBlocking = true;
  27357. _this.name = url || "";
  27358. _this.url = url;
  27359. _this._noMipmap = noMipmap;
  27360. _this._invertY = invertY;
  27361. _this._samplingMode = samplingMode;
  27362. _this._buffer = buffer;
  27363. _this._deleteBuffer = deleteBuffer;
  27364. if (format) {
  27365. _this._format = format;
  27366. }
  27367. scene = _this.getScene();
  27368. if (!scene) {
  27369. return _this;
  27370. }
  27371. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27372. var load = function () {
  27373. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27374. _this.onLoadObservable.notifyObservers(_this);
  27375. }
  27376. if (onLoad) {
  27377. onLoad();
  27378. }
  27379. if (!_this.isBlocking && scene) {
  27380. scene.resetCachedMaterial();
  27381. }
  27382. };
  27383. if (!_this.url) {
  27384. _this._delayedOnLoad = load;
  27385. _this._delayedOnError = onError;
  27386. return _this;
  27387. }
  27388. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27389. if (!_this._texture) {
  27390. if (!scene.useDelayedTextureLoading) {
  27391. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27392. if (deleteBuffer) {
  27393. delete _this._buffer;
  27394. }
  27395. }
  27396. else {
  27397. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27398. _this._delayedOnLoad = load;
  27399. _this._delayedOnError = onError;
  27400. }
  27401. }
  27402. else {
  27403. if (_this._texture.isReady) {
  27404. BABYLON.Tools.SetImmediate(function () { return load(); });
  27405. }
  27406. else {
  27407. _this._texture.onLoadedObservable.add(load);
  27408. }
  27409. }
  27410. return _this;
  27411. }
  27412. Object.defineProperty(Texture.prototype, "noMipmap", {
  27413. get: function () {
  27414. return this._noMipmap;
  27415. },
  27416. enumerable: true,
  27417. configurable: true
  27418. });
  27419. Object.defineProperty(Texture.prototype, "isBlocking", {
  27420. get: function () {
  27421. return this._isBlocking;
  27422. },
  27423. set: function (value) {
  27424. this._isBlocking = value;
  27425. },
  27426. enumerable: true,
  27427. configurable: true
  27428. });
  27429. Object.defineProperty(Texture.prototype, "samplingMode", {
  27430. get: function () {
  27431. return this._samplingMode;
  27432. },
  27433. enumerable: true,
  27434. configurable: true
  27435. });
  27436. Texture.prototype.updateURL = function (url) {
  27437. this.url = url;
  27438. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27439. this.delayLoad();
  27440. };
  27441. Texture.prototype.delayLoad = function () {
  27442. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27443. return;
  27444. }
  27445. var scene = this.getScene();
  27446. if (!scene) {
  27447. return;
  27448. }
  27449. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27450. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27451. if (!this._texture) {
  27452. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27453. if (this._deleteBuffer) {
  27454. delete this._buffer;
  27455. }
  27456. }
  27457. else {
  27458. if (this._delayedOnLoad) {
  27459. if (this._texture.isReady) {
  27460. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27461. }
  27462. else {
  27463. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27464. }
  27465. }
  27466. }
  27467. this._delayedOnLoad = null;
  27468. this._delayedOnError = null;
  27469. };
  27470. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27471. if (!this._texture) {
  27472. return;
  27473. }
  27474. var scene = this.getScene();
  27475. if (!scene) {
  27476. return;
  27477. }
  27478. this._samplingMode = samplingMode;
  27479. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27480. };
  27481. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27482. x *= this.uScale;
  27483. y *= this.vScale;
  27484. x -= 0.5 * this.uScale;
  27485. y -= 0.5 * this.vScale;
  27486. z -= 0.5;
  27487. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27488. t.x += 0.5 * this.uScale + this.uOffset;
  27489. t.y += 0.5 * this.vScale + this.vOffset;
  27490. t.z += 0.5;
  27491. };
  27492. Texture.prototype.getTextureMatrix = function () {
  27493. var _this = this;
  27494. if (this.uOffset === this._cachedUOffset &&
  27495. this.vOffset === this._cachedVOffset &&
  27496. this.uScale === this._cachedUScale &&
  27497. this.vScale === this._cachedVScale &&
  27498. this.uAng === this._cachedUAng &&
  27499. this.vAng === this._cachedVAng &&
  27500. this.wAng === this._cachedWAng) {
  27501. return this._cachedTextureMatrix;
  27502. }
  27503. this._cachedUOffset = this.uOffset;
  27504. this._cachedVOffset = this.vOffset;
  27505. this._cachedUScale = this.uScale;
  27506. this._cachedVScale = this.vScale;
  27507. this._cachedUAng = this.uAng;
  27508. this._cachedVAng = this.vAng;
  27509. this._cachedWAng = this.wAng;
  27510. if (!this._cachedTextureMatrix) {
  27511. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27512. this._rowGenerationMatrix = new BABYLON.Matrix();
  27513. this._t0 = BABYLON.Vector3.Zero();
  27514. this._t1 = BABYLON.Vector3.Zero();
  27515. this._t2 = BABYLON.Vector3.Zero();
  27516. }
  27517. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27518. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27519. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27520. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27521. this._t1.subtractInPlace(this._t0);
  27522. this._t2.subtractInPlace(this._t0);
  27523. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27524. this._cachedTextureMatrix.m[0] = this._t1.x;
  27525. this._cachedTextureMatrix.m[1] = this._t1.y;
  27526. this._cachedTextureMatrix.m[2] = this._t1.z;
  27527. this._cachedTextureMatrix.m[4] = this._t2.x;
  27528. this._cachedTextureMatrix.m[5] = this._t2.y;
  27529. this._cachedTextureMatrix.m[6] = this._t2.z;
  27530. this._cachedTextureMatrix.m[8] = this._t0.x;
  27531. this._cachedTextureMatrix.m[9] = this._t0.y;
  27532. this._cachedTextureMatrix.m[10] = this._t0.z;
  27533. var scene = this.getScene();
  27534. if (!scene) {
  27535. return this._cachedTextureMatrix;
  27536. }
  27537. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27538. return mat.hasTexture(_this);
  27539. });
  27540. return this._cachedTextureMatrix;
  27541. };
  27542. Texture.prototype.getReflectionTextureMatrix = function () {
  27543. var _this = this;
  27544. var scene = this.getScene();
  27545. if (!scene) {
  27546. return this._cachedTextureMatrix;
  27547. }
  27548. if (this.uOffset === this._cachedUOffset &&
  27549. this.vOffset === this._cachedVOffset &&
  27550. this.uScale === this._cachedUScale &&
  27551. this.vScale === this._cachedVScale &&
  27552. this.coordinatesMode === this._cachedCoordinatesMode) {
  27553. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27554. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27555. return this._cachedTextureMatrix;
  27556. }
  27557. }
  27558. else {
  27559. return this._cachedTextureMatrix;
  27560. }
  27561. }
  27562. if (!this._cachedTextureMatrix) {
  27563. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27564. }
  27565. if (!this._projectionModeMatrix) {
  27566. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27567. }
  27568. this._cachedUOffset = this.uOffset;
  27569. this._cachedVOffset = this.vOffset;
  27570. this._cachedUScale = this.uScale;
  27571. this._cachedVScale = this.vScale;
  27572. this._cachedCoordinatesMode = this.coordinatesMode;
  27573. switch (this.coordinatesMode) {
  27574. case Texture.PLANAR_MODE:
  27575. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27576. this._cachedTextureMatrix[0] = this.uScale;
  27577. this._cachedTextureMatrix[5] = this.vScale;
  27578. this._cachedTextureMatrix[12] = this.uOffset;
  27579. this._cachedTextureMatrix[13] = this.vOffset;
  27580. break;
  27581. case Texture.PROJECTION_MODE:
  27582. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27583. this._projectionModeMatrix.m[0] = 0.5;
  27584. this._projectionModeMatrix.m[5] = -0.5;
  27585. this._projectionModeMatrix.m[10] = 0.0;
  27586. this._projectionModeMatrix.m[12] = 0.5;
  27587. this._projectionModeMatrix.m[13] = 0.5;
  27588. this._projectionModeMatrix.m[14] = 1.0;
  27589. this._projectionModeMatrix.m[15] = 1.0;
  27590. var projectionMatrix = scene.getProjectionMatrix();
  27591. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27592. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27593. break;
  27594. default:
  27595. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27596. break;
  27597. }
  27598. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27599. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27600. });
  27601. return this._cachedTextureMatrix;
  27602. };
  27603. Texture.prototype.clone = function () {
  27604. var _this = this;
  27605. return BABYLON.SerializationHelper.Clone(function () {
  27606. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27607. }, this);
  27608. };
  27609. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27610. get: function () {
  27611. if (!this._onLoadObservable) {
  27612. this._onLoadObservable = new BABYLON.Observable();
  27613. }
  27614. return this._onLoadObservable;
  27615. },
  27616. enumerable: true,
  27617. configurable: true
  27618. });
  27619. Texture.prototype.serialize = function () {
  27620. var serializationObject = _super.prototype.serialize.call(this);
  27621. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27622. serializationObject.base64String = this._buffer;
  27623. serializationObject.name = serializationObject.name.replace("data:", "");
  27624. }
  27625. return serializationObject;
  27626. };
  27627. Texture.prototype.getClassName = function () {
  27628. return "Texture";
  27629. };
  27630. Texture.prototype.dispose = function () {
  27631. _super.prototype.dispose.call(this);
  27632. if (this.onLoadObservable) {
  27633. this.onLoadObservable.clear();
  27634. this._onLoadObservable = null;
  27635. }
  27636. this._delayedOnLoad = null;
  27637. this._delayedOnError = null;
  27638. };
  27639. // Statics
  27640. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27641. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27642. if (onLoad === void 0) { onLoad = null; }
  27643. if (onError === void 0) { onError = null; }
  27644. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27645. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27646. };
  27647. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27648. if (parsedTexture.customType) {
  27649. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27650. // Update Sampling Mode
  27651. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27652. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27653. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27654. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27655. }
  27656. }
  27657. return parsedCustomTexture;
  27658. }
  27659. if (parsedTexture.isCube) {
  27660. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27661. }
  27662. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27663. return null;
  27664. }
  27665. var texture = BABYLON.SerializationHelper.Parse(function () {
  27666. var generateMipMaps = true;
  27667. if (parsedTexture.noMipmap) {
  27668. generateMipMaps = false;
  27669. }
  27670. if (parsedTexture.mirrorPlane) {
  27671. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27672. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27673. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27674. return mirrorTexture;
  27675. }
  27676. else if (parsedTexture.isRenderTarget) {
  27677. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27678. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27679. return renderTargetTexture;
  27680. }
  27681. else {
  27682. var texture;
  27683. if (parsedTexture.base64String) {
  27684. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27685. }
  27686. else {
  27687. var url = rootUrl + parsedTexture.name;
  27688. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27689. url = parsedTexture.url;
  27690. }
  27691. texture = new Texture(url, scene, !generateMipMaps);
  27692. }
  27693. return texture;
  27694. }
  27695. }, parsedTexture, scene);
  27696. // Update Sampling Mode
  27697. if (parsedTexture.samplingMode) {
  27698. var sampling = parsedTexture.samplingMode;
  27699. if (texture._samplingMode !== sampling) {
  27700. texture.updateSamplingMode(sampling);
  27701. }
  27702. }
  27703. // Animations
  27704. if (parsedTexture.animations) {
  27705. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27706. var parsedAnimation = parsedTexture.animations[animationIndex];
  27707. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27708. }
  27709. }
  27710. return texture;
  27711. };
  27712. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27713. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27714. if (noMipmap === void 0) { noMipmap = false; }
  27715. if (invertY === void 0) { invertY = true; }
  27716. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27717. if (onLoad === void 0) { onLoad = null; }
  27718. if (onError === void 0) { onError = null; }
  27719. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27720. if (name.substr(0, 5) !== "data:") {
  27721. name = "data:" + name;
  27722. }
  27723. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27724. };
  27725. // Constants
  27726. Texture.NEAREST_SAMPLINGMODE = 1;
  27727. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27728. Texture.BILINEAR_SAMPLINGMODE = 2;
  27729. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27730. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27731. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27732. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27733. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27734. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27735. Texture.NEAREST_LINEAR = 7;
  27736. Texture.NEAREST_NEAREST = 8;
  27737. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27738. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27739. Texture.LINEAR_LINEAR = 11;
  27740. Texture.LINEAR_NEAREST = 12;
  27741. Texture.EXPLICIT_MODE = 0;
  27742. Texture.SPHERICAL_MODE = 1;
  27743. Texture.PLANAR_MODE = 2;
  27744. Texture.CUBIC_MODE = 3;
  27745. Texture.PROJECTION_MODE = 4;
  27746. Texture.SKYBOX_MODE = 5;
  27747. Texture.INVCUBIC_MODE = 6;
  27748. Texture.EQUIRECTANGULAR_MODE = 7;
  27749. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27750. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27751. Texture.CLAMP_ADDRESSMODE = 0;
  27752. Texture.WRAP_ADDRESSMODE = 1;
  27753. Texture.MIRROR_ADDRESSMODE = 2;
  27754. /**
  27755. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27756. */
  27757. Texture.UseSerializedUrlIfAny = false;
  27758. __decorate([
  27759. BABYLON.serialize()
  27760. ], Texture.prototype, "url", void 0);
  27761. __decorate([
  27762. BABYLON.serialize()
  27763. ], Texture.prototype, "uOffset", void 0);
  27764. __decorate([
  27765. BABYLON.serialize()
  27766. ], Texture.prototype, "vOffset", void 0);
  27767. __decorate([
  27768. BABYLON.serialize()
  27769. ], Texture.prototype, "uScale", void 0);
  27770. __decorate([
  27771. BABYLON.serialize()
  27772. ], Texture.prototype, "vScale", void 0);
  27773. __decorate([
  27774. BABYLON.serialize()
  27775. ], Texture.prototype, "uAng", void 0);
  27776. __decorate([
  27777. BABYLON.serialize()
  27778. ], Texture.prototype, "vAng", void 0);
  27779. __decorate([
  27780. BABYLON.serialize()
  27781. ], Texture.prototype, "wAng", void 0);
  27782. __decorate([
  27783. BABYLON.serialize()
  27784. ], Texture.prototype, "isBlocking", null);
  27785. return Texture;
  27786. }(BABYLON.BaseTexture));
  27787. BABYLON.Texture = Texture;
  27788. })(BABYLON || (BABYLON = {}));
  27789. //# sourceMappingURL=babylon.texture.js.map
  27790. "use strict";
  27791. var BABYLON;
  27792. (function (BABYLON) {
  27793. var _InstancesBatch = /** @class */ (function () {
  27794. function _InstancesBatch() {
  27795. this.mustReturn = false;
  27796. this.visibleInstances = new Array();
  27797. this.renderSelf = new Array();
  27798. }
  27799. return _InstancesBatch;
  27800. }());
  27801. BABYLON._InstancesBatch = _InstancesBatch;
  27802. var Mesh = /** @class */ (function (_super) {
  27803. __extends(Mesh, _super);
  27804. /**
  27805. * @constructor
  27806. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27807. * @param {Scene} scene The scene to add this mesh to.
  27808. * @param {Node} parent The parent of this mesh, if it has one
  27809. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27810. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27811. * When false, achieved by calling a clone(), also passing False.
  27812. * This will make creation of children, recursive.
  27813. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27814. */
  27815. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27816. if (scene === void 0) { scene = null; }
  27817. if (parent === void 0) { parent = null; }
  27818. if (source === void 0) { source = null; }
  27819. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27820. var _this = _super.call(this, name, scene) || this;
  27821. // Events
  27822. /**
  27823. * An event triggered before rendering the mesh
  27824. */
  27825. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27826. /**
  27827. * An event triggered after rendering the mesh
  27828. */
  27829. _this.onAfterRenderObservable = new BABYLON.Observable();
  27830. /**
  27831. * An event triggered before drawing the mesh
  27832. */
  27833. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27834. // Members
  27835. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27836. _this.instances = new Array();
  27837. _this._LODLevels = new Array();
  27838. _this._visibleInstances = {};
  27839. _this._renderIdForInstances = new Array();
  27840. _this._batchCache = new _InstancesBatch();
  27841. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27842. // Use by builder only to know what orientation were the mesh build in.
  27843. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27844. _this.overrideMaterialSideOrientation = null;
  27845. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27846. // Will be used to save a source mesh reference, If any
  27847. _this._source = null;
  27848. scene = _this.getScene();
  27849. if (source) {
  27850. // Source mesh
  27851. _this._source = source;
  27852. // Geometry
  27853. if (source._geometry) {
  27854. source._geometry.applyToMesh(_this);
  27855. }
  27856. // Deep copy
  27857. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27858. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27859. // Metadata
  27860. if (source.metadata && source.metadata.clone) {
  27861. _this.metadata = source.metadata.clone();
  27862. }
  27863. else {
  27864. _this.metadata = source.metadata;
  27865. }
  27866. // Tags
  27867. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27868. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27869. }
  27870. // Parent
  27871. _this.parent = source.parent;
  27872. // Pivot
  27873. _this.setPivotMatrix(source.getPivotMatrix());
  27874. _this.id = name + "." + source.id;
  27875. // Material
  27876. _this.material = source.material;
  27877. var index;
  27878. if (!doNotCloneChildren) {
  27879. // Children
  27880. var directDescendants = source.getDescendants(true);
  27881. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27882. var child = directDescendants[index_1];
  27883. if (child.clone) {
  27884. child.clone(name + "." + child.name, _this);
  27885. }
  27886. }
  27887. }
  27888. // Physics clone
  27889. var physicsEngine = _this.getScene().getPhysicsEngine();
  27890. if (clonePhysicsImpostor && physicsEngine) {
  27891. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27892. if (impostor) {
  27893. _this.physicsImpostor = impostor.clone(_this);
  27894. }
  27895. }
  27896. // Particles
  27897. for (index = 0; index < scene.particleSystems.length; index++) {
  27898. var system = scene.particleSystems[index];
  27899. if (system.emitter === source) {
  27900. system.clone(system.name, _this);
  27901. }
  27902. }
  27903. _this.computeWorldMatrix(true);
  27904. }
  27905. // Parent
  27906. if (parent !== null) {
  27907. _this.parent = parent;
  27908. }
  27909. return _this;
  27910. }
  27911. Object.defineProperty(Mesh, "FRONTSIDE", {
  27912. /**
  27913. * Mesh side orientation : usually the external or front surface
  27914. */
  27915. get: function () {
  27916. return Mesh._FRONTSIDE;
  27917. },
  27918. enumerable: true,
  27919. configurable: true
  27920. });
  27921. Object.defineProperty(Mesh, "BACKSIDE", {
  27922. /**
  27923. * Mesh side orientation : usually the internal or back surface
  27924. */
  27925. get: function () {
  27926. return Mesh._BACKSIDE;
  27927. },
  27928. enumerable: true,
  27929. configurable: true
  27930. });
  27931. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27932. /**
  27933. * Mesh side orientation : both internal and external or front and back surfaces
  27934. */
  27935. get: function () {
  27936. return Mesh._DOUBLESIDE;
  27937. },
  27938. enumerable: true,
  27939. configurable: true
  27940. });
  27941. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27942. /**
  27943. * Mesh side orientation : by default, `FRONTSIDE`
  27944. */
  27945. get: function () {
  27946. return Mesh._DEFAULTSIDE;
  27947. },
  27948. enumerable: true,
  27949. configurable: true
  27950. });
  27951. Object.defineProperty(Mesh, "NO_CAP", {
  27952. /**
  27953. * Mesh cap setting : no cap
  27954. */
  27955. get: function () {
  27956. return Mesh._NO_CAP;
  27957. },
  27958. enumerable: true,
  27959. configurable: true
  27960. });
  27961. Object.defineProperty(Mesh, "CAP_START", {
  27962. /**
  27963. * Mesh cap setting : one cap at the beginning of the mesh
  27964. */
  27965. get: function () {
  27966. return Mesh._CAP_START;
  27967. },
  27968. enumerable: true,
  27969. configurable: true
  27970. });
  27971. Object.defineProperty(Mesh, "CAP_END", {
  27972. /**
  27973. * Mesh cap setting : one cap at the end of the mesh
  27974. */
  27975. get: function () {
  27976. return Mesh._CAP_END;
  27977. },
  27978. enumerable: true,
  27979. configurable: true
  27980. });
  27981. Object.defineProperty(Mesh, "CAP_ALL", {
  27982. /**
  27983. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27984. */
  27985. get: function () {
  27986. return Mesh._CAP_ALL;
  27987. },
  27988. enumerable: true,
  27989. configurable: true
  27990. });
  27991. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27992. set: function (callback) {
  27993. if (this._onBeforeDrawObserver) {
  27994. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27995. }
  27996. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27997. },
  27998. enumerable: true,
  27999. configurable: true
  28000. });
  28001. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  28002. get: function () {
  28003. return this._morphTargetManager;
  28004. },
  28005. set: function (value) {
  28006. if (this._morphTargetManager === value) {
  28007. return;
  28008. }
  28009. this._morphTargetManager = value;
  28010. this._syncGeometryWithMorphTargetManager();
  28011. },
  28012. enumerable: true,
  28013. configurable: true
  28014. });
  28015. Object.defineProperty(Mesh.prototype, "source", {
  28016. get: function () {
  28017. return this._source;
  28018. },
  28019. enumerable: true,
  28020. configurable: true
  28021. });
  28022. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  28023. get: function () {
  28024. return this._unIndexed;
  28025. },
  28026. set: function (value) {
  28027. if (this._unIndexed !== value) {
  28028. this._unIndexed = value;
  28029. this._markSubMeshesAsAttributesDirty();
  28030. }
  28031. },
  28032. enumerable: true,
  28033. configurable: true
  28034. });
  28035. // Methods
  28036. /**
  28037. * Returns the string "Mesh".
  28038. */
  28039. Mesh.prototype.getClassName = function () {
  28040. return "Mesh";
  28041. };
  28042. /**
  28043. * Returns a string.
  28044. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28045. */
  28046. Mesh.prototype.toString = function (fullDetails) {
  28047. var ret = _super.prototype.toString.call(this, fullDetails);
  28048. ret += ", n vertices: " + this.getTotalVertices();
  28049. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28050. if (this.animations) {
  28051. for (var i = 0; i < this.animations.length; i++) {
  28052. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28053. }
  28054. }
  28055. if (fullDetails) {
  28056. if (this._geometry) {
  28057. var ib = this.getIndices();
  28058. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28059. if (vb && ib) {
  28060. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28061. }
  28062. }
  28063. else {
  28064. ret += ", flat shading: UNKNOWN";
  28065. }
  28066. }
  28067. return ret;
  28068. };
  28069. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28070. /**
  28071. * True if the mesh has some Levels Of Details (LOD).
  28072. * Returns a boolean.
  28073. */
  28074. get: function () {
  28075. return this._LODLevels.length > 0;
  28076. },
  28077. enumerable: true,
  28078. configurable: true
  28079. });
  28080. /**
  28081. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28082. * @returns an array of {BABYLON.MeshLODLevel}
  28083. */
  28084. Mesh.prototype.getLODLevels = function () {
  28085. return this._LODLevels;
  28086. };
  28087. Mesh.prototype._sortLODLevels = function () {
  28088. this._LODLevels.sort(function (a, b) {
  28089. if (a.distance < b.distance) {
  28090. return 1;
  28091. }
  28092. if (a.distance > b.distance) {
  28093. return -1;
  28094. }
  28095. return 0;
  28096. });
  28097. };
  28098. /**
  28099. * Add a mesh as LOD level triggered at the given distance.
  28100. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28101. * @param {number} distance The distance from the center of the object to show this level
  28102. * @param {Mesh} mesh The mesh to be added as LOD level
  28103. * @return {Mesh} This mesh (for chaining)
  28104. */
  28105. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28106. if (mesh && mesh._masterMesh) {
  28107. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28108. return this;
  28109. }
  28110. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28111. this._LODLevels.push(level);
  28112. if (mesh) {
  28113. mesh._masterMesh = this;
  28114. }
  28115. this._sortLODLevels();
  28116. return this;
  28117. };
  28118. /**
  28119. * Returns the LOD level mesh at the passed distance or null if not found.
  28120. * It is related to the method `addLODLevel(distance, mesh)`.
  28121. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28122. * Returns an object Mesh or `null`.
  28123. */
  28124. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28125. for (var index = 0; index < this._LODLevels.length; index++) {
  28126. var level = this._LODLevels[index];
  28127. if (level.distance === distance) {
  28128. return level.mesh;
  28129. }
  28130. }
  28131. return null;
  28132. };
  28133. /**
  28134. * Remove a mesh from the LOD array
  28135. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28136. * @param {Mesh} mesh The mesh to be removed.
  28137. * @return {Mesh} This mesh (for chaining)
  28138. */
  28139. Mesh.prototype.removeLODLevel = function (mesh) {
  28140. for (var index = 0; index < this._LODLevels.length; index++) {
  28141. if (this._LODLevels[index].mesh === mesh) {
  28142. this._LODLevels.splice(index, 1);
  28143. if (mesh) {
  28144. mesh._masterMesh = null;
  28145. }
  28146. }
  28147. }
  28148. this._sortLODLevels();
  28149. return this;
  28150. };
  28151. /**
  28152. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28153. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28154. */
  28155. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28156. if (!this._LODLevels || this._LODLevels.length === 0) {
  28157. return this;
  28158. }
  28159. var bSphere;
  28160. if (boundingSphere) {
  28161. bSphere = boundingSphere;
  28162. }
  28163. else {
  28164. var boundingInfo = this.getBoundingInfo();
  28165. bSphere = boundingInfo.boundingSphere;
  28166. }
  28167. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28168. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28169. if (this.onLODLevelSelection) {
  28170. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28171. }
  28172. return this;
  28173. }
  28174. for (var index = 0; index < this._LODLevels.length; index++) {
  28175. var level = this._LODLevels[index];
  28176. if (level.distance < distanceToCamera) {
  28177. if (level.mesh) {
  28178. level.mesh._preActivate();
  28179. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28180. }
  28181. if (this.onLODLevelSelection) {
  28182. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28183. }
  28184. return level.mesh;
  28185. }
  28186. }
  28187. if (this.onLODLevelSelection) {
  28188. this.onLODLevelSelection(distanceToCamera, this, this);
  28189. }
  28190. return this;
  28191. };
  28192. Object.defineProperty(Mesh.prototype, "geometry", {
  28193. /**
  28194. * Returns the mesh internal Geometry object.
  28195. */
  28196. get: function () {
  28197. return this._geometry;
  28198. },
  28199. enumerable: true,
  28200. configurable: true
  28201. });
  28202. /**
  28203. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28204. */
  28205. Mesh.prototype.getTotalVertices = function () {
  28206. if (this._geometry === null || this._geometry === undefined) {
  28207. return 0;
  28208. }
  28209. return this._geometry.getTotalVertices();
  28210. };
  28211. /**
  28212. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28213. * 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.
  28214. * You can force the copy with forceCopy === true
  28215. * Returns null if the mesh has no geometry or no vertex buffer.
  28216. * Possible `kind` values :
  28217. * - BABYLON.VertexBuffer.PositionKind
  28218. * - BABYLON.VertexBuffer.UVKind
  28219. * - BABYLON.VertexBuffer.UV2Kind
  28220. * - BABYLON.VertexBuffer.UV3Kind
  28221. * - BABYLON.VertexBuffer.UV4Kind
  28222. * - BABYLON.VertexBuffer.UV5Kind
  28223. * - BABYLON.VertexBuffer.UV6Kind
  28224. * - BABYLON.VertexBuffer.ColorKind
  28225. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28226. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28227. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28228. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28229. */
  28230. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28231. if (!this._geometry) {
  28232. return null;
  28233. }
  28234. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28235. };
  28236. /**
  28237. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28238. * Returns `null` if the mesh has no geometry.
  28239. * Possible `kind` values :
  28240. * - BABYLON.VertexBuffer.PositionKind
  28241. * - BABYLON.VertexBuffer.UVKind
  28242. * - BABYLON.VertexBuffer.UV2Kind
  28243. * - BABYLON.VertexBuffer.UV3Kind
  28244. * - BABYLON.VertexBuffer.UV4Kind
  28245. * - BABYLON.VertexBuffer.UV5Kind
  28246. * - BABYLON.VertexBuffer.UV6Kind
  28247. * - BABYLON.VertexBuffer.ColorKind
  28248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28252. */
  28253. Mesh.prototype.getVertexBuffer = function (kind) {
  28254. if (!this._geometry) {
  28255. return null;
  28256. }
  28257. return this._geometry.getVertexBuffer(kind);
  28258. };
  28259. /**
  28260. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28261. * Possible `kind` values :
  28262. * - BABYLON.VertexBuffer.PositionKind
  28263. * - BABYLON.VertexBuffer.UVKind
  28264. * - BABYLON.VertexBuffer.UV2Kind
  28265. * - BABYLON.VertexBuffer.UV3Kind
  28266. * - BABYLON.VertexBuffer.UV4Kind
  28267. * - BABYLON.VertexBuffer.UV5Kind
  28268. * - BABYLON.VertexBuffer.UV6Kind
  28269. * - BABYLON.VertexBuffer.ColorKind
  28270. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28271. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28272. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28273. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28274. */
  28275. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28276. if (!this._geometry) {
  28277. if (this._delayInfo) {
  28278. return this._delayInfo.indexOf(kind) !== -1;
  28279. }
  28280. return false;
  28281. }
  28282. return this._geometry.isVerticesDataPresent(kind);
  28283. };
  28284. /**
  28285. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28286. * Possible `kind` values :
  28287. * - BABYLON.VertexBuffer.PositionKind
  28288. * - BABYLON.VertexBuffer.UVKind
  28289. * - BABYLON.VertexBuffer.UV2Kind
  28290. * - BABYLON.VertexBuffer.UV3Kind
  28291. * - BABYLON.VertexBuffer.UV4Kind
  28292. * - BABYLON.VertexBuffer.UV5Kind
  28293. * - BABYLON.VertexBuffer.UV6Kind
  28294. * - BABYLON.VertexBuffer.ColorKind
  28295. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28296. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28297. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28298. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28299. */
  28300. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28301. if (!this._geometry) {
  28302. if (this._delayInfo) {
  28303. return this._delayInfo.indexOf(kind) !== -1;
  28304. }
  28305. return false;
  28306. }
  28307. return this._geometry.isVertexBufferUpdatable(kind);
  28308. };
  28309. /**
  28310. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28311. * Possible `kind` values :
  28312. * - BABYLON.VertexBuffer.PositionKind
  28313. * - BABYLON.VertexBuffer.UVKind
  28314. * - BABYLON.VertexBuffer.UV2Kind
  28315. * - BABYLON.VertexBuffer.UV3Kind
  28316. * - BABYLON.VertexBuffer.UV4Kind
  28317. * - BABYLON.VertexBuffer.UV5Kind
  28318. * - BABYLON.VertexBuffer.UV6Kind
  28319. * - BABYLON.VertexBuffer.ColorKind
  28320. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28321. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28322. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28323. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28324. */
  28325. Mesh.prototype.getVerticesDataKinds = function () {
  28326. if (!this._geometry) {
  28327. var result = new Array();
  28328. if (this._delayInfo) {
  28329. this._delayInfo.forEach(function (kind, index, array) {
  28330. result.push(kind);
  28331. });
  28332. }
  28333. return result;
  28334. }
  28335. return this._geometry.getVerticesDataKinds();
  28336. };
  28337. /**
  28338. * Returns a positive integer : the total number of indices in this mesh geometry.
  28339. * Returns zero if the mesh has no geometry.
  28340. */
  28341. Mesh.prototype.getTotalIndices = function () {
  28342. if (!this._geometry) {
  28343. return 0;
  28344. }
  28345. return this._geometry.getTotalIndices();
  28346. };
  28347. /**
  28348. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28349. * 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.
  28350. * Returns an empty array if the mesh has no geometry.
  28351. */
  28352. Mesh.prototype.getIndices = function (copyWhenShared) {
  28353. if (!this._geometry) {
  28354. return [];
  28355. }
  28356. return this._geometry.getIndices(copyWhenShared);
  28357. };
  28358. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28359. get: function () {
  28360. return this._masterMesh !== null && this._masterMesh !== undefined;
  28361. },
  28362. enumerable: true,
  28363. configurable: true
  28364. });
  28365. /**
  28366. * Determine if the current mesh is ready to be rendered
  28367. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28368. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28369. * @returns true if all associated assets are ready (material, textures, shaders)
  28370. */
  28371. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28372. if (completeCheck === void 0) { completeCheck = false; }
  28373. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28374. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28375. return false;
  28376. }
  28377. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28378. return false;
  28379. }
  28380. if (!this.subMeshes || this.subMeshes.length === 0) {
  28381. return true;
  28382. }
  28383. if (!completeCheck) {
  28384. return true;
  28385. }
  28386. var engine = this.getEngine();
  28387. var scene = this.getScene();
  28388. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28389. this.computeWorldMatrix();
  28390. var mat = this.material || scene.defaultMaterial;
  28391. if (mat) {
  28392. if (mat.storeEffectOnSubMeshes) {
  28393. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28394. var subMesh = _a[_i];
  28395. var effectiveMaterial = subMesh.getMaterial();
  28396. if (effectiveMaterial) {
  28397. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28398. return false;
  28399. }
  28400. }
  28401. }
  28402. }
  28403. else {
  28404. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28405. return false;
  28406. }
  28407. }
  28408. }
  28409. // Shadows
  28410. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28411. var light = _c[_b];
  28412. var generator = light.getShadowGenerator();
  28413. if (generator) {
  28414. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28415. var subMesh = _e[_d];
  28416. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28417. return false;
  28418. }
  28419. }
  28420. }
  28421. }
  28422. // LOD
  28423. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28424. var lod = _g[_f];
  28425. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28426. return false;
  28427. }
  28428. }
  28429. return true;
  28430. };
  28431. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28432. /**
  28433. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28434. * This property is pertinent only for updatable parametric shapes.
  28435. */
  28436. get: function () {
  28437. return this._areNormalsFrozen;
  28438. },
  28439. enumerable: true,
  28440. configurable: true
  28441. });
  28442. /**
  28443. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28444. * It has no effect at all on other shapes.
  28445. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28446. * Returns the Mesh.
  28447. */
  28448. Mesh.prototype.freezeNormals = function () {
  28449. this._areNormalsFrozen = true;
  28450. return this;
  28451. };
  28452. /**
  28453. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28454. * It has no effect at all on other shapes.
  28455. * It reactivates the mesh normals computation if it was previously frozen.
  28456. * Returns the Mesh.
  28457. */
  28458. Mesh.prototype.unfreezeNormals = function () {
  28459. this._areNormalsFrozen = false;
  28460. return this;
  28461. };
  28462. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28463. /**
  28464. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28465. */
  28466. set: function (count) {
  28467. this._overridenInstanceCount = count;
  28468. },
  28469. enumerable: true,
  28470. configurable: true
  28471. });
  28472. // Methods
  28473. Mesh.prototype._preActivate = function () {
  28474. var sceneRenderId = this.getScene().getRenderId();
  28475. if (this._preActivateId === sceneRenderId) {
  28476. return this;
  28477. }
  28478. this._preActivateId = sceneRenderId;
  28479. this._visibleInstances = null;
  28480. return this;
  28481. };
  28482. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28483. if (this._visibleInstances) {
  28484. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28485. }
  28486. return this;
  28487. };
  28488. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28489. if (!this._visibleInstances) {
  28490. this._visibleInstances = {};
  28491. this._visibleInstances.defaultRenderId = renderId;
  28492. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28493. }
  28494. if (!this._visibleInstances[renderId]) {
  28495. this._visibleInstances[renderId] = new Array();
  28496. }
  28497. this._visibleInstances[renderId].push(instance);
  28498. return this;
  28499. };
  28500. /**
  28501. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28502. * This means the mesh underlying bounding box and sphere are recomputed.
  28503. * Returns the Mesh.
  28504. */
  28505. Mesh.prototype.refreshBoundingInfo = function () {
  28506. return this._refreshBoundingInfo(false);
  28507. };
  28508. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28509. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28510. return this;
  28511. }
  28512. var data = this._getPositionData(applySkeleton);
  28513. if (data) {
  28514. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28515. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28516. }
  28517. if (this.subMeshes) {
  28518. for (var index = 0; index < this.subMeshes.length; index++) {
  28519. this.subMeshes[index].refreshBoundingInfo();
  28520. }
  28521. }
  28522. this._updateBoundingInfo();
  28523. return this;
  28524. };
  28525. Mesh.prototype._getPositionData = function (applySkeleton) {
  28526. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28527. if (data && applySkeleton && this.skeleton) {
  28528. data = BABYLON.Tools.Slice(data);
  28529. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28530. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28531. if (matricesWeightsData && matricesIndicesData) {
  28532. var needExtras = this.numBoneInfluencers > 4;
  28533. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28534. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28535. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28536. var tempVector = BABYLON.Tmp.Vector3[0];
  28537. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28538. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28539. var matWeightIdx = 0;
  28540. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28541. finalMatrix.reset();
  28542. var inf;
  28543. var weight;
  28544. for (inf = 0; inf < 4; inf++) {
  28545. weight = matricesWeightsData[matWeightIdx + inf];
  28546. if (weight <= 0)
  28547. break;
  28548. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28549. finalMatrix.addToSelf(tempMatrix);
  28550. }
  28551. if (needExtras) {
  28552. for (inf = 0; inf < 4; inf++) {
  28553. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28554. if (weight <= 0)
  28555. break;
  28556. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28557. finalMatrix.addToSelf(tempMatrix);
  28558. }
  28559. }
  28560. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28561. tempVector.toArray(data, index);
  28562. }
  28563. }
  28564. }
  28565. return data;
  28566. };
  28567. Mesh.prototype._createGlobalSubMesh = function (force) {
  28568. var totalVertices = this.getTotalVertices();
  28569. if (!totalVertices || !this.getIndices()) {
  28570. return null;
  28571. }
  28572. // Check if we need to recreate the submeshes
  28573. if (this.subMeshes && this.subMeshes.length > 0) {
  28574. var ib = this.getIndices();
  28575. if (!ib) {
  28576. return null;
  28577. }
  28578. var totalIndices = ib.length;
  28579. var needToRecreate = false;
  28580. if (force) {
  28581. needToRecreate = true;
  28582. }
  28583. else {
  28584. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28585. var submesh = _a[_i];
  28586. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28587. needToRecreate = true;
  28588. break;
  28589. }
  28590. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28591. needToRecreate = true;
  28592. break;
  28593. }
  28594. }
  28595. }
  28596. if (!needToRecreate) {
  28597. return this.subMeshes[0];
  28598. }
  28599. }
  28600. this.releaseSubMeshes();
  28601. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28602. };
  28603. Mesh.prototype.subdivide = function (count) {
  28604. if (count < 1) {
  28605. return;
  28606. }
  28607. var totalIndices = this.getTotalIndices();
  28608. var subdivisionSize = (totalIndices / count) | 0;
  28609. var offset = 0;
  28610. // Ensure that subdivisionSize is a multiple of 3
  28611. while (subdivisionSize % 3 !== 0) {
  28612. subdivisionSize++;
  28613. }
  28614. this.releaseSubMeshes();
  28615. for (var index = 0; index < count; index++) {
  28616. if (offset >= totalIndices) {
  28617. break;
  28618. }
  28619. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28620. offset += subdivisionSize;
  28621. }
  28622. this.synchronizeInstances();
  28623. };
  28624. /**
  28625. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28626. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28627. * The `data` are either a numeric array either a Float32Array.
  28628. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28629. * 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).
  28630. * Note that a new underlying VertexBuffer object is created each call.
  28631. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28632. *
  28633. * Possible `kind` values :
  28634. * - BABYLON.VertexBuffer.PositionKind
  28635. * - BABYLON.VertexBuffer.UVKind
  28636. * - BABYLON.VertexBuffer.UV2Kind
  28637. * - BABYLON.VertexBuffer.UV3Kind
  28638. * - BABYLON.VertexBuffer.UV4Kind
  28639. * - BABYLON.VertexBuffer.UV5Kind
  28640. * - BABYLON.VertexBuffer.UV6Kind
  28641. * - BABYLON.VertexBuffer.ColorKind
  28642. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28643. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28644. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28645. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28646. *
  28647. * Returns the Mesh.
  28648. */
  28649. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28650. if (updatable === void 0) { updatable = false; }
  28651. if (!this._geometry) {
  28652. var vertexData = new BABYLON.VertexData();
  28653. vertexData.set(data, kind);
  28654. var scene = this.getScene();
  28655. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28656. }
  28657. else {
  28658. this._geometry.setVerticesData(kind, data, updatable, stride);
  28659. }
  28660. return this;
  28661. };
  28662. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28663. if (updatable === void 0) { updatable = true; }
  28664. var vb = this.getVertexBuffer(kind);
  28665. if (!vb || vb.isUpdatable() === updatable) {
  28666. return;
  28667. }
  28668. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28669. };
  28670. /**
  28671. * Sets the mesh VertexBuffer.
  28672. * Returns the Mesh.
  28673. */
  28674. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28675. if (!this._geometry) {
  28676. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28677. }
  28678. this._geometry.setVerticesBuffer(buffer);
  28679. return this;
  28680. };
  28681. /**
  28682. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28683. * If the mesh has no geometry, it is simply returned as it is.
  28684. * The `data` are either a numeric array either a Float32Array.
  28685. * No new underlying VertexBuffer object is created.
  28686. * 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.
  28687. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28688. *
  28689. * Possible `kind` values :
  28690. * - BABYLON.VertexBuffer.PositionKind
  28691. * - BABYLON.VertexBuffer.UVKind
  28692. * - BABYLON.VertexBuffer.UV2Kind
  28693. * - BABYLON.VertexBuffer.UV3Kind
  28694. * - BABYLON.VertexBuffer.UV4Kind
  28695. * - BABYLON.VertexBuffer.UV5Kind
  28696. * - BABYLON.VertexBuffer.UV6Kind
  28697. * - BABYLON.VertexBuffer.ColorKind
  28698. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28699. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28700. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28701. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28702. *
  28703. * Returns the Mesh.
  28704. */
  28705. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28706. if (!this._geometry) {
  28707. return this;
  28708. }
  28709. if (!makeItUnique) {
  28710. this._geometry.updateVerticesData(kind, data, updateExtends);
  28711. }
  28712. else {
  28713. this.makeGeometryUnique();
  28714. this.updateVerticesData(kind, data, updateExtends, false);
  28715. }
  28716. return this;
  28717. };
  28718. /**
  28719. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28720. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28721. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28722. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28723. * Returns the Mesh.
  28724. */
  28725. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28726. if (computeNormals === void 0) { computeNormals = true; }
  28727. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28728. if (!positions) {
  28729. return this;
  28730. }
  28731. positionFunction(positions);
  28732. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28733. if (computeNormals) {
  28734. var indices = this.getIndices();
  28735. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28736. if (!normals) {
  28737. return this;
  28738. }
  28739. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28740. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28741. }
  28742. return this;
  28743. };
  28744. /**
  28745. * Creates a un-shared specific occurence of the geometry for the mesh.
  28746. * Returns the Mesh.
  28747. */
  28748. Mesh.prototype.makeGeometryUnique = function () {
  28749. if (!this._geometry) {
  28750. return this;
  28751. }
  28752. var oldGeometry = this._geometry;
  28753. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28754. oldGeometry.releaseForMesh(this, true);
  28755. geometry.applyToMesh(this);
  28756. return this;
  28757. };
  28758. /**
  28759. * Sets the mesh indices.
  28760. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28761. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28762. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28763. * This method creates a new index buffer each call.
  28764. * Returns the Mesh.
  28765. */
  28766. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28767. if (totalVertices === void 0) { totalVertices = null; }
  28768. if (updatable === void 0) { updatable = false; }
  28769. if (!this._geometry) {
  28770. var vertexData = new BABYLON.VertexData();
  28771. vertexData.indices = indices;
  28772. var scene = this.getScene();
  28773. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28774. }
  28775. else {
  28776. this._geometry.setIndices(indices, totalVertices, updatable);
  28777. }
  28778. return this;
  28779. };
  28780. /**
  28781. * Update the current index buffer
  28782. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28783. * Returns the Mesh.
  28784. */
  28785. Mesh.prototype.updateIndices = function (indices, offset) {
  28786. if (!this._geometry) {
  28787. return this;
  28788. }
  28789. this._geometry.updateIndices(indices, offset);
  28790. return this;
  28791. };
  28792. /**
  28793. * Invert the geometry to move from a right handed system to a left handed one.
  28794. * Returns the Mesh.
  28795. */
  28796. Mesh.prototype.toLeftHanded = function () {
  28797. if (!this._geometry) {
  28798. return this;
  28799. }
  28800. this._geometry.toLeftHanded();
  28801. return this;
  28802. };
  28803. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28804. if (!this._geometry) {
  28805. return this;
  28806. }
  28807. var engine = this.getScene().getEngine();
  28808. // Wireframe
  28809. var indexToBind;
  28810. if (this._unIndexed) {
  28811. indexToBind = null;
  28812. }
  28813. else {
  28814. switch (fillMode) {
  28815. case BABYLON.Material.PointFillMode:
  28816. indexToBind = null;
  28817. break;
  28818. case BABYLON.Material.WireFrameFillMode:
  28819. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28820. break;
  28821. default:
  28822. case BABYLON.Material.TriangleFillMode:
  28823. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28824. break;
  28825. }
  28826. }
  28827. // VBOs
  28828. this._geometry._bind(effect, indexToBind);
  28829. return this;
  28830. };
  28831. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28832. if (alternate === void 0) { alternate = false; }
  28833. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28834. return this;
  28835. }
  28836. this.onBeforeDrawObservable.notifyObservers(this);
  28837. var scene = this.getScene();
  28838. var engine = scene.getEngine();
  28839. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28840. // or triangles as points
  28841. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28842. }
  28843. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28844. // Triangles as wireframe
  28845. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28846. }
  28847. else {
  28848. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28849. }
  28850. if (scene._isAlternateRenderingEnabled && !alternate) {
  28851. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28852. if (!effect || !scene.activeCamera) {
  28853. return this;
  28854. }
  28855. scene._switchToAlternateCameraConfiguration(true);
  28856. this._effectiveMaterial.bindView(effect);
  28857. this._effectiveMaterial.bindViewProjection(effect);
  28858. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28859. this._draw(subMesh, fillMode, instancesCount, true);
  28860. engine.setViewport(scene.activeCamera.viewport);
  28861. scene._switchToAlternateCameraConfiguration(false);
  28862. this._effectiveMaterial.bindView(effect);
  28863. this._effectiveMaterial.bindViewProjection(effect);
  28864. }
  28865. return this;
  28866. };
  28867. /**
  28868. * Registers for this mesh a javascript function called just before the rendering process.
  28869. * This function is passed the current mesh.
  28870. * Return the Mesh.
  28871. */
  28872. Mesh.prototype.registerBeforeRender = function (func) {
  28873. this.onBeforeRenderObservable.add(func);
  28874. return this;
  28875. };
  28876. /**
  28877. * Disposes a previously registered javascript function called before the rendering.
  28878. * This function is passed the current mesh.
  28879. * Returns the Mesh.
  28880. */
  28881. Mesh.prototype.unregisterBeforeRender = function (func) {
  28882. this.onBeforeRenderObservable.removeCallback(func);
  28883. return this;
  28884. };
  28885. /**
  28886. * Registers for this mesh a javascript function called just after the rendering is complete.
  28887. * This function is passed the current mesh.
  28888. * Returns the Mesh.
  28889. */
  28890. Mesh.prototype.registerAfterRender = function (func) {
  28891. this.onAfterRenderObservable.add(func);
  28892. return this;
  28893. };
  28894. /**
  28895. * Disposes a previously registered javascript function called after the rendering.
  28896. * This function is passed the current mesh.
  28897. * Return the Mesh.
  28898. */
  28899. Mesh.prototype.unregisterAfterRender = function (func) {
  28900. this.onAfterRenderObservable.removeCallback(func);
  28901. return this;
  28902. };
  28903. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28904. var scene = this.getScene();
  28905. this._batchCache.mustReturn = false;
  28906. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28907. this._batchCache.visibleInstances[subMeshId] = null;
  28908. if (this._visibleInstances) {
  28909. var currentRenderId = scene.getRenderId();
  28910. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28911. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28912. var selfRenderId = this._renderId;
  28913. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28914. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28915. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28916. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28917. }
  28918. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28919. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28920. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28921. this._batchCache.mustReturn = true;
  28922. return this._batchCache;
  28923. }
  28924. if (currentRenderId !== selfRenderId) {
  28925. this._batchCache.renderSelf[subMeshId] = false;
  28926. }
  28927. }
  28928. this._renderIdForInstances[subMeshId] = currentRenderId;
  28929. }
  28930. return this._batchCache;
  28931. };
  28932. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28933. var visibleInstances = batch.visibleInstances[subMesh._id];
  28934. if (!visibleInstances) {
  28935. return this;
  28936. }
  28937. var matricesCount = visibleInstances.length + 1;
  28938. var bufferSize = matricesCount * 16 * 4;
  28939. var currentInstancesBufferSize = this._instancesBufferSize;
  28940. var instancesBuffer = this._instancesBuffer;
  28941. while (this._instancesBufferSize < bufferSize) {
  28942. this._instancesBufferSize *= 2;
  28943. }
  28944. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28945. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28946. }
  28947. var offset = 0;
  28948. var instancesCount = 0;
  28949. var world = this.getWorldMatrix();
  28950. if (batch.renderSelf[subMesh._id]) {
  28951. world.copyToArray(this._instancesData, offset);
  28952. offset += 16;
  28953. instancesCount++;
  28954. }
  28955. if (visibleInstances) {
  28956. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28957. var instance = visibleInstances[instanceIndex];
  28958. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28959. offset += 16;
  28960. instancesCount++;
  28961. }
  28962. }
  28963. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28964. if (instancesBuffer) {
  28965. instancesBuffer.dispose();
  28966. }
  28967. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28968. this._instancesBuffer = instancesBuffer;
  28969. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28970. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28971. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28972. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28973. }
  28974. else {
  28975. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28976. }
  28977. this._bind(subMesh, effect, fillMode);
  28978. this._draw(subMesh, fillMode, instancesCount);
  28979. engine.unbindInstanceAttributes();
  28980. return this;
  28981. };
  28982. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28983. var scene = this.getScene();
  28984. var engine = scene.getEngine();
  28985. if (hardwareInstancedRendering) {
  28986. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28987. }
  28988. else {
  28989. if (batch.renderSelf[subMesh._id]) {
  28990. // Draw
  28991. if (onBeforeDraw) {
  28992. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28993. }
  28994. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28995. }
  28996. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28997. if (visibleInstancesForSubMesh) {
  28998. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28999. var instance = visibleInstancesForSubMesh[instanceIndex];
  29000. // World
  29001. var world = instance.getWorldMatrix();
  29002. if (onBeforeDraw) {
  29003. onBeforeDraw(true, world, effectiveMaterial);
  29004. }
  29005. // Draw
  29006. this._draw(subMesh, fillMode);
  29007. }
  29008. }
  29009. }
  29010. return this;
  29011. };
  29012. /**
  29013. * Triggers the draw call for the mesh.
  29014. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  29015. * Returns the Mesh.
  29016. */
  29017. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  29018. this.checkOcclusionQuery();
  29019. if (this._isOccluded) {
  29020. return this;
  29021. }
  29022. var scene = this.getScene();
  29023. // Managing instances
  29024. var batch = this._getInstancesRenderList(subMesh._id);
  29025. if (batch.mustReturn) {
  29026. return this;
  29027. }
  29028. // Checking geometry state
  29029. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29030. return this;
  29031. }
  29032. this.onBeforeRenderObservable.notifyObservers(this);
  29033. var engine = scene.getEngine();
  29034. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29035. // Material
  29036. var material = subMesh.getMaterial();
  29037. if (!material) {
  29038. return this;
  29039. }
  29040. this._effectiveMaterial = material;
  29041. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29042. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29043. return this;
  29044. }
  29045. }
  29046. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29047. return this;
  29048. }
  29049. // Alpha mode
  29050. if (enableAlphaMode) {
  29051. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29052. }
  29053. // Outline - step 1
  29054. var savedDepthWrite = engine.getDepthWrite();
  29055. if (this.renderOutline) {
  29056. engine.setDepthWrite(false);
  29057. scene.getOutlineRenderer().render(subMesh, batch);
  29058. engine.setDepthWrite(savedDepthWrite);
  29059. }
  29060. var effect;
  29061. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29062. effect = subMesh.effect;
  29063. }
  29064. else {
  29065. effect = this._effectiveMaterial.getEffect();
  29066. }
  29067. if (!effect) {
  29068. return this;
  29069. }
  29070. var sideOrientation = this.overrideMaterialSideOrientation;
  29071. if (sideOrientation == null) {
  29072. sideOrientation = this._effectiveMaterial.sideOrientation;
  29073. if (this._getWorldMatrixDeterminant() < 0) {
  29074. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29075. }
  29076. }
  29077. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29078. if (this._effectiveMaterial.forceDepthWrite) {
  29079. engine.setDepthWrite(true);
  29080. }
  29081. // Bind
  29082. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29083. if (!hardwareInstancedRendering) {
  29084. this._bind(subMesh, effect, fillMode);
  29085. }
  29086. var world = this.getWorldMatrix();
  29087. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29088. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29089. }
  29090. else {
  29091. this._effectiveMaterial.bind(world, this);
  29092. }
  29093. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29094. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29095. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29096. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29097. }
  29098. // Draw
  29099. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29100. // Unbind
  29101. this._effectiveMaterial.unbind();
  29102. // Outline - step 2
  29103. if (this.renderOutline && savedDepthWrite) {
  29104. engine.setDepthWrite(true);
  29105. engine.setColorWrite(false);
  29106. scene.getOutlineRenderer().render(subMesh, batch);
  29107. engine.setColorWrite(true);
  29108. }
  29109. // Overlay
  29110. if (this.renderOverlay) {
  29111. var currentMode = engine.getAlphaMode();
  29112. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29113. scene.getOutlineRenderer().render(subMesh, batch, true);
  29114. engine.setAlphaMode(currentMode);
  29115. }
  29116. this.onAfterRenderObservable.notifyObservers(this);
  29117. return this;
  29118. };
  29119. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29120. if (isInstance && effectiveMaterial) {
  29121. effectiveMaterial.bindOnlyWorldMatrix(world);
  29122. }
  29123. };
  29124. /**
  29125. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29126. */
  29127. Mesh.prototype.getEmittedParticleSystems = function () {
  29128. var results = new Array();
  29129. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29130. var particleSystem = this.getScene().particleSystems[index];
  29131. if (particleSystem.emitter === this) {
  29132. results.push(particleSystem);
  29133. }
  29134. }
  29135. return results;
  29136. };
  29137. /**
  29138. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29139. */
  29140. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29141. var results = new Array();
  29142. var descendants = this.getDescendants();
  29143. descendants.push(this);
  29144. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29145. var particleSystem = this.getScene().particleSystems[index];
  29146. var emitter = particleSystem.emitter;
  29147. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29148. results.push(particleSystem);
  29149. }
  29150. }
  29151. return results;
  29152. };
  29153. Mesh.prototype._checkDelayState = function () {
  29154. var scene = this.getScene();
  29155. if (this._geometry) {
  29156. this._geometry.load(scene);
  29157. }
  29158. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29159. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29160. this._queueLoad(scene);
  29161. }
  29162. return this;
  29163. };
  29164. Mesh.prototype._queueLoad = function (scene) {
  29165. var _this = this;
  29166. scene._addPendingData(this);
  29167. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29168. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29169. if (data instanceof ArrayBuffer) {
  29170. _this._delayLoadingFunction(data, _this);
  29171. }
  29172. else {
  29173. _this._delayLoadingFunction(JSON.parse(data), _this);
  29174. }
  29175. _this.instances.forEach(function (instance) {
  29176. instance._syncSubMeshes();
  29177. });
  29178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29179. scene._removePendingData(_this);
  29180. }, function () { }, scene.database, getBinaryData);
  29181. return this;
  29182. };
  29183. /**
  29184. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29185. */
  29186. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29187. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29188. return false;
  29189. }
  29190. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29191. return false;
  29192. }
  29193. this._checkDelayState();
  29194. return true;
  29195. };
  29196. /**
  29197. * Sets the mesh material by the material or multiMaterial `id` property.
  29198. * The material `id` is a string identifying the material or the multiMaterial.
  29199. * This method returns the Mesh.
  29200. */
  29201. Mesh.prototype.setMaterialByID = function (id) {
  29202. var materials = this.getScene().materials;
  29203. var index;
  29204. for (index = materials.length - 1; index > -1; index--) {
  29205. if (materials[index].id === id) {
  29206. this.material = materials[index];
  29207. return this;
  29208. }
  29209. }
  29210. // Multi
  29211. var multiMaterials = this.getScene().multiMaterials;
  29212. for (index = multiMaterials.length - 1; index > -1; index--) {
  29213. if (multiMaterials[index].id === id) {
  29214. this.material = multiMaterials[index];
  29215. return this;
  29216. }
  29217. }
  29218. return this;
  29219. };
  29220. /**
  29221. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29222. */
  29223. Mesh.prototype.getAnimatables = function () {
  29224. var results = new Array();
  29225. if (this.material) {
  29226. results.push(this.material);
  29227. }
  29228. if (this.skeleton) {
  29229. results.push(this.skeleton);
  29230. }
  29231. return results;
  29232. };
  29233. /**
  29234. * Modifies the mesh geometry according to the passed transformation matrix.
  29235. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29236. * The mesh normals are modified accordingly the same transformation.
  29237. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29238. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29239. * Returns the Mesh.
  29240. */
  29241. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29242. // Position
  29243. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29244. return this;
  29245. }
  29246. var submeshes = this.subMeshes.splice(0);
  29247. this._resetPointsArrayCache();
  29248. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29249. var temp = new Array();
  29250. var index;
  29251. for (index = 0; index < data.length; index += 3) {
  29252. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29253. }
  29254. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29255. // Normals
  29256. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29257. return this;
  29258. }
  29259. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29260. temp = [];
  29261. for (index = 0; index < data.length; index += 3) {
  29262. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29263. }
  29264. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29265. // flip faces?
  29266. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29267. this.flipFaces();
  29268. }
  29269. // Restore submeshes
  29270. this.releaseSubMeshes();
  29271. this.subMeshes = submeshes;
  29272. return this;
  29273. };
  29274. /**
  29275. * Modifies the mesh geometry according to its own current World Matrix.
  29276. * The mesh World Matrix is then reset.
  29277. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29278. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29279. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29280. * Returns the Mesh.
  29281. */
  29282. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29283. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29284. this.scaling.copyFromFloats(1, 1, 1);
  29285. this.position.copyFromFloats(0, 0, 0);
  29286. this.rotation.copyFromFloats(0, 0, 0);
  29287. //only if quaternion is already set
  29288. if (this.rotationQuaternion) {
  29289. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29290. }
  29291. this._worldMatrix = BABYLON.Matrix.Identity();
  29292. return this;
  29293. };
  29294. Object.defineProperty(Mesh.prototype, "_positions", {
  29295. // Cache
  29296. get: function () {
  29297. if (this._geometry) {
  29298. return this._geometry._positions;
  29299. }
  29300. return null;
  29301. },
  29302. enumerable: true,
  29303. configurable: true
  29304. });
  29305. Mesh.prototype._resetPointsArrayCache = function () {
  29306. if (this._geometry) {
  29307. this._geometry._resetPointsArrayCache();
  29308. }
  29309. return this;
  29310. };
  29311. Mesh.prototype._generatePointsArray = function () {
  29312. if (this._geometry) {
  29313. return this._geometry._generatePointsArray();
  29314. }
  29315. return false;
  29316. };
  29317. /**
  29318. * Returns a new Mesh object generated from the current mesh properties.
  29319. * This method must not get confused with createInstance().
  29320. * The parameter `name` is a string, the name given to the new mesh.
  29321. * The optional parameter `newParent` can be any Node object (default `null`).
  29322. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29323. * 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.
  29324. */
  29325. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29326. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29327. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29328. };
  29329. /**
  29330. * Releases resources associated with this mesh.
  29331. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29332. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29333. */
  29334. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29335. var _this = this;
  29336. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29337. this.morphTargetManager = null;
  29338. if (this._geometry) {
  29339. this._geometry.releaseForMesh(this, true);
  29340. }
  29341. // Sources
  29342. var meshes = this.getScene().meshes;
  29343. meshes.forEach(function (abstractMesh) {
  29344. var mesh = abstractMesh;
  29345. if (mesh._source && mesh._source === _this) {
  29346. mesh._source = null;
  29347. }
  29348. });
  29349. this._source = null;
  29350. // Instances
  29351. if (this._instancesBuffer) {
  29352. this._instancesBuffer.dispose();
  29353. this._instancesBuffer = null;
  29354. }
  29355. while (this.instances.length) {
  29356. this.instances[0].dispose();
  29357. }
  29358. // Effect layers.
  29359. var effectLayers = this.getScene().effectLayers;
  29360. for (var i = 0; i < effectLayers.length; i++) {
  29361. var effectLayer = effectLayers[i];
  29362. if (effectLayer) {
  29363. effectLayer._disposeMesh(this);
  29364. }
  29365. }
  29366. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29367. };
  29368. /**
  29369. * Modifies the mesh geometry according to a displacement map.
  29370. * 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.
  29371. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29372. * This method returns nothing.
  29373. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29374. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29375. * 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.
  29376. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29377. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29378. *
  29379. * Returns the Mesh.
  29380. */
  29381. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29382. var _this = this;
  29383. var scene = this.getScene();
  29384. var onload = function (img) {
  29385. // Getting height map data
  29386. var canvas = document.createElement("canvas");
  29387. var context = canvas.getContext("2d");
  29388. var heightMapWidth = img.width;
  29389. var heightMapHeight = img.height;
  29390. canvas.width = heightMapWidth;
  29391. canvas.height = heightMapHeight;
  29392. context.drawImage(img, 0, 0);
  29393. // Create VertexData from map data
  29394. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29395. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29396. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29397. //execute success callback, if set
  29398. if (onSuccess) {
  29399. onSuccess(_this);
  29400. }
  29401. };
  29402. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29403. return this;
  29404. };
  29405. /**
  29406. * Modifies the mesh geometry according to a displacementMap buffer.
  29407. * 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.
  29408. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29409. * This method returns nothing.
  29410. * 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.
  29411. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29412. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29413. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29414. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29415. *
  29416. * Returns the Mesh.
  29417. */
  29418. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29419. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29420. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29421. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29422. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29423. return this;
  29424. }
  29425. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29426. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29427. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29428. var position = BABYLON.Vector3.Zero();
  29429. var normal = BABYLON.Vector3.Zero();
  29430. var uv = BABYLON.Vector2.Zero();
  29431. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29432. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29433. for (var index = 0; index < positions.length; index += 3) {
  29434. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29435. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29436. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29437. // Compute height
  29438. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29439. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29440. var pos = (u + v * heightMapWidth) * 4;
  29441. var r = buffer[pos] / 255.0;
  29442. var g = buffer[pos + 1] / 255.0;
  29443. var b = buffer[pos + 2] / 255.0;
  29444. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29445. normal.normalize();
  29446. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29447. position = position.add(normal);
  29448. position.toArray(positions, index);
  29449. }
  29450. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29451. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29452. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29453. return this;
  29454. };
  29455. /**
  29456. * Modify the mesh to get a flat shading rendering.
  29457. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29458. * This method returns the Mesh.
  29459. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29460. */
  29461. Mesh.prototype.convertToFlatShadedMesh = function () {
  29462. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29463. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29464. var kinds = this.getVerticesDataKinds();
  29465. var vbs = {};
  29466. var data = {};
  29467. var newdata = {};
  29468. var updatableNormals = false;
  29469. var kindIndex;
  29470. var kind;
  29471. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29472. kind = kinds[kindIndex];
  29473. var vertexBuffer = this.getVertexBuffer(kind);
  29474. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29475. updatableNormals = vertexBuffer.isUpdatable();
  29476. kinds.splice(kindIndex, 1);
  29477. kindIndex--;
  29478. continue;
  29479. }
  29480. vbs[kind] = vertexBuffer;
  29481. data[kind] = vbs[kind].getData();
  29482. newdata[kind] = [];
  29483. }
  29484. // Save previous submeshes
  29485. var previousSubmeshes = this.subMeshes.slice(0);
  29486. var indices = this.getIndices();
  29487. var totalIndices = this.getTotalIndices();
  29488. // Generating unique vertices per face
  29489. var index;
  29490. for (index = 0; index < totalIndices; index++) {
  29491. var vertexIndex = indices[index];
  29492. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29493. kind = kinds[kindIndex];
  29494. var stride = vbs[kind].getStrideSize();
  29495. for (var offset = 0; offset < stride; offset++) {
  29496. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29497. }
  29498. }
  29499. }
  29500. // Updating faces & normal
  29501. var normals = [];
  29502. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29503. for (index = 0; index < totalIndices; index += 3) {
  29504. indices[index] = index;
  29505. indices[index + 1] = index + 1;
  29506. indices[index + 2] = index + 2;
  29507. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29508. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29509. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29510. var p1p2 = p1.subtract(p2);
  29511. var p3p2 = p3.subtract(p2);
  29512. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29513. // Store same normals for every vertex
  29514. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29515. normals.push(normal.x);
  29516. normals.push(normal.y);
  29517. normals.push(normal.z);
  29518. }
  29519. }
  29520. this.setIndices(indices);
  29521. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29522. // Updating vertex buffers
  29523. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29524. kind = kinds[kindIndex];
  29525. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29526. }
  29527. // Updating submeshes
  29528. this.releaseSubMeshes();
  29529. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29530. var previousOne = previousSubmeshes[submeshIndex];
  29531. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29532. }
  29533. this.synchronizeInstances();
  29534. return this;
  29535. };
  29536. /**
  29537. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29538. * In other words, more vertices, no more indices and a single bigger VBO.
  29539. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29540. * Returns the Mesh.
  29541. */
  29542. Mesh.prototype.convertToUnIndexedMesh = function () {
  29543. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29544. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29545. var kinds = this.getVerticesDataKinds();
  29546. var vbs = {};
  29547. var data = {};
  29548. var newdata = {};
  29549. var kindIndex;
  29550. var kind;
  29551. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29552. kind = kinds[kindIndex];
  29553. var vertexBuffer = this.getVertexBuffer(kind);
  29554. vbs[kind] = vertexBuffer;
  29555. data[kind] = vbs[kind].getData();
  29556. newdata[kind] = [];
  29557. }
  29558. // Save previous submeshes
  29559. var previousSubmeshes = this.subMeshes.slice(0);
  29560. var indices = this.getIndices();
  29561. var totalIndices = this.getTotalIndices();
  29562. // Generating unique vertices per face
  29563. var index;
  29564. for (index = 0; index < totalIndices; index++) {
  29565. var vertexIndex = indices[index];
  29566. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29567. kind = kinds[kindIndex];
  29568. var stride = vbs[kind].getStrideSize();
  29569. for (var offset = 0; offset < stride; offset++) {
  29570. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29571. }
  29572. }
  29573. }
  29574. // Updating indices
  29575. for (index = 0; index < totalIndices; index += 3) {
  29576. indices[index] = index;
  29577. indices[index + 1] = index + 1;
  29578. indices[index + 2] = index + 2;
  29579. }
  29580. this.setIndices(indices);
  29581. // Updating vertex buffers
  29582. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29583. kind = kinds[kindIndex];
  29584. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29585. }
  29586. // Updating submeshes
  29587. this.releaseSubMeshes();
  29588. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29589. var previousOne = previousSubmeshes[submeshIndex];
  29590. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29591. }
  29592. this._unIndexed = true;
  29593. this.synchronizeInstances();
  29594. return this;
  29595. };
  29596. /**
  29597. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29598. * This method returns the Mesh.
  29599. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29600. */
  29601. Mesh.prototype.flipFaces = function (flipNormals) {
  29602. if (flipNormals === void 0) { flipNormals = false; }
  29603. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29604. var i;
  29605. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29606. for (i = 0; i < vertex_data.normals.length; i++) {
  29607. vertex_data.normals[i] *= -1;
  29608. }
  29609. }
  29610. if (vertex_data.indices) {
  29611. var temp;
  29612. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29613. // reassign indices
  29614. temp = vertex_data.indices[i + 1];
  29615. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29616. vertex_data.indices[i + 2] = temp;
  29617. }
  29618. }
  29619. vertex_data.applyToMesh(this);
  29620. return this;
  29621. };
  29622. // Instances
  29623. /**
  29624. * Creates a new InstancedMesh object from the mesh model.
  29625. * An instance shares the same properties and the same material than its model.
  29626. * Only these properties of each instance can then be set individually :
  29627. * - position
  29628. * - rotation
  29629. * - rotationQuaternion
  29630. * - setPivotMatrix
  29631. * - scaling
  29632. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29633. * Warning : this method is not supported for Line mesh and LineSystem
  29634. */
  29635. Mesh.prototype.createInstance = function (name) {
  29636. return new BABYLON.InstancedMesh(name, this);
  29637. };
  29638. /**
  29639. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29640. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29641. * This method returns the Mesh.
  29642. */
  29643. Mesh.prototype.synchronizeInstances = function () {
  29644. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29645. var instance = this.instances[instanceIndex];
  29646. instance._syncSubMeshes();
  29647. }
  29648. return this;
  29649. };
  29650. /**
  29651. * Simplify the mesh according to the given array of settings.
  29652. * Function will return immediately and will simplify async. It returns the Mesh.
  29653. * @param settings a collection of simplification settings.
  29654. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29655. * @param type the type of simplification to run.
  29656. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29657. */
  29658. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29659. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29660. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29661. this.getScene().simplificationQueue.addTask({
  29662. settings: settings,
  29663. parallelProcessing: parallelProcessing,
  29664. mesh: this,
  29665. simplificationType: simplificationType,
  29666. successCallback: successCallback
  29667. });
  29668. return this;
  29669. };
  29670. /**
  29671. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29672. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29673. * This should be used together with the simplification to avoid disappearing triangles.
  29674. * Returns the Mesh.
  29675. * @param successCallback an optional success callback to be called after the optimization finished.
  29676. */
  29677. Mesh.prototype.optimizeIndices = function (successCallback) {
  29678. var _this = this;
  29679. var indices = this.getIndices();
  29680. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29681. if (!positions || !indices) {
  29682. return this;
  29683. }
  29684. var vectorPositions = new Array();
  29685. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29686. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29687. }
  29688. var dupes = new Array();
  29689. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29690. var realPos = vectorPositions.length - 1 - iteration;
  29691. var testedPosition = vectorPositions[realPos];
  29692. for (var j = 0; j < realPos; ++j) {
  29693. var againstPosition = vectorPositions[j];
  29694. if (testedPosition.equals(againstPosition)) {
  29695. dupes[realPos] = j;
  29696. break;
  29697. }
  29698. }
  29699. }, function () {
  29700. for (var i = 0; i < indices.length; ++i) {
  29701. indices[i] = dupes[indices[i]] || indices[i];
  29702. }
  29703. //indices are now reordered
  29704. var originalSubMeshes = _this.subMeshes.slice(0);
  29705. _this.setIndices(indices);
  29706. _this.subMeshes = originalSubMeshes;
  29707. if (successCallback) {
  29708. successCallback(_this);
  29709. }
  29710. });
  29711. return this;
  29712. };
  29713. Mesh.prototype.serialize = function (serializationObject) {
  29714. serializationObject.name = this.name;
  29715. serializationObject.id = this.id;
  29716. serializationObject.type = this.getClassName();
  29717. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29718. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29719. }
  29720. serializationObject.position = this.position.asArray();
  29721. if (this.rotationQuaternion) {
  29722. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29723. }
  29724. else if (this.rotation) {
  29725. serializationObject.rotation = this.rotation.asArray();
  29726. }
  29727. serializationObject.scaling = this.scaling.asArray();
  29728. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29729. serializationObject.isEnabled = this.isEnabled(false);
  29730. serializationObject.isVisible = this.isVisible;
  29731. serializationObject.infiniteDistance = this.infiniteDistance;
  29732. serializationObject.pickable = this.isPickable;
  29733. serializationObject.receiveShadows = this.receiveShadows;
  29734. serializationObject.billboardMode = this.billboardMode;
  29735. serializationObject.visibility = this.visibility;
  29736. serializationObject.checkCollisions = this.checkCollisions;
  29737. serializationObject.isBlocker = this.isBlocker;
  29738. // Parent
  29739. if (this.parent) {
  29740. serializationObject.parentId = this.parent.id;
  29741. }
  29742. // Geometry
  29743. serializationObject.isUnIndexed = this.isUnIndexed;
  29744. var geometry = this._geometry;
  29745. if (geometry) {
  29746. var geometryId = geometry.id;
  29747. serializationObject.geometryId = geometryId;
  29748. // SubMeshes
  29749. serializationObject.subMeshes = [];
  29750. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29751. var subMesh = this.subMeshes[subIndex];
  29752. serializationObject.subMeshes.push({
  29753. materialIndex: subMesh.materialIndex,
  29754. verticesStart: subMesh.verticesStart,
  29755. verticesCount: subMesh.verticesCount,
  29756. indexStart: subMesh.indexStart,
  29757. indexCount: subMesh.indexCount
  29758. });
  29759. }
  29760. }
  29761. // Material
  29762. if (this.material) {
  29763. serializationObject.materialId = this.material.id;
  29764. }
  29765. else {
  29766. this.material = null;
  29767. }
  29768. // Morph targets
  29769. if (this.morphTargetManager) {
  29770. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29771. }
  29772. // Skeleton
  29773. if (this.skeleton) {
  29774. serializationObject.skeletonId = this.skeleton.id;
  29775. }
  29776. // Physics
  29777. //TODO implement correct serialization for physics impostors.
  29778. var impostor = this.getPhysicsImpostor();
  29779. if (impostor) {
  29780. serializationObject.physicsMass = impostor.getParam("mass");
  29781. serializationObject.physicsFriction = impostor.getParam("friction");
  29782. serializationObject.physicsRestitution = impostor.getParam("mass");
  29783. serializationObject.physicsImpostor = impostor.type;
  29784. }
  29785. // Metadata
  29786. if (this.metadata) {
  29787. serializationObject.metadata = this.metadata;
  29788. }
  29789. // Instances
  29790. serializationObject.instances = [];
  29791. for (var index = 0; index < this.instances.length; index++) {
  29792. var instance = this.instances[index];
  29793. var serializationInstance = {
  29794. name: instance.name,
  29795. id: instance.id,
  29796. position: instance.position.asArray(),
  29797. scaling: instance.scaling.asArray()
  29798. };
  29799. if (instance.rotationQuaternion) {
  29800. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29801. }
  29802. else if (instance.rotation) {
  29803. serializationInstance.rotation = instance.rotation.asArray();
  29804. }
  29805. serializationObject.instances.push(serializationInstance);
  29806. // Animations
  29807. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29808. serializationInstance.ranges = instance.serializeAnimationRanges();
  29809. }
  29810. //
  29811. // Animations
  29812. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29813. serializationObject.ranges = this.serializeAnimationRanges();
  29814. // Layer mask
  29815. serializationObject.layerMask = this.layerMask;
  29816. // Alpha
  29817. serializationObject.alphaIndex = this.alphaIndex;
  29818. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29819. // Overlay
  29820. serializationObject.overlayAlpha = this.overlayAlpha;
  29821. serializationObject.overlayColor = this.overlayColor.asArray();
  29822. serializationObject.renderOverlay = this.renderOverlay;
  29823. // Fog
  29824. serializationObject.applyFog = this.applyFog;
  29825. // Action Manager
  29826. if (this.actionManager) {
  29827. serializationObject.actions = this.actionManager.serialize(this.name);
  29828. }
  29829. };
  29830. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29831. if (!this.geometry) {
  29832. return;
  29833. }
  29834. this._markSubMeshesAsAttributesDirty();
  29835. var morphTargetManager = this._morphTargetManager;
  29836. if (morphTargetManager && morphTargetManager.vertexCount) {
  29837. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29838. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29839. this.morphTargetManager = null;
  29840. return;
  29841. }
  29842. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29843. var morphTarget = morphTargetManager.getActiveTarget(index);
  29844. var positions = morphTarget.getPositions();
  29845. if (!positions) {
  29846. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29847. return;
  29848. }
  29849. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29850. var normals = morphTarget.getNormals();
  29851. if (normals) {
  29852. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29853. }
  29854. var tangents = morphTarget.getTangents();
  29855. if (tangents) {
  29856. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29857. }
  29858. }
  29859. }
  29860. else {
  29861. var index = 0;
  29862. // Positions
  29863. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29864. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29865. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29866. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29867. }
  29868. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29869. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29870. }
  29871. index++;
  29872. }
  29873. }
  29874. };
  29875. // Statics
  29876. /**
  29877. * Returns a new Mesh object parsed from the source provided.
  29878. * The parameter `parsedMesh` is the source.
  29879. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29880. */
  29881. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29882. var mesh;
  29883. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29884. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29885. }
  29886. else {
  29887. mesh = new Mesh(parsedMesh.name, scene);
  29888. }
  29889. mesh.id = parsedMesh.id;
  29890. if (BABYLON.Tags) {
  29891. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29892. }
  29893. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29894. if (parsedMesh.metadata !== undefined) {
  29895. mesh.metadata = parsedMesh.metadata;
  29896. }
  29897. if (parsedMesh.rotationQuaternion) {
  29898. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29899. }
  29900. else if (parsedMesh.rotation) {
  29901. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29902. }
  29903. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29904. if (parsedMesh.localMatrix) {
  29905. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29906. }
  29907. else if (parsedMesh.pivotMatrix) {
  29908. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29909. }
  29910. mesh.setEnabled(parsedMesh.isEnabled);
  29911. mesh.isVisible = parsedMesh.isVisible;
  29912. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29913. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29914. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29915. if (parsedMesh.applyFog !== undefined) {
  29916. mesh.applyFog = parsedMesh.applyFog;
  29917. }
  29918. if (parsedMesh.pickable !== undefined) {
  29919. mesh.isPickable = parsedMesh.pickable;
  29920. }
  29921. if (parsedMesh.alphaIndex !== undefined) {
  29922. mesh.alphaIndex = parsedMesh.alphaIndex;
  29923. }
  29924. mesh.receiveShadows = parsedMesh.receiveShadows;
  29925. mesh.billboardMode = parsedMesh.billboardMode;
  29926. if (parsedMesh.visibility !== undefined) {
  29927. mesh.visibility = parsedMesh.visibility;
  29928. }
  29929. mesh.checkCollisions = parsedMesh.checkCollisions;
  29930. if (parsedMesh.isBlocker !== undefined) {
  29931. mesh.isBlocker = parsedMesh.isBlocker;
  29932. }
  29933. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29934. // freezeWorldMatrix
  29935. if (parsedMesh.freezeWorldMatrix) {
  29936. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29937. }
  29938. // Parent
  29939. if (parsedMesh.parentId) {
  29940. mesh._waitingParentId = parsedMesh.parentId;
  29941. }
  29942. // Actions
  29943. if (parsedMesh.actions !== undefined) {
  29944. mesh._waitingActions = parsedMesh.actions;
  29945. }
  29946. // Overlay
  29947. if (parsedMesh.overlayAlpha !== undefined) {
  29948. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29949. }
  29950. if (parsedMesh.overlayColor !== undefined) {
  29951. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29952. }
  29953. if (parsedMesh.renderOverlay !== undefined) {
  29954. mesh.renderOverlay = parsedMesh.renderOverlay;
  29955. }
  29956. // Geometry
  29957. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29958. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29959. if (parsedMesh.delayLoadingFile) {
  29960. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29961. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29962. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29963. if (parsedMesh._binaryInfo) {
  29964. mesh._binaryInfo = parsedMesh._binaryInfo;
  29965. }
  29966. mesh._delayInfo = [];
  29967. if (parsedMesh.hasUVs) {
  29968. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29969. }
  29970. if (parsedMesh.hasUVs2) {
  29971. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29972. }
  29973. if (parsedMesh.hasUVs3) {
  29974. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29975. }
  29976. if (parsedMesh.hasUVs4) {
  29977. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29978. }
  29979. if (parsedMesh.hasUVs5) {
  29980. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29981. }
  29982. if (parsedMesh.hasUVs6) {
  29983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29984. }
  29985. if (parsedMesh.hasColors) {
  29986. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29987. }
  29988. if (parsedMesh.hasMatricesIndices) {
  29989. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29990. }
  29991. if (parsedMesh.hasMatricesWeights) {
  29992. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29993. }
  29994. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29995. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29996. mesh._checkDelayState();
  29997. }
  29998. }
  29999. else {
  30000. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  30001. }
  30002. // Material
  30003. if (parsedMesh.materialId) {
  30004. mesh.setMaterialByID(parsedMesh.materialId);
  30005. }
  30006. else {
  30007. mesh.material = null;
  30008. }
  30009. // Morph targets
  30010. if (parsedMesh.morphTargetManagerId > -1) {
  30011. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  30012. }
  30013. // Skeleton
  30014. if (parsedMesh.skeletonId > -1) {
  30015. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  30016. if (parsedMesh.numBoneInfluencers) {
  30017. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  30018. }
  30019. }
  30020. // Animations
  30021. if (parsedMesh.animations) {
  30022. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30023. var parsedAnimation = parsedMesh.animations[animationIndex];
  30024. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30025. }
  30026. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  30027. }
  30028. if (parsedMesh.autoAnimate) {
  30029. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  30030. }
  30031. // Layer Mask
  30032. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  30033. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  30034. }
  30035. else {
  30036. mesh.layerMask = 0x0FFFFFFF;
  30037. }
  30038. // Physics
  30039. if (parsedMesh.physicsImpostor) {
  30040. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30041. mass: parsedMesh.physicsMass,
  30042. friction: parsedMesh.physicsFriction,
  30043. restitution: parsedMesh.physicsRestitution
  30044. }, scene);
  30045. }
  30046. // Instances
  30047. if (parsedMesh.instances) {
  30048. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30049. var parsedInstance = parsedMesh.instances[index];
  30050. var instance = mesh.createInstance(parsedInstance.name);
  30051. if (parsedInstance.id) {
  30052. instance.id = parsedInstance.id;
  30053. }
  30054. if (BABYLON.Tags) {
  30055. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30056. }
  30057. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30058. if (parsedInstance.parentId) {
  30059. instance._waitingParentId = parsedInstance.parentId;
  30060. }
  30061. if (parsedInstance.rotationQuaternion) {
  30062. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30063. }
  30064. else if (parsedInstance.rotation) {
  30065. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30066. }
  30067. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30068. instance.checkCollisions = mesh.checkCollisions;
  30069. if (parsedMesh.animations) {
  30070. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30071. parsedAnimation = parsedMesh.animations[animationIndex];
  30072. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30073. }
  30074. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30075. }
  30076. }
  30077. }
  30078. return mesh;
  30079. };
  30080. /**
  30081. * Creates a ribbon mesh.
  30082. * Please consider using the same method from the MeshBuilder class instead.
  30083. * 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.
  30084. *
  30085. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30086. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30087. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30088. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30089. * 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.
  30090. * 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.
  30091. * 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
  30092. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30093. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30095. */
  30096. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30097. if (closeArray === void 0) { closeArray = false; }
  30098. if (updatable === void 0) { updatable = false; }
  30099. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30100. pathArray: pathArray,
  30101. closeArray: closeArray,
  30102. closePath: closePath,
  30103. offset: offset,
  30104. updatable: updatable,
  30105. sideOrientation: sideOrientation,
  30106. instance: instance
  30107. }, scene);
  30108. };
  30109. /**
  30110. * Creates a plane polygonal mesh. By default, this is a disc.
  30111. * Please consider using the same method from the MeshBuilder class instead.
  30112. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30113. * 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.
  30114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30115. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30117. */
  30118. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30119. if (scene === void 0) { scene = null; }
  30120. var options = {
  30121. radius: radius,
  30122. tessellation: tessellation,
  30123. sideOrientation: sideOrientation,
  30124. updatable: updatable
  30125. };
  30126. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30127. };
  30128. /**
  30129. * Creates a box mesh.
  30130. * Please consider using the same method from the MeshBuilder class instead.
  30131. * The parameter `size` sets the size (float) of each box side (default 1).
  30132. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30133. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30134. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30135. */
  30136. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30137. if (scene === void 0) { scene = null; }
  30138. var options = {
  30139. size: size,
  30140. sideOrientation: sideOrientation,
  30141. updatable: updatable
  30142. };
  30143. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30144. };
  30145. /**
  30146. * Creates a sphere mesh.
  30147. * Please consider using the same method from the MeshBuilder class instead.
  30148. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30149. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30150. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30151. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30153. */
  30154. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30155. var options = {
  30156. segments: segments,
  30157. diameterX: diameter,
  30158. diameterY: diameter,
  30159. diameterZ: diameter,
  30160. sideOrientation: sideOrientation,
  30161. updatable: updatable
  30162. };
  30163. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30164. };
  30165. /**
  30166. * Creates a cylinder or a cone mesh.
  30167. * Please consider using the same method from the MeshBuilder class instead.
  30168. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30169. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30170. * 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.
  30171. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30172. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30174. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30176. */
  30177. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30178. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30179. if (scene !== undefined) {
  30180. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30181. updatable = scene;
  30182. }
  30183. scene = subdivisions;
  30184. subdivisions = 1;
  30185. }
  30186. var options = {
  30187. height: height,
  30188. diameterTop: diameterTop,
  30189. diameterBottom: diameterBottom,
  30190. tessellation: tessellation,
  30191. subdivisions: subdivisions,
  30192. sideOrientation: sideOrientation,
  30193. updatable: updatable
  30194. };
  30195. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30196. };
  30197. // Torus (Code from SharpDX.org)
  30198. /**
  30199. * Creates a torus mesh.
  30200. * Please consider using the same method from the MeshBuilder class instead.
  30201. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30202. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30203. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30205. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30207. */
  30208. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30209. var options = {
  30210. diameter: diameter,
  30211. thickness: thickness,
  30212. tessellation: tessellation,
  30213. sideOrientation: sideOrientation,
  30214. updatable: updatable
  30215. };
  30216. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30217. };
  30218. /**
  30219. * Creates a torus knot mesh.
  30220. * Please consider using the same method from the MeshBuilder class instead.
  30221. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30222. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30223. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30224. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30226. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30227. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30228. */
  30229. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30230. var options = {
  30231. radius: radius,
  30232. tube: tube,
  30233. radialSegments: radialSegments,
  30234. tubularSegments: tubularSegments,
  30235. p: p,
  30236. q: q,
  30237. sideOrientation: sideOrientation,
  30238. updatable: updatable
  30239. };
  30240. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30241. };
  30242. /**
  30243. * Creates a line mesh.
  30244. * Please consider using the same method from the MeshBuilder class instead.
  30245. * 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.
  30246. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30247. * The parameter `points` is an array successive Vector3.
  30248. * 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
  30249. * When updating an instance, remember that only point positions can change, not the number of points.
  30250. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30251. */
  30252. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30253. if (scene === void 0) { scene = null; }
  30254. if (updatable === void 0) { updatable = false; }
  30255. if (instance === void 0) { instance = null; }
  30256. var options = {
  30257. points: points,
  30258. updatable: updatable,
  30259. instance: instance
  30260. };
  30261. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30262. };
  30263. /**
  30264. * Creates a dashed line mesh.
  30265. * Please consider using the same method from the MeshBuilder class instead.
  30266. * 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.
  30267. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30268. * The parameter `points` is an array successive Vector3.
  30269. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30270. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30271. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30272. * 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
  30273. * When updating an instance, remember that only point positions can change, not the number of points.
  30274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30275. */
  30276. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30277. if (scene === void 0) { scene = null; }
  30278. var options = {
  30279. points: points,
  30280. dashSize: dashSize,
  30281. gapSize: gapSize,
  30282. dashNb: dashNb,
  30283. updatable: updatable,
  30284. instance: instance
  30285. };
  30286. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30287. };
  30288. /**
  30289. * Creates a polygon mesh.
  30290. * Please consider using the same method from the MeshBuilder class instead.
  30291. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30292. * 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.
  30293. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30295. * Remember you can only change the shape positions, not their number when updating a polygon.
  30296. */
  30297. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30298. var options = {
  30299. shape: shape,
  30300. holes: holes,
  30301. updatable: updatable,
  30302. sideOrientation: sideOrientation
  30303. };
  30304. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30305. };
  30306. /**
  30307. * Creates an extruded polygon mesh, with depth in the Y direction.
  30308. * Please consider using the same method from the MeshBuilder class instead.
  30309. */
  30310. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30311. var options = {
  30312. shape: shape,
  30313. holes: holes,
  30314. depth: depth,
  30315. updatable: updatable,
  30316. sideOrientation: sideOrientation
  30317. };
  30318. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30319. };
  30320. /**
  30321. * Creates an extruded shape mesh.
  30322. * 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.
  30323. * Please consider using the same method from the MeshBuilder class instead.
  30324. *
  30325. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30326. * 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
  30327. * extruded along the Z axis.
  30328. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30329. * 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.
  30330. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30331. * 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
  30332. * 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
  30333. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30334. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30335. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30336. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30337. */
  30338. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30339. if (scene === void 0) { scene = null; }
  30340. var options = {
  30341. shape: shape,
  30342. path: path,
  30343. scale: scale,
  30344. rotation: rotation,
  30345. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30346. sideOrientation: sideOrientation,
  30347. instance: instance,
  30348. updatable: updatable
  30349. };
  30350. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30351. };
  30352. /**
  30353. * Creates an custom extruded shape mesh.
  30354. * 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.
  30355. * Please consider using the same method from the MeshBuilder class instead.
  30356. *
  30357. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30358. * 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
  30359. * extruded along the Z axis.
  30360. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30361. * 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
  30362. * and the distance of this point from the begining of the path :
  30363. * ```javascript
  30364. * var rotationFunction = function(i, distance) {
  30365. * // do things
  30366. * return rotationValue; }
  30367. * ```
  30368. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30369. * 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
  30370. * and the distance of this point from the begining of the path :
  30371. * ```javascript
  30372. * var scaleFunction = function(i, distance) {
  30373. * // do things
  30374. * return scaleValue;}
  30375. * ```
  30376. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30377. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30378. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30379. * 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
  30380. * 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
  30381. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30382. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30383. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30385. */
  30386. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30387. var options = {
  30388. shape: shape,
  30389. path: path,
  30390. scaleFunction: scaleFunction,
  30391. rotationFunction: rotationFunction,
  30392. ribbonCloseArray: ribbonCloseArray,
  30393. ribbonClosePath: ribbonClosePath,
  30394. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30395. sideOrientation: sideOrientation,
  30396. instance: instance,
  30397. updatable: updatable
  30398. };
  30399. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30400. };
  30401. /**
  30402. * Creates lathe mesh.
  30403. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30404. * Please consider using the same method from the MeshBuilder class instead.
  30405. * 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
  30406. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30407. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30408. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30412. */
  30413. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30414. var options = {
  30415. shape: shape,
  30416. radius: radius,
  30417. tessellation: tessellation,
  30418. sideOrientation: sideOrientation,
  30419. updatable: updatable
  30420. };
  30421. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30422. };
  30423. /**
  30424. * Creates a plane mesh.
  30425. * Please consider using the same method from the MeshBuilder class instead.
  30426. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30430. */
  30431. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30432. var options = {
  30433. size: size,
  30434. width: size,
  30435. height: size,
  30436. sideOrientation: sideOrientation,
  30437. updatable: updatable
  30438. };
  30439. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30440. };
  30441. /**
  30442. * Creates a ground mesh.
  30443. * Please consider using the same method from the MeshBuilder class instead.
  30444. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30445. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30447. */
  30448. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30449. var options = {
  30450. width: width,
  30451. height: height,
  30452. subdivisions: subdivisions,
  30453. updatable: updatable
  30454. };
  30455. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30456. };
  30457. /**
  30458. * Creates a tiled ground mesh.
  30459. * Please consider using the same method from the MeshBuilder class instead.
  30460. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30461. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30462. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30463. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30464. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30465. * numbers of subdivisions on the ground width and height of each tile.
  30466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30467. */
  30468. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30469. var options = {
  30470. xmin: xmin,
  30471. zmin: zmin,
  30472. xmax: xmax,
  30473. zmax: zmax,
  30474. subdivisions: subdivisions,
  30475. precision: precision,
  30476. updatable: updatable
  30477. };
  30478. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30479. };
  30480. /**
  30481. * Creates a ground mesh from a height map.
  30482. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30483. * Please consider using the same method from the MeshBuilder class instead.
  30484. * The parameter `url` sets the URL of the height map image resource.
  30485. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30486. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30487. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30488. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30489. * 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).
  30490. * This function is passed the newly built mesh :
  30491. * ```javascript
  30492. * function(mesh) { // do things
  30493. * return; }
  30494. * ```
  30495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30496. */
  30497. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30498. var options = {
  30499. width: width,
  30500. height: height,
  30501. subdivisions: subdivisions,
  30502. minHeight: minHeight,
  30503. maxHeight: maxHeight,
  30504. updatable: updatable,
  30505. onReady: onReady
  30506. };
  30507. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30508. };
  30509. /**
  30510. * Creates a tube mesh.
  30511. * 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.
  30512. * Please consider using the same method from the MeshBuilder class instead.
  30513. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30514. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30515. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30516. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30517. * 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.
  30518. * It must return a radius value (positive float) :
  30519. * ```javascript
  30520. * var radiusFunction = function(i, distance) {
  30521. * // do things
  30522. * return radius; }
  30523. * ```
  30524. * 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
  30525. * 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
  30526. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30527. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30529. */
  30530. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30531. var options = {
  30532. path: path,
  30533. radius: radius,
  30534. tessellation: tessellation,
  30535. radiusFunction: radiusFunction,
  30536. arc: 1,
  30537. cap: cap,
  30538. updatable: updatable,
  30539. sideOrientation: sideOrientation,
  30540. instance: instance
  30541. };
  30542. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30543. };
  30544. /**
  30545. * Creates a polyhedron mesh.
  30546. * Please consider using the same method from the MeshBuilder class instead.
  30547. * 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
  30548. * to choose the wanted type.
  30549. * The parameter `size` (positive float, default 1) sets the polygon size.
  30550. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30551. * 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`.
  30552. * 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
  30553. * 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)`).
  30554. * 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
  30555. * 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.
  30556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30557. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30559. */
  30560. Mesh.CreatePolyhedron = function (name, options, scene) {
  30561. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30562. };
  30563. /**
  30564. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30565. * Please consider using the same method from the MeshBuilder class instead.
  30566. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30567. * 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`).
  30568. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30569. * 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.
  30570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30571. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30573. */
  30574. Mesh.CreateIcoSphere = function (name, options, scene) {
  30575. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30576. };
  30577. /**
  30578. * Creates a decal mesh.
  30579. * Please consider using the same method from the MeshBuilder class instead.
  30580. * 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.
  30581. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30582. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30583. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30584. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30585. */
  30586. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30587. var options = {
  30588. position: position,
  30589. normal: normal,
  30590. size: size,
  30591. angle: angle
  30592. };
  30593. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30594. };
  30595. // Skeletons
  30596. /**
  30597. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30598. */
  30599. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30600. if (!this._sourcePositions) {
  30601. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30602. if (!source) {
  30603. return this._sourcePositions;
  30604. }
  30605. this._sourcePositions = new Float32Array(source);
  30606. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30607. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30608. }
  30609. }
  30610. return this._sourcePositions;
  30611. };
  30612. /**
  30613. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30614. */
  30615. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30616. if (!this._sourceNormals) {
  30617. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30618. if (!source) {
  30619. return this._sourceNormals;
  30620. }
  30621. this._sourceNormals = new Float32Array(source);
  30622. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30623. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30624. }
  30625. }
  30626. return this._sourceNormals;
  30627. };
  30628. /**
  30629. * Updates the vertex buffer by applying transformation from the bones.
  30630. * Returns the Mesh.
  30631. *
  30632. * @param {skeleton} skeleton to apply
  30633. */
  30634. Mesh.prototype.applySkeleton = function (skeleton) {
  30635. if (!this.geometry) {
  30636. return this;
  30637. }
  30638. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30639. return this;
  30640. }
  30641. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30642. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30643. return this;
  30644. }
  30645. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30646. return this;
  30647. }
  30648. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30649. return this;
  30650. }
  30651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30652. return this;
  30653. }
  30654. if (!this._sourcePositions) {
  30655. var submeshes = this.subMeshes.slice();
  30656. this.setPositionsForCPUSkinning();
  30657. this.subMeshes = submeshes;
  30658. }
  30659. if (!this._sourceNormals) {
  30660. this.setNormalsForCPUSkinning();
  30661. }
  30662. // positionsData checks for not being Float32Array will only pass at most once
  30663. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30664. if (!positionsData) {
  30665. return this;
  30666. }
  30667. if (!(positionsData instanceof Float32Array)) {
  30668. positionsData = new Float32Array(positionsData);
  30669. }
  30670. // normalsData checks for not being Float32Array will only pass at most once
  30671. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30672. if (!normalsData) {
  30673. return this;
  30674. }
  30675. if (!(normalsData instanceof Float32Array)) {
  30676. normalsData = new Float32Array(normalsData);
  30677. }
  30678. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30679. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30680. if (!matricesWeightsData || !matricesIndicesData) {
  30681. return this;
  30682. }
  30683. var needExtras = this.numBoneInfluencers > 4;
  30684. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30685. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30686. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30687. var tempVector3 = BABYLON.Vector3.Zero();
  30688. var finalMatrix = new BABYLON.Matrix();
  30689. var tempMatrix = new BABYLON.Matrix();
  30690. var matWeightIdx = 0;
  30691. var inf;
  30692. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30693. var weight;
  30694. for (inf = 0; inf < 4; inf++) {
  30695. weight = matricesWeightsData[matWeightIdx + inf];
  30696. if (weight > 0) {
  30697. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30698. finalMatrix.addToSelf(tempMatrix);
  30699. }
  30700. else
  30701. break;
  30702. }
  30703. if (needExtras) {
  30704. for (inf = 0; inf < 4; inf++) {
  30705. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30706. if (weight > 0) {
  30707. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30708. finalMatrix.addToSelf(tempMatrix);
  30709. }
  30710. else
  30711. break;
  30712. }
  30713. }
  30714. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30715. tempVector3.toArray(positionsData, index);
  30716. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30717. tempVector3.toArray(normalsData, index);
  30718. finalMatrix.reset();
  30719. }
  30720. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30721. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30722. return this;
  30723. };
  30724. // Tools
  30725. /**
  30726. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30727. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30728. */
  30729. Mesh.MinMax = function (meshes) {
  30730. var minVector = null;
  30731. var maxVector = null;
  30732. meshes.forEach(function (mesh, index, array) {
  30733. var boundingInfo = mesh.getBoundingInfo();
  30734. var boundingBox = boundingInfo.boundingBox;
  30735. if (!minVector || !maxVector) {
  30736. minVector = boundingBox.minimumWorld;
  30737. maxVector = boundingBox.maximumWorld;
  30738. }
  30739. else {
  30740. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30741. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30742. }
  30743. });
  30744. if (!minVector || !maxVector) {
  30745. return {
  30746. min: BABYLON.Vector3.Zero(),
  30747. max: BABYLON.Vector3.Zero()
  30748. };
  30749. }
  30750. return {
  30751. min: minVector,
  30752. max: maxVector
  30753. };
  30754. };
  30755. /**
  30756. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30757. */
  30758. Mesh.Center = function (meshesOrMinMaxVector) {
  30759. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30760. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30761. };
  30762. /**
  30763. * Merge the array of meshes into a single mesh for performance reasons.
  30764. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30765. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30766. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30767. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30768. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30769. */
  30770. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30771. if (disposeSource === void 0) { disposeSource = true; }
  30772. var index;
  30773. if (!allow32BitsIndices) {
  30774. var totalVertices = 0;
  30775. // Counting vertices
  30776. for (index = 0; index < meshes.length; index++) {
  30777. if (meshes[index]) {
  30778. totalVertices += meshes[index].getTotalVertices();
  30779. if (totalVertices > 65536) {
  30780. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30781. return null;
  30782. }
  30783. }
  30784. }
  30785. }
  30786. // Merge
  30787. var vertexData = null;
  30788. var otherVertexData;
  30789. var indiceArray = new Array();
  30790. var source = null;
  30791. for (index = 0; index < meshes.length; index++) {
  30792. if (meshes[index]) {
  30793. meshes[index].computeWorldMatrix(true);
  30794. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30795. otherVertexData.transform(meshes[index].getWorldMatrix());
  30796. if (vertexData) {
  30797. vertexData.merge(otherVertexData);
  30798. }
  30799. else {
  30800. vertexData = otherVertexData;
  30801. source = meshes[index];
  30802. }
  30803. if (subdivideWithSubMeshes) {
  30804. indiceArray.push(meshes[index].getTotalIndices());
  30805. }
  30806. }
  30807. }
  30808. source = source;
  30809. if (!meshSubclass) {
  30810. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30811. }
  30812. vertexData.applyToMesh(meshSubclass);
  30813. // Setting properties
  30814. meshSubclass.material = source.material;
  30815. meshSubclass.checkCollisions = source.checkCollisions;
  30816. // Cleaning
  30817. if (disposeSource) {
  30818. for (index = 0; index < meshes.length; index++) {
  30819. if (meshes[index]) {
  30820. meshes[index].dispose();
  30821. }
  30822. }
  30823. }
  30824. // Subdivide
  30825. if (subdivideWithSubMeshes) {
  30826. //-- Suppresions du submesh global
  30827. meshSubclass.releaseSubMeshes();
  30828. index = 0;
  30829. var offset = 0;
  30830. //-- aplique la subdivision en fonction du tableau d'indices
  30831. while (index < indiceArray.length) {
  30832. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30833. offset += indiceArray[index];
  30834. index++;
  30835. }
  30836. }
  30837. return meshSubclass;
  30838. };
  30839. // Consts
  30840. Mesh._FRONTSIDE = 0;
  30841. Mesh._BACKSIDE = 1;
  30842. Mesh._DOUBLESIDE = 2;
  30843. Mesh._DEFAULTSIDE = 0;
  30844. Mesh._NO_CAP = 0;
  30845. Mesh._CAP_START = 1;
  30846. Mesh._CAP_END = 2;
  30847. Mesh._CAP_ALL = 3;
  30848. return Mesh;
  30849. }(BABYLON.AbstractMesh));
  30850. BABYLON.Mesh = Mesh;
  30851. })(BABYLON || (BABYLON = {}));
  30852. //# sourceMappingURL=babylon.mesh.js.map
  30853. "use strict";
  30854. var BABYLON;
  30855. (function (BABYLON) {
  30856. var BaseSubMesh = /** @class */ (function () {
  30857. function BaseSubMesh() {
  30858. }
  30859. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30860. get: function () {
  30861. return this._materialEffect;
  30862. },
  30863. enumerable: true,
  30864. configurable: true
  30865. });
  30866. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30867. if (defines === void 0) { defines = null; }
  30868. if (this._materialEffect === effect) {
  30869. if (!effect) {
  30870. this._materialDefines = null;
  30871. }
  30872. return;
  30873. }
  30874. this._materialDefines = defines;
  30875. this._materialEffect = effect;
  30876. };
  30877. return BaseSubMesh;
  30878. }());
  30879. BABYLON.BaseSubMesh = BaseSubMesh;
  30880. var SubMesh = /** @class */ (function (_super) {
  30881. __extends(SubMesh, _super);
  30882. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30883. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30884. var _this = _super.call(this) || this;
  30885. _this.materialIndex = materialIndex;
  30886. _this.verticesStart = verticesStart;
  30887. _this.verticesCount = verticesCount;
  30888. _this.indexStart = indexStart;
  30889. _this.indexCount = indexCount;
  30890. _this._renderId = 0;
  30891. _this._mesh = mesh;
  30892. _this._renderingMesh = renderingMesh || mesh;
  30893. mesh.subMeshes.push(_this);
  30894. _this._trianglePlanes = [];
  30895. _this._id = mesh.subMeshes.length - 1;
  30896. if (createBoundingBox) {
  30897. _this.refreshBoundingInfo();
  30898. mesh.computeWorldMatrix(true);
  30899. }
  30900. return _this;
  30901. }
  30902. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30903. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30904. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30905. };
  30906. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30907. get: function () {
  30908. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30909. },
  30910. enumerable: true,
  30911. configurable: true
  30912. });
  30913. /**
  30914. * Returns the submesh BoudingInfo object.
  30915. */
  30916. SubMesh.prototype.getBoundingInfo = function () {
  30917. if (this.IsGlobal) {
  30918. return this._mesh.getBoundingInfo();
  30919. }
  30920. return this._boundingInfo;
  30921. };
  30922. /**
  30923. * Sets the submesh BoundingInfo.
  30924. * Return the SubMesh.
  30925. */
  30926. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30927. this._boundingInfo = boundingInfo;
  30928. return this;
  30929. };
  30930. /**
  30931. * Returns the mesh of the current submesh.
  30932. */
  30933. SubMesh.prototype.getMesh = function () {
  30934. return this._mesh;
  30935. };
  30936. /**
  30937. * Returns the rendering mesh of the submesh.
  30938. */
  30939. SubMesh.prototype.getRenderingMesh = function () {
  30940. return this._renderingMesh;
  30941. };
  30942. /**
  30943. * Returns the submesh material.
  30944. */
  30945. SubMesh.prototype.getMaterial = function () {
  30946. var rootMaterial = this._renderingMesh.material;
  30947. if (rootMaterial === null || rootMaterial === undefined) {
  30948. return this._mesh.getScene().defaultMaterial;
  30949. }
  30950. else if (rootMaterial.getSubMaterial) {
  30951. var multiMaterial = rootMaterial;
  30952. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30953. if (this._currentMaterial !== effectiveMaterial) {
  30954. this._currentMaterial = effectiveMaterial;
  30955. this._materialDefines = null;
  30956. }
  30957. return effectiveMaterial;
  30958. }
  30959. return rootMaterial;
  30960. };
  30961. // Methods
  30962. /**
  30963. * Sets a new updated BoundingInfo object to the submesh.
  30964. * Returns the SubMesh.
  30965. */
  30966. SubMesh.prototype.refreshBoundingInfo = function () {
  30967. this._lastColliderWorldVertices = null;
  30968. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30969. return this;
  30970. }
  30971. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30972. if (!data) {
  30973. this._boundingInfo = this._mesh.getBoundingInfo();
  30974. return this;
  30975. }
  30976. var indices = this._renderingMesh.getIndices();
  30977. var extend;
  30978. //is this the only submesh?
  30979. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30980. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30981. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30982. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30983. }
  30984. else {
  30985. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30986. }
  30987. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30988. return this;
  30989. };
  30990. SubMesh.prototype._checkCollision = function (collider) {
  30991. var boundingInfo = this.getBoundingInfo();
  30992. return boundingInfo._checkCollision(collider);
  30993. };
  30994. /**
  30995. * Updates the submesh BoundingInfo.
  30996. * Returns the Submesh.
  30997. */
  30998. SubMesh.prototype.updateBoundingInfo = function (world) {
  30999. var boundingInfo = this.getBoundingInfo();
  31000. if (!boundingInfo) {
  31001. this.refreshBoundingInfo();
  31002. boundingInfo = this.getBoundingInfo();
  31003. }
  31004. boundingInfo.update(world);
  31005. return this;
  31006. };
  31007. /**
  31008. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  31009. * Boolean returned.
  31010. */
  31011. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  31012. var boundingInfo = this.getBoundingInfo();
  31013. if (!boundingInfo) {
  31014. return false;
  31015. }
  31016. return boundingInfo.isInFrustum(frustumPlanes);
  31017. };
  31018. /**
  31019. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  31020. * Boolean returned.
  31021. */
  31022. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  31023. var boundingInfo = this.getBoundingInfo();
  31024. if (!boundingInfo) {
  31025. return false;
  31026. }
  31027. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  31028. };
  31029. /**
  31030. * Renders the submesh.
  31031. * Returns it.
  31032. */
  31033. SubMesh.prototype.render = function (enableAlphaMode) {
  31034. this._renderingMesh.render(this, enableAlphaMode);
  31035. return this;
  31036. };
  31037. /**
  31038. * Returns a new Index Buffer.
  31039. * Type returned : WebGLBuffer.
  31040. */
  31041. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31042. if (!this._linesIndexBuffer) {
  31043. var linesIndices = [];
  31044. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31045. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31046. }
  31047. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31048. this.linesIndexCount = linesIndices.length;
  31049. }
  31050. return this._linesIndexBuffer;
  31051. };
  31052. /**
  31053. * True is the passed Ray intersects the submesh bounding box.
  31054. * Boolean returned.
  31055. */
  31056. SubMesh.prototype.canIntersects = function (ray) {
  31057. var boundingInfo = this.getBoundingInfo();
  31058. if (!boundingInfo) {
  31059. return false;
  31060. }
  31061. return ray.intersectsBox(boundingInfo.boundingBox);
  31062. };
  31063. /**
  31064. * Returns an object IntersectionInfo.
  31065. */
  31066. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31067. var intersectInfo = null;
  31068. var material = this.getMaterial();
  31069. if (!material) {
  31070. return null;
  31071. }
  31072. switch (material.fillMode) {
  31073. case BABYLON.Material.PointListDrawMode:
  31074. case BABYLON.Material.LineListDrawMode:
  31075. case BABYLON.Material.LineLoopDrawMode:
  31076. case BABYLON.Material.LineStripDrawMode:
  31077. case BABYLON.Material.TriangleFanDrawMode:
  31078. case BABYLON.Material.TriangleStripDrawMode:
  31079. return null;
  31080. }
  31081. // LineMesh first as it's also a Mesh...
  31082. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31083. var lineMesh = this._mesh;
  31084. // Line test
  31085. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31086. var p0 = positions[indices[index]];
  31087. var p1 = positions[indices[index + 1]];
  31088. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31089. if (length < 0) {
  31090. continue;
  31091. }
  31092. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31093. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31094. if (fastCheck) {
  31095. break;
  31096. }
  31097. }
  31098. }
  31099. }
  31100. else {
  31101. // Triangles test
  31102. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31103. var p0 = positions[indices[index]];
  31104. var p1 = positions[indices[index + 1]];
  31105. var p2 = positions[indices[index + 2]];
  31106. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31107. if (currentIntersectInfo) {
  31108. if (currentIntersectInfo.distance < 0) {
  31109. continue;
  31110. }
  31111. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31112. intersectInfo = currentIntersectInfo;
  31113. intersectInfo.faceId = index / 3;
  31114. if (fastCheck) {
  31115. break;
  31116. }
  31117. }
  31118. }
  31119. }
  31120. }
  31121. return intersectInfo;
  31122. };
  31123. SubMesh.prototype._rebuild = function () {
  31124. if (this._linesIndexBuffer) {
  31125. this._linesIndexBuffer = null;
  31126. }
  31127. };
  31128. // Clone
  31129. /**
  31130. * Creates a new Submesh from the passed Mesh.
  31131. */
  31132. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31133. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31134. if (!this.IsGlobal) {
  31135. var boundingInfo = this.getBoundingInfo();
  31136. if (!boundingInfo) {
  31137. return result;
  31138. }
  31139. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31140. }
  31141. return result;
  31142. };
  31143. // Dispose
  31144. /**
  31145. * Disposes the Submesh.
  31146. * Returns nothing.
  31147. */
  31148. SubMesh.prototype.dispose = function () {
  31149. if (this._linesIndexBuffer) {
  31150. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31151. this._linesIndexBuffer = null;
  31152. }
  31153. // Remove from mesh
  31154. var index = this._mesh.subMeshes.indexOf(this);
  31155. this._mesh.subMeshes.splice(index, 1);
  31156. };
  31157. // Statics
  31158. /**
  31159. * Creates a new Submesh from the passed parameters :
  31160. * - materialIndex (integer) : the index of the main mesh material.
  31161. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31162. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31163. * - mesh (Mesh) : the main mesh to create the submesh from.
  31164. * - renderingMesh (optional Mesh) : rendering mesh.
  31165. */
  31166. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31167. var minVertexIndex = Number.MAX_VALUE;
  31168. var maxVertexIndex = -Number.MAX_VALUE;
  31169. renderingMesh = (renderingMesh || mesh);
  31170. var indices = renderingMesh.getIndices();
  31171. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31172. var vertexIndex = indices[index];
  31173. if (vertexIndex < minVertexIndex)
  31174. minVertexIndex = vertexIndex;
  31175. if (vertexIndex > maxVertexIndex)
  31176. maxVertexIndex = vertexIndex;
  31177. }
  31178. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31179. };
  31180. return SubMesh;
  31181. }(BaseSubMesh));
  31182. BABYLON.SubMesh = SubMesh;
  31183. })(BABYLON || (BABYLON = {}));
  31184. //# sourceMappingURL=babylon.subMesh.js.map
  31185. "use strict";
  31186. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31187. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31188. s = arguments[i];
  31189. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31190. t[p] = s[p];
  31191. }
  31192. return t;
  31193. };
  31194. var BABYLON;
  31195. (function (BABYLON) {
  31196. /**
  31197. * Manages the defines for the Material.
  31198. */
  31199. var MaterialDefines = /** @class */ (function () {
  31200. function MaterialDefines() {
  31201. this._isDirty = true;
  31202. this._areLightsDirty = true;
  31203. this._areAttributesDirty = true;
  31204. this._areTexturesDirty = true;
  31205. this._areFresnelDirty = true;
  31206. this._areMiscDirty = true;
  31207. this._areImageProcessingDirty = true;
  31208. this._normals = false;
  31209. this._uvs = false;
  31210. this._needNormals = false;
  31211. this._needUVs = false;
  31212. }
  31213. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31214. /**
  31215. * Specifies if the material needs to be re-calculated.
  31216. */
  31217. get: function () {
  31218. return this._isDirty;
  31219. },
  31220. enumerable: true,
  31221. configurable: true
  31222. });
  31223. /**
  31224. * Marks the material to indicate that it has been re-calculated.
  31225. */
  31226. MaterialDefines.prototype.markAsProcessed = function () {
  31227. this._isDirty = false;
  31228. this._areAttributesDirty = false;
  31229. this._areTexturesDirty = false;
  31230. this._areFresnelDirty = false;
  31231. this._areLightsDirty = false;
  31232. this._areMiscDirty = false;
  31233. this._areImageProcessingDirty = false;
  31234. };
  31235. /**
  31236. * Marks the material to indicate that it needs to be re-calculated.
  31237. */
  31238. MaterialDefines.prototype.markAsUnprocessed = function () {
  31239. this._isDirty = true;
  31240. };
  31241. /**
  31242. * Marks the material to indicate all of its defines need to be re-calculated.
  31243. */
  31244. MaterialDefines.prototype.markAllAsDirty = function () {
  31245. this._areTexturesDirty = true;
  31246. this._areAttributesDirty = true;
  31247. this._areLightsDirty = true;
  31248. this._areFresnelDirty = true;
  31249. this._areMiscDirty = true;
  31250. this._areImageProcessingDirty = true;
  31251. this._isDirty = true;
  31252. };
  31253. /**
  31254. * Marks the material to indicate that image processing needs to be re-calculated.
  31255. */
  31256. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31257. this._areImageProcessingDirty = true;
  31258. this._isDirty = true;
  31259. };
  31260. /**
  31261. * Marks the material to indicate the lights need to be re-calculated.
  31262. */
  31263. MaterialDefines.prototype.markAsLightDirty = function () {
  31264. this._areLightsDirty = true;
  31265. this._isDirty = true;
  31266. };
  31267. /**
  31268. * Marks the attribute state as changed.
  31269. */
  31270. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31271. this._areAttributesDirty = true;
  31272. this._isDirty = true;
  31273. };
  31274. /**
  31275. * Marks the texture state as changed.
  31276. */
  31277. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31278. this._areTexturesDirty = true;
  31279. this._isDirty = true;
  31280. };
  31281. /**
  31282. * Marks the fresnel state as changed.
  31283. */
  31284. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31285. this._areFresnelDirty = true;
  31286. this._isDirty = true;
  31287. };
  31288. /**
  31289. * Marks the misc state as changed.
  31290. */
  31291. MaterialDefines.prototype.markAsMiscDirty = function () {
  31292. this._areMiscDirty = true;
  31293. this._isDirty = true;
  31294. };
  31295. /**
  31296. * Rebuilds the material defines.
  31297. */
  31298. MaterialDefines.prototype.rebuild = function () {
  31299. if (this._keys) {
  31300. delete this._keys;
  31301. }
  31302. this._keys = [];
  31303. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31304. var key = _a[_i];
  31305. if (key[0] === "_") {
  31306. continue;
  31307. }
  31308. this._keys.push(key);
  31309. }
  31310. };
  31311. /**
  31312. * Specifies if two material defines are equal.
  31313. * @param other - A material define instance to compare to.
  31314. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31315. */
  31316. MaterialDefines.prototype.isEqual = function (other) {
  31317. if (this._keys.length !== other._keys.length) {
  31318. return false;
  31319. }
  31320. for (var index = 0; index < this._keys.length; index++) {
  31321. var prop = this._keys[index];
  31322. if (this[prop] !== other[prop]) {
  31323. return false;
  31324. }
  31325. }
  31326. return true;
  31327. };
  31328. /**
  31329. * Clones this instance's defines to another instance.
  31330. * @param other - material defines to clone values to.
  31331. */
  31332. MaterialDefines.prototype.cloneTo = function (other) {
  31333. if (this._keys.length !== other._keys.length) {
  31334. other._keys = this._keys.slice(0);
  31335. }
  31336. for (var index = 0; index < this._keys.length; index++) {
  31337. var prop = this._keys[index];
  31338. other[prop] = this[prop];
  31339. }
  31340. };
  31341. /**
  31342. * Resets the material define values.
  31343. */
  31344. MaterialDefines.prototype.reset = function () {
  31345. for (var index = 0; index < this._keys.length; index++) {
  31346. var prop = this._keys[index];
  31347. var type = typeof this[prop];
  31348. switch (type) {
  31349. case "number":
  31350. this[prop] = 0;
  31351. break;
  31352. case "string":
  31353. this[prop] = "";
  31354. break;
  31355. default:
  31356. this[prop] = false;
  31357. break;
  31358. }
  31359. }
  31360. };
  31361. /**
  31362. * Converts the material define values to a string.
  31363. * @returns - String of material define information.
  31364. */
  31365. MaterialDefines.prototype.toString = function () {
  31366. var result = "";
  31367. for (var index = 0; index < this._keys.length; index++) {
  31368. var prop = this._keys[index];
  31369. var value = this[prop];
  31370. var type = typeof value;
  31371. switch (type) {
  31372. case "number":
  31373. case "string":
  31374. result += "#define " + prop + " " + value + "\n";
  31375. break;
  31376. default:
  31377. if (value) {
  31378. result += "#define " + prop + "\n";
  31379. }
  31380. break;
  31381. }
  31382. }
  31383. return result;
  31384. };
  31385. return MaterialDefines;
  31386. }());
  31387. BABYLON.MaterialDefines = MaterialDefines;
  31388. /**
  31389. * This offers the main features of a material in BJS.
  31390. */
  31391. var Material = /** @class */ (function () {
  31392. /**
  31393. * Creates a material instance.
  31394. * @param name - The name of the material.
  31395. * @param scene - The BJS scene to reference.
  31396. * @param doNotAdd - Specifies if the material should be added to the scene.
  31397. */
  31398. function Material(name, scene, doNotAdd) {
  31399. /**
  31400. * Specifies if the ready state should be checked on each call.
  31401. */
  31402. this.checkReadyOnEveryCall = false;
  31403. /**
  31404. * Specifies if the ready state should be checked once.
  31405. */
  31406. this.checkReadyOnlyOnce = false;
  31407. /**
  31408. * The state of the material.
  31409. */
  31410. this.state = "";
  31411. /**
  31412. * The alpha value of the material.
  31413. */
  31414. this._alpha = 1.0;
  31415. /**
  31416. * Specifies if back face culling is enabled.
  31417. */
  31418. this._backFaceCulling = true;
  31419. /**
  31420. * Specifies if the material should be serialized.
  31421. */
  31422. this.doNotSerialize = false;
  31423. /**
  31424. * Specifies if the effect should be stored on sub meshes.
  31425. */
  31426. this.storeEffectOnSubMeshes = false;
  31427. /**
  31428. * An event triggered when the material is disposed.
  31429. */
  31430. this.onDisposeObservable = new BABYLON.Observable();
  31431. /**
  31432. * An event triggered when the material is bound.
  31433. */
  31434. this.onBindObservable = new BABYLON.Observable();
  31435. /**
  31436. * An event triggered when the material is unbound.
  31437. */
  31438. this.onUnBindObservable = new BABYLON.Observable();
  31439. /**
  31440. * Stores the value of the alpha mode.
  31441. */
  31442. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31443. /**
  31444. * Stores the state of the need depth pre-pass value.
  31445. */
  31446. this._needDepthPrePass = false;
  31447. /**
  31448. * Specifies if depth writing should be disabled.
  31449. */
  31450. this.disableDepthWrite = false;
  31451. /**
  31452. * Specifies if depth writing should be forced.
  31453. */
  31454. this.forceDepthWrite = false;
  31455. /**
  31456. * Specifies if there should be a separate pass for culling.
  31457. */
  31458. this.separateCullingPass = false;
  31459. /**
  31460. * Stores the state specifing if fog should be enabled.
  31461. */
  31462. this._fogEnabled = true;
  31463. /**
  31464. * Stores the size of points.
  31465. */
  31466. this.pointSize = 1.0;
  31467. /**
  31468. * Stores the z offset value.
  31469. */
  31470. this.zOffset = 0;
  31471. /**
  31472. * Specifies if the material was previously ready.
  31473. */
  31474. this._wasPreviouslyReady = false;
  31475. /**
  31476. * Stores the fill mode state.
  31477. */
  31478. this._fillMode = Material.TriangleFillMode;
  31479. this.name = name;
  31480. this.id = name || BABYLON.Tools.RandomId();
  31481. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31482. if (this._scene.useRightHandedSystem) {
  31483. this.sideOrientation = Material.ClockWiseSideOrientation;
  31484. }
  31485. else {
  31486. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31487. }
  31488. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31489. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31490. if (!doNotAdd) {
  31491. this._scene.materials.push(this);
  31492. }
  31493. }
  31494. Object.defineProperty(Material, "TriangleFillMode", {
  31495. /**
  31496. * Returns the triangle fill mode.
  31497. */
  31498. get: function () {
  31499. return Material._TriangleFillMode;
  31500. },
  31501. enumerable: true,
  31502. configurable: true
  31503. });
  31504. Object.defineProperty(Material, "WireFrameFillMode", {
  31505. /**
  31506. * Returns the wireframe mode.
  31507. */
  31508. get: function () {
  31509. return Material._WireFrameFillMode;
  31510. },
  31511. enumerable: true,
  31512. configurable: true
  31513. });
  31514. Object.defineProperty(Material, "PointFillMode", {
  31515. /**
  31516. * Returns the point fill mode.
  31517. */
  31518. get: function () {
  31519. return Material._PointFillMode;
  31520. },
  31521. enumerable: true,
  31522. configurable: true
  31523. });
  31524. Object.defineProperty(Material, "PointListDrawMode", {
  31525. /**
  31526. * Returns the point list draw mode.
  31527. */
  31528. get: function () {
  31529. return Material._PointListDrawMode;
  31530. },
  31531. enumerable: true,
  31532. configurable: true
  31533. });
  31534. Object.defineProperty(Material, "LineListDrawMode", {
  31535. /**
  31536. * Returns the line list draw mode.
  31537. */
  31538. get: function () {
  31539. return Material._LineListDrawMode;
  31540. },
  31541. enumerable: true,
  31542. configurable: true
  31543. });
  31544. Object.defineProperty(Material, "LineLoopDrawMode", {
  31545. /**
  31546. * Returns the line loop draw mode.
  31547. */
  31548. get: function () {
  31549. return Material._LineLoopDrawMode;
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(Material, "LineStripDrawMode", {
  31555. /**
  31556. * Returns the line strip draw mode.
  31557. */
  31558. get: function () {
  31559. return Material._LineStripDrawMode;
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31565. /**
  31566. * Returns the triangle strip draw mode.
  31567. */
  31568. get: function () {
  31569. return Material._TriangleStripDrawMode;
  31570. },
  31571. enumerable: true,
  31572. configurable: true
  31573. });
  31574. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31575. /**
  31576. * Returns the triangle fan draw mode.
  31577. */
  31578. get: function () {
  31579. return Material._TriangleFanDrawMode;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31585. /**
  31586. * Returns the clock-wise side orientation.
  31587. */
  31588. get: function () {
  31589. return Material._ClockWiseSideOrientation;
  31590. },
  31591. enumerable: true,
  31592. configurable: true
  31593. });
  31594. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31595. /**
  31596. * Returns the counter clock-wise side orientation.
  31597. */
  31598. get: function () {
  31599. return Material._CounterClockWiseSideOrientation;
  31600. },
  31601. enumerable: true,
  31602. configurable: true
  31603. });
  31604. Object.defineProperty(Material, "TextureDirtyFlag", {
  31605. /**
  31606. * Returns the dirty texture flag value.
  31607. */
  31608. get: function () {
  31609. return Material._TextureDirtyFlag;
  31610. },
  31611. enumerable: true,
  31612. configurable: true
  31613. });
  31614. Object.defineProperty(Material, "LightDirtyFlag", {
  31615. /**
  31616. * Returns the dirty light flag value.
  31617. */
  31618. get: function () {
  31619. return Material._LightDirtyFlag;
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31625. /**
  31626. * Returns the dirty fresnel flag value.
  31627. */
  31628. get: function () {
  31629. return Material._FresnelDirtyFlag;
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31635. /**
  31636. * Returns the dirty attributes flag value.
  31637. */
  31638. get: function () {
  31639. return Material._AttributesDirtyFlag;
  31640. },
  31641. enumerable: true,
  31642. configurable: true
  31643. });
  31644. Object.defineProperty(Material, "MiscDirtyFlag", {
  31645. /**
  31646. * Returns the dirty misc flag value.
  31647. */
  31648. get: function () {
  31649. return Material._MiscDirtyFlag;
  31650. },
  31651. enumerable: true,
  31652. configurable: true
  31653. });
  31654. Object.defineProperty(Material.prototype, "alpha", {
  31655. /**
  31656. * Gets the alpha value of the material.
  31657. */
  31658. get: function () {
  31659. return this._alpha;
  31660. },
  31661. /**
  31662. * Sets the alpha value of the material.
  31663. */
  31664. set: function (value) {
  31665. if (this._alpha === value) {
  31666. return;
  31667. }
  31668. this._alpha = value;
  31669. this.markAsDirty(Material.MiscDirtyFlag);
  31670. },
  31671. enumerable: true,
  31672. configurable: true
  31673. });
  31674. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31675. /**
  31676. * Gets the back-face culling state.
  31677. */
  31678. get: function () {
  31679. return this._backFaceCulling;
  31680. },
  31681. /**
  31682. * Sets the back-face culling state.
  31683. */
  31684. set: function (value) {
  31685. if (this._backFaceCulling === value) {
  31686. return;
  31687. }
  31688. this._backFaceCulling = value;
  31689. this.markAsDirty(Material.TextureDirtyFlag);
  31690. },
  31691. enumerable: true,
  31692. configurable: true
  31693. });
  31694. Object.defineProperty(Material.prototype, "onDispose", {
  31695. /**
  31696. * Called during a dispose event.
  31697. */
  31698. set: function (callback) {
  31699. if (this._onDisposeObserver) {
  31700. this.onDisposeObservable.remove(this._onDisposeObserver);
  31701. }
  31702. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31703. },
  31704. enumerable: true,
  31705. configurable: true
  31706. });
  31707. Object.defineProperty(Material.prototype, "onBind", {
  31708. /**
  31709. * Called during a bind event.
  31710. */
  31711. set: function (callback) {
  31712. if (this._onBindObserver) {
  31713. this.onBindObservable.remove(this._onBindObserver);
  31714. }
  31715. this._onBindObserver = this.onBindObservable.add(callback);
  31716. },
  31717. enumerable: true,
  31718. configurable: true
  31719. });
  31720. Object.defineProperty(Material.prototype, "alphaMode", {
  31721. /**
  31722. * Gets the value of the alpha mode.
  31723. */
  31724. get: function () {
  31725. return this._alphaMode;
  31726. },
  31727. /**
  31728. * Sets the value of the alpha mode.
  31729. *
  31730. * | Value | Type | Description |
  31731. * | --- | --- | --- |
  31732. * | 0 | ALPHA_DISABLE | |
  31733. * | 1 | ALPHA_ADD | |
  31734. * | 2 | ALPHA_COMBINE | |
  31735. * | 3 | ALPHA_SUBTRACT | |
  31736. * | 4 | ALPHA_MULTIPLY | |
  31737. * | 5 | ALPHA_MAXIMIZED | |
  31738. * | 6 | ALPHA_ONEONE | |
  31739. * | 7 | ALPHA_PREMULTIPLIED | |
  31740. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  31741. * | 9 | ALPHA_INTERPOLATE | |
  31742. * | 10 | ALPHA_SCREENMODE | |
  31743. *
  31744. */
  31745. set: function (value) {
  31746. if (this._alphaMode === value) {
  31747. return;
  31748. }
  31749. this._alphaMode = value;
  31750. this.markAsDirty(Material.TextureDirtyFlag);
  31751. },
  31752. enumerable: true,
  31753. configurable: true
  31754. });
  31755. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31756. /**
  31757. * Gets the depth pre-pass value.
  31758. */
  31759. get: function () {
  31760. return this._needDepthPrePass;
  31761. },
  31762. /**
  31763. * Sets the need depth pre-pass value.
  31764. */
  31765. set: function (value) {
  31766. if (this._needDepthPrePass === value) {
  31767. return;
  31768. }
  31769. this._needDepthPrePass = value;
  31770. if (this._needDepthPrePass) {
  31771. this.checkReadyOnEveryCall = true;
  31772. }
  31773. },
  31774. enumerable: true,
  31775. configurable: true
  31776. });
  31777. Object.defineProperty(Material.prototype, "fogEnabled", {
  31778. /**
  31779. * Gets the value of the fog enabled state.
  31780. */
  31781. get: function () {
  31782. return this._fogEnabled;
  31783. },
  31784. /**
  31785. * Sets the state for enabling fog.
  31786. */
  31787. set: function (value) {
  31788. if (this._fogEnabled === value) {
  31789. return;
  31790. }
  31791. this._fogEnabled = value;
  31792. this.markAsDirty(Material.MiscDirtyFlag);
  31793. },
  31794. enumerable: true,
  31795. configurable: true
  31796. });
  31797. Object.defineProperty(Material.prototype, "wireframe", {
  31798. /**
  31799. * Gets a value specifying if wireframe mode is enabled.
  31800. */
  31801. get: function () {
  31802. switch (this._fillMode) {
  31803. case Material.WireFrameFillMode:
  31804. case Material.LineListDrawMode:
  31805. case Material.LineLoopDrawMode:
  31806. case Material.LineStripDrawMode:
  31807. return true;
  31808. }
  31809. return this._scene.forceWireframe;
  31810. },
  31811. /**
  31812. * Sets the state of wireframe mode.
  31813. */
  31814. set: function (value) {
  31815. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31816. },
  31817. enumerable: true,
  31818. configurable: true
  31819. });
  31820. Object.defineProperty(Material.prototype, "pointsCloud", {
  31821. /**
  31822. * Gets the value specifying if point clouds are enabled.
  31823. */
  31824. get: function () {
  31825. switch (this._fillMode) {
  31826. case Material.PointFillMode:
  31827. case Material.PointListDrawMode:
  31828. return true;
  31829. }
  31830. return this._scene.forcePointsCloud;
  31831. },
  31832. /**
  31833. * Sets the state of point cloud mode.
  31834. */
  31835. set: function (value) {
  31836. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31837. },
  31838. enumerable: true,
  31839. configurable: true
  31840. });
  31841. Object.defineProperty(Material.prototype, "fillMode", {
  31842. /**
  31843. * Gets the material fill mode.
  31844. */
  31845. get: function () {
  31846. return this._fillMode;
  31847. },
  31848. /**
  31849. * Sets the material fill mode.
  31850. */
  31851. set: function (value) {
  31852. if (this._fillMode === value) {
  31853. return;
  31854. }
  31855. this._fillMode = value;
  31856. this.markAsDirty(Material.MiscDirtyFlag);
  31857. },
  31858. enumerable: true,
  31859. configurable: true
  31860. });
  31861. /**
  31862. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31863. * subclasses should override adding information pertainent to themselves.
  31864. * @returns - String with material information.
  31865. */
  31866. Material.prototype.toString = function (fullDetails) {
  31867. var ret = "Name: " + this.name;
  31868. if (fullDetails) {
  31869. }
  31870. return ret;
  31871. };
  31872. /**
  31873. * Gets the class name of the material.
  31874. * @returns - String with the class name of the material.
  31875. */
  31876. Material.prototype.getClassName = function () {
  31877. return "Material";
  31878. };
  31879. Object.defineProperty(Material.prototype, "isFrozen", {
  31880. /**
  31881. * Specifies if updates for the material been locked.
  31882. */
  31883. get: function () {
  31884. return this.checkReadyOnlyOnce;
  31885. },
  31886. enumerable: true,
  31887. configurable: true
  31888. });
  31889. /**
  31890. * Locks updates for the material.
  31891. */
  31892. Material.prototype.freeze = function () {
  31893. this.checkReadyOnlyOnce = true;
  31894. };
  31895. /**
  31896. * Unlocks updates for the material.
  31897. */
  31898. Material.prototype.unfreeze = function () {
  31899. this.checkReadyOnlyOnce = false;
  31900. };
  31901. /**
  31902. * Specifies if the material is ready to be used.
  31903. * @param mesh - BJS mesh.
  31904. * @param useInstances - Specifies if instances should be used.
  31905. * @returns - Boolean indicating if the material is ready to be used.
  31906. */
  31907. Material.prototype.isReady = function (mesh, useInstances) {
  31908. return true;
  31909. };
  31910. /**
  31911. * Specifies that the submesh is ready to be used.
  31912. * @param mesh - BJS mesh.
  31913. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31914. * @param useInstances - Specifies that instances should be used.
  31915. * @returns - boolean indicating that the submesh is ready or not.
  31916. */
  31917. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31918. return false;
  31919. };
  31920. /**
  31921. * Returns the material effect.
  31922. * @returns - Nullable material effect.
  31923. */
  31924. Material.prototype.getEffect = function () {
  31925. return this._effect;
  31926. };
  31927. /**
  31928. * Returns the BJS scene.
  31929. * @returns - BJS Scene.
  31930. */
  31931. Material.prototype.getScene = function () {
  31932. return this._scene;
  31933. };
  31934. /**
  31935. * Specifies if the material will require alpha blending
  31936. * @returns - Boolean specifying if alpha blending is needed.
  31937. */
  31938. Material.prototype.needAlphaBlending = function () {
  31939. return (this.alpha < 1.0);
  31940. };
  31941. /**
  31942. * Specifies if the mesh will require alpha blending.
  31943. * @param mesh - BJS mesh.
  31944. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31945. */
  31946. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31947. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31948. };
  31949. /**
  31950. * Specifies if this material should be rendered in alpha test mode.
  31951. * @returns - Boolean specifying if an alpha test is needed.
  31952. */
  31953. Material.prototype.needAlphaTesting = function () {
  31954. return false;
  31955. };
  31956. /**
  31957. * Gets the texture used for the alpha test.
  31958. * @returns - Nullable alpha test texture.
  31959. */
  31960. Material.prototype.getAlphaTestTexture = function () {
  31961. return null;
  31962. };
  31963. /**
  31964. * Marks the material to indicate that it needs to be re-calculated.
  31965. */
  31966. Material.prototype.markDirty = function () {
  31967. this._wasPreviouslyReady = false;
  31968. };
  31969. Material.prototype._preBind = function (effect, overrideOrientation) {
  31970. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31971. var engine = this._scene.getEngine();
  31972. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31973. var reverse = orientation === Material.ClockWiseSideOrientation;
  31974. engine.enableEffect(effect ? effect : this._effect);
  31975. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31976. return reverse;
  31977. };
  31978. /**
  31979. * Binds the material to the mesh.
  31980. * @param world - World transformation matrix.
  31981. * @param mesh - Mesh to bind the material to.
  31982. */
  31983. Material.prototype.bind = function (world, mesh) {
  31984. };
  31985. /**
  31986. * Binds the submesh to the material.
  31987. * @param world - World transformation matrix.
  31988. * @param mesh - Mesh containing the submesh.
  31989. * @param subMesh - Submesh to bind the material to.
  31990. */
  31991. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31992. };
  31993. /**
  31994. * Binds the world matrix to the material.
  31995. * @param world - World transformation matrix.
  31996. */
  31997. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31998. };
  31999. /**
  32000. * Binds the scene's uniform buffer to the effect.
  32001. * @param effect - Effect to bind to the scene uniform buffer.
  32002. * @param sceneUbo - Scene uniform buffer.
  32003. */
  32004. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  32005. sceneUbo.bindToEffect(effect, "Scene");
  32006. };
  32007. /**
  32008. * Binds the view matrix to the effect.
  32009. * @param effect - Effect to bind the view matrix to.
  32010. */
  32011. Material.prototype.bindView = function (effect) {
  32012. if (!this._useUBO) {
  32013. effect.setMatrix("view", this.getScene().getViewMatrix());
  32014. }
  32015. else {
  32016. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32017. }
  32018. };
  32019. /**
  32020. * Binds the view projection matrix to the effect.
  32021. * @param effect - Effect to bind the view projection matrix to.
  32022. */
  32023. Material.prototype.bindViewProjection = function (effect) {
  32024. if (!this._useUBO) {
  32025. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32026. }
  32027. else {
  32028. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32029. }
  32030. };
  32031. /**
  32032. * Specifies if material alpha testing should be turned on for the mesh.
  32033. * @param mesh - BJS mesh.
  32034. */
  32035. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  32036. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  32037. };
  32038. /**
  32039. * Processes to execute after binding the material to a mesh.
  32040. * @param mesh - BJS mesh.
  32041. */
  32042. Material.prototype._afterBind = function (mesh) {
  32043. this._scene._cachedMaterial = this;
  32044. if (mesh) {
  32045. this._scene._cachedVisibility = mesh.visibility;
  32046. }
  32047. else {
  32048. this._scene._cachedVisibility = 1;
  32049. }
  32050. if (mesh) {
  32051. this.onBindObservable.notifyObservers(mesh);
  32052. }
  32053. if (this.disableDepthWrite) {
  32054. var engine = this._scene.getEngine();
  32055. this._cachedDepthWriteState = engine.getDepthWrite();
  32056. engine.setDepthWrite(false);
  32057. }
  32058. };
  32059. /**
  32060. * Unbinds the material from the mesh.
  32061. */
  32062. Material.prototype.unbind = function () {
  32063. this.onUnBindObservable.notifyObservers(this);
  32064. if (this.disableDepthWrite) {
  32065. var engine = this._scene.getEngine();
  32066. engine.setDepthWrite(this._cachedDepthWriteState);
  32067. }
  32068. };
  32069. /**
  32070. * Gets the active textures from the material.
  32071. * @returns - Array of textures.
  32072. */
  32073. Material.prototype.getActiveTextures = function () {
  32074. return [];
  32075. };
  32076. /**
  32077. * Specifies if the material uses a texture.
  32078. * @param texture - Texture to check against the material.
  32079. * @returns - Boolean specifying if the material uses the texture.
  32080. */
  32081. Material.prototype.hasTexture = function (texture) {
  32082. return false;
  32083. };
  32084. /**
  32085. * Makes a duplicate of the material, and gives it a new name.
  32086. * @param name - Name to call the duplicated material.
  32087. * @returns - Nullable cloned material
  32088. */
  32089. Material.prototype.clone = function (name) {
  32090. return null;
  32091. };
  32092. /**
  32093. * Gets the meshes bound to the material.
  32094. * @returns - Array of meshes bound to the material.
  32095. */
  32096. Material.prototype.getBindedMeshes = function () {
  32097. var result = new Array();
  32098. for (var index = 0; index < this._scene.meshes.length; index++) {
  32099. var mesh = this._scene.meshes[index];
  32100. if (mesh.material === this) {
  32101. result.push(mesh);
  32102. }
  32103. }
  32104. return result;
  32105. };
  32106. /**
  32107. * Force shader compilation
  32108. * @param mesh - BJS mesh.
  32109. * @param onCompiled - function to execute once the material is compiled.
  32110. * @param options - options to pass to this function.
  32111. */
  32112. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32113. var _this = this;
  32114. var localOptions = __assign({ clipPlane: false }, options);
  32115. var subMesh = new BABYLON.BaseSubMesh();
  32116. var scene = this.getScene();
  32117. var checkReady = function () {
  32118. if (!_this._scene || !_this._scene.getEngine()) {
  32119. return;
  32120. }
  32121. if (subMesh._materialDefines) {
  32122. subMesh._materialDefines._renderId = -1;
  32123. }
  32124. var clipPlaneState = scene.clipPlane;
  32125. if (localOptions.clipPlane) {
  32126. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32127. }
  32128. if (_this.storeEffectOnSubMeshes) {
  32129. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32130. if (onCompiled) {
  32131. onCompiled(_this);
  32132. }
  32133. }
  32134. else {
  32135. setTimeout(checkReady, 16);
  32136. }
  32137. }
  32138. else {
  32139. if (_this.isReady(mesh)) {
  32140. if (onCompiled) {
  32141. onCompiled(_this);
  32142. }
  32143. }
  32144. else {
  32145. setTimeout(checkReady, 16);
  32146. }
  32147. }
  32148. if (localOptions.clipPlane) {
  32149. scene.clipPlane = clipPlaneState;
  32150. }
  32151. };
  32152. checkReady();
  32153. };
  32154. /**
  32155. * Force shader compilation.
  32156. * @param mesh The mesh that will use this material
  32157. * @param options Additional options for compiling the shaders
  32158. * @returns A promise that resolves when the compilation completes
  32159. */
  32160. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32161. var _this = this;
  32162. return new Promise(function (resolve) {
  32163. _this.forceCompilation(mesh, function () {
  32164. resolve();
  32165. }, options);
  32166. });
  32167. };
  32168. /**
  32169. * Marks a define in the material to indicate that it needs to be re-computed.
  32170. * @param flag - Material define flag.
  32171. */
  32172. Material.prototype.markAsDirty = function (flag) {
  32173. if (flag & Material.TextureDirtyFlag) {
  32174. this._markAllSubMeshesAsTexturesDirty();
  32175. }
  32176. if (flag & Material.LightDirtyFlag) {
  32177. this._markAllSubMeshesAsLightsDirty();
  32178. }
  32179. if (flag & Material.FresnelDirtyFlag) {
  32180. this._markAllSubMeshesAsFresnelDirty();
  32181. }
  32182. if (flag & Material.AttributesDirtyFlag) {
  32183. this._markAllSubMeshesAsAttributesDirty();
  32184. }
  32185. if (flag & Material.MiscDirtyFlag) {
  32186. this._markAllSubMeshesAsMiscDirty();
  32187. }
  32188. this.getScene().resetCachedMaterial();
  32189. };
  32190. /**
  32191. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32192. * @param func - function which checks material defines against the submeshes.
  32193. */
  32194. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32195. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32196. var mesh = _a[_i];
  32197. if (!mesh.subMeshes) {
  32198. continue;
  32199. }
  32200. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32201. var subMesh = _c[_b];
  32202. if (subMesh.getMaterial() !== this) {
  32203. continue;
  32204. }
  32205. if (!subMesh._materialDefines) {
  32206. continue;
  32207. }
  32208. func(subMesh._materialDefines);
  32209. }
  32210. }
  32211. };
  32212. /**
  32213. * Indicates that image processing needs to be re-calculated for all submeshes.
  32214. */
  32215. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32216. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32217. };
  32218. /**
  32219. * Indicates that textures need to be re-calculated for all submeshes.
  32220. */
  32221. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32222. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32223. };
  32224. /**
  32225. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32226. */
  32227. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32228. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32229. };
  32230. /**
  32231. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32232. */
  32233. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32234. this._markAllSubMeshesAsDirty(function (defines) {
  32235. defines.markAsFresnelDirty();
  32236. defines.markAsMiscDirty();
  32237. });
  32238. };
  32239. /**
  32240. * Indicates that lights need to be re-calculated for all submeshes.
  32241. */
  32242. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32243. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32244. };
  32245. /**
  32246. * Indicates that attributes need to be re-calculated for all submeshes.
  32247. */
  32248. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32249. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32250. };
  32251. /**
  32252. * Indicates that misc needs to be re-calculated for all submeshes.
  32253. */
  32254. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32255. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32256. };
  32257. /**
  32258. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32259. */
  32260. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32261. this._markAllSubMeshesAsDirty(function (defines) {
  32262. defines.markAsTexturesDirty();
  32263. defines.markAsMiscDirty();
  32264. });
  32265. };
  32266. /**
  32267. * Disposes the material.
  32268. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32269. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32270. */
  32271. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32272. // Animations
  32273. this.getScene().stopAnimation(this);
  32274. this.getScene().freeProcessedMaterials();
  32275. // Remove from scene
  32276. var index = this._scene.materials.indexOf(this);
  32277. if (index >= 0) {
  32278. this._scene.materials.splice(index, 1);
  32279. }
  32280. // Remove from meshes
  32281. for (index = 0; index < this._scene.meshes.length; index++) {
  32282. var mesh = this._scene.meshes[index];
  32283. if (mesh.material === this) {
  32284. mesh.material = null;
  32285. if (mesh.geometry) {
  32286. var geometry = (mesh.geometry);
  32287. if (this.storeEffectOnSubMeshes) {
  32288. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32289. var subMesh = _a[_i];
  32290. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32291. if (forceDisposeEffect && subMesh._materialEffect) {
  32292. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32293. }
  32294. }
  32295. }
  32296. else {
  32297. geometry._releaseVertexArrayObject(this._effect);
  32298. }
  32299. }
  32300. }
  32301. }
  32302. this._uniformBuffer.dispose();
  32303. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32304. if (forceDisposeEffect && this._effect) {
  32305. if (!this.storeEffectOnSubMeshes) {
  32306. this._scene.getEngine()._releaseEffect(this._effect);
  32307. }
  32308. this._effect = null;
  32309. }
  32310. // Callback
  32311. this.onDisposeObservable.notifyObservers(this);
  32312. this.onDisposeObservable.clear();
  32313. this.onBindObservable.clear();
  32314. this.onUnBindObservable.clear();
  32315. };
  32316. /**
  32317. * Serializes this material.
  32318. * @returns - serialized material object.
  32319. */
  32320. Material.prototype.serialize = function () {
  32321. return BABYLON.SerializationHelper.Serialize(this);
  32322. };
  32323. /**
  32324. * Creates a MultiMaterial from parse MultiMaterial data.
  32325. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32326. * @param scene - BJS scene.
  32327. * @returns - MultiMaterial.
  32328. */
  32329. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32330. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32331. multiMaterial.id = parsedMultiMaterial.id;
  32332. if (BABYLON.Tags) {
  32333. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32334. }
  32335. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32336. var subMatId = parsedMultiMaterial.materials[matIndex];
  32337. if (subMatId) {
  32338. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32339. }
  32340. else {
  32341. multiMaterial.subMaterials.push(null);
  32342. }
  32343. }
  32344. return multiMaterial;
  32345. };
  32346. /**
  32347. * Creates a material from parsed material data.
  32348. * @param parsedMaterial - Parsed material data.
  32349. * @param scene - BJS scene.
  32350. * @param rootUrl - Root URL containing the material information.
  32351. * @returns - Parsed material.
  32352. */
  32353. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32354. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32355. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32356. }
  32357. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32358. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32359. if (!BABYLON.LegacyPBRMaterial) {
  32360. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32361. return;
  32362. }
  32363. }
  32364. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32365. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32366. ;
  32367. };
  32368. // Triangle views
  32369. Material._TriangleFillMode = 0;
  32370. Material._WireFrameFillMode = 1;
  32371. Material._PointFillMode = 2;
  32372. // Draw modes
  32373. Material._PointListDrawMode = 3;
  32374. Material._LineListDrawMode = 4;
  32375. Material._LineLoopDrawMode = 5;
  32376. Material._LineStripDrawMode = 6;
  32377. Material._TriangleStripDrawMode = 7;
  32378. Material._TriangleFanDrawMode = 8;
  32379. /**
  32380. * Stores the clock-wise side orientation.
  32381. */
  32382. Material._ClockWiseSideOrientation = 0;
  32383. /**
  32384. * Stores the counter clock-wise side orientation.
  32385. */
  32386. Material._CounterClockWiseSideOrientation = 1;
  32387. /**
  32388. * The dirty texture flag value.
  32389. */
  32390. Material._TextureDirtyFlag = 1;
  32391. /**
  32392. * The dirty light flag value.
  32393. */
  32394. Material._LightDirtyFlag = 2;
  32395. /**
  32396. * The dirty fresnel flag value.
  32397. */
  32398. Material._FresnelDirtyFlag = 4;
  32399. /**
  32400. * The dirty attribute flag value.
  32401. */
  32402. Material._AttributesDirtyFlag = 8;
  32403. /**
  32404. * The dirty misc flag value.
  32405. */
  32406. Material._MiscDirtyFlag = 16;
  32407. __decorate([
  32408. BABYLON.serialize()
  32409. ], Material.prototype, "id", void 0);
  32410. __decorate([
  32411. BABYLON.serialize()
  32412. ], Material.prototype, "name", void 0);
  32413. __decorate([
  32414. BABYLON.serialize()
  32415. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32416. __decorate([
  32417. BABYLON.serialize()
  32418. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32419. __decorate([
  32420. BABYLON.serialize()
  32421. ], Material.prototype, "state", void 0);
  32422. __decorate([
  32423. BABYLON.serialize("alpha")
  32424. ], Material.prototype, "_alpha", void 0);
  32425. __decorate([
  32426. BABYLON.serialize("backFaceCulling")
  32427. ], Material.prototype, "_backFaceCulling", void 0);
  32428. __decorate([
  32429. BABYLON.serialize()
  32430. ], Material.prototype, "sideOrientation", void 0);
  32431. __decorate([
  32432. BABYLON.serialize("alphaMode")
  32433. ], Material.prototype, "_alphaMode", void 0);
  32434. __decorate([
  32435. BABYLON.serialize()
  32436. ], Material.prototype, "_needDepthPrePass", void 0);
  32437. __decorate([
  32438. BABYLON.serialize()
  32439. ], Material.prototype, "disableDepthWrite", void 0);
  32440. __decorate([
  32441. BABYLON.serialize()
  32442. ], Material.prototype, "forceDepthWrite", void 0);
  32443. __decorate([
  32444. BABYLON.serialize()
  32445. ], Material.prototype, "separateCullingPass", void 0);
  32446. __decorate([
  32447. BABYLON.serialize("fogEnabled")
  32448. ], Material.prototype, "_fogEnabled", void 0);
  32449. __decorate([
  32450. BABYLON.serialize()
  32451. ], Material.prototype, "pointSize", void 0);
  32452. __decorate([
  32453. BABYLON.serialize()
  32454. ], Material.prototype, "zOffset", void 0);
  32455. __decorate([
  32456. BABYLON.serialize()
  32457. ], Material.prototype, "wireframe", null);
  32458. __decorate([
  32459. BABYLON.serialize()
  32460. ], Material.prototype, "pointsCloud", null);
  32461. __decorate([
  32462. BABYLON.serialize()
  32463. ], Material.prototype, "fillMode", null);
  32464. return Material;
  32465. }());
  32466. BABYLON.Material = Material;
  32467. })(BABYLON || (BABYLON = {}));
  32468. //# sourceMappingURL=babylon.material.js.map
  32469. "use strict";
  32470. var BABYLON;
  32471. (function (BABYLON) {
  32472. var UniformBuffer = /** @class */ (function () {
  32473. /**
  32474. * Uniform buffer objects.
  32475. *
  32476. * Handles blocks of uniform on the GPU.
  32477. *
  32478. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32479. *
  32480. * For more information, please refer to :
  32481. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32482. */
  32483. function UniformBuffer(engine, data, dynamic) {
  32484. this._engine = engine;
  32485. this._noUBO = !engine.supportsUniformBuffers;
  32486. this._dynamic = dynamic;
  32487. this._data = data || [];
  32488. this._uniformLocations = {};
  32489. this._uniformSizes = {};
  32490. this._uniformLocationPointer = 0;
  32491. this._needSync = false;
  32492. if (this._noUBO) {
  32493. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32494. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32495. this.updateFloat = this._updateFloatForEffect;
  32496. this.updateFloat2 = this._updateFloat2ForEffect;
  32497. this.updateFloat3 = this._updateFloat3ForEffect;
  32498. this.updateFloat4 = this._updateFloat4ForEffect;
  32499. this.updateMatrix = this._updateMatrixForEffect;
  32500. this.updateVector3 = this._updateVector3ForEffect;
  32501. this.updateVector4 = this._updateVector4ForEffect;
  32502. this.updateColor3 = this._updateColor3ForEffect;
  32503. this.updateColor4 = this._updateColor4ForEffect;
  32504. }
  32505. else {
  32506. this._engine._uniformBuffers.push(this);
  32507. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32508. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32509. this.updateFloat = this._updateFloatForUniform;
  32510. this.updateFloat2 = this._updateFloat2ForUniform;
  32511. this.updateFloat3 = this._updateFloat3ForUniform;
  32512. this.updateFloat4 = this._updateFloat4ForUniform;
  32513. this.updateMatrix = this._updateMatrixForUniform;
  32514. this.updateVector3 = this._updateVector3ForUniform;
  32515. this.updateVector4 = this._updateVector4ForUniform;
  32516. this.updateColor3 = this._updateColor3ForUniform;
  32517. this.updateColor4 = this._updateColor4ForUniform;
  32518. }
  32519. }
  32520. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32521. // Properties
  32522. /**
  32523. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32524. * or just falling back on setUniformXXX calls.
  32525. */
  32526. get: function () {
  32527. return !this._noUBO;
  32528. },
  32529. enumerable: true,
  32530. configurable: true
  32531. });
  32532. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32533. /**
  32534. * Indicates if the WebGL underlying uniform buffer is in sync
  32535. * with the javascript cache data.
  32536. */
  32537. get: function () {
  32538. return !this._needSync;
  32539. },
  32540. enumerable: true,
  32541. configurable: true
  32542. });
  32543. /**
  32544. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32545. * Also, a dynamic UniformBuffer will disable cache verification and always
  32546. * update the underlying WebGL uniform buffer to the GPU.
  32547. */
  32548. UniformBuffer.prototype.isDynamic = function () {
  32549. return this._dynamic !== undefined;
  32550. };
  32551. /**
  32552. * The data cache on JS side.
  32553. */
  32554. UniformBuffer.prototype.getData = function () {
  32555. return this._bufferData;
  32556. };
  32557. /**
  32558. * The underlying WebGL Uniform buffer.
  32559. */
  32560. UniformBuffer.prototype.getBuffer = function () {
  32561. return this._buffer;
  32562. };
  32563. /**
  32564. * std140 layout specifies how to align data within an UBO structure.
  32565. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32566. * for specs.
  32567. */
  32568. UniformBuffer.prototype._fillAlignment = function (size) {
  32569. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32570. // and 4x4 matrices
  32571. // TODO : change if other types are used
  32572. var alignment;
  32573. if (size <= 2) {
  32574. alignment = size;
  32575. }
  32576. else {
  32577. alignment = 4;
  32578. }
  32579. if ((this._uniformLocationPointer % alignment) !== 0) {
  32580. var oldPointer = this._uniformLocationPointer;
  32581. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32582. var diff = this._uniformLocationPointer - oldPointer;
  32583. for (var i = 0; i < diff; i++) {
  32584. this._data.push(0);
  32585. }
  32586. }
  32587. };
  32588. /**
  32589. * Adds an uniform in the buffer.
  32590. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32591. * for the layout to be correct !
  32592. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32593. * @param {number|number[]} size Data size, or data directly.
  32594. */
  32595. UniformBuffer.prototype.addUniform = function (name, size) {
  32596. if (this._noUBO) {
  32597. return;
  32598. }
  32599. if (this._uniformLocations[name] !== undefined) {
  32600. // Already existing uniform
  32601. return;
  32602. }
  32603. // This function must be called in the order of the shader layout !
  32604. // size can be the size of the uniform, or data directly
  32605. var data;
  32606. if (size instanceof Array) {
  32607. data = size;
  32608. size = data.length;
  32609. }
  32610. else {
  32611. size = size;
  32612. data = [];
  32613. // Fill with zeros
  32614. for (var i = 0; i < size; i++) {
  32615. data.push(0);
  32616. }
  32617. }
  32618. this._fillAlignment(size);
  32619. this._uniformSizes[name] = size;
  32620. this._uniformLocations[name] = this._uniformLocationPointer;
  32621. this._uniformLocationPointer += size;
  32622. for (var i = 0; i < size; i++) {
  32623. this._data.push(data[i]);
  32624. }
  32625. this._needSync = true;
  32626. };
  32627. /**
  32628. * Wrapper for addUniform.
  32629. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32630. * @param {Matrix} mat A 4x4 matrix.
  32631. */
  32632. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32633. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32634. };
  32635. /**
  32636. * Wrapper for addUniform.
  32637. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32638. * @param {number} x
  32639. * @param {number} y
  32640. */
  32641. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32642. var temp = [x, y];
  32643. this.addUniform(name, temp);
  32644. };
  32645. /**
  32646. * Wrapper for addUniform.
  32647. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32648. * @param {number} x
  32649. * @param {number} y
  32650. * @param {number} z
  32651. */
  32652. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32653. var temp = [x, y, z];
  32654. this.addUniform(name, temp);
  32655. };
  32656. /**
  32657. * Wrapper for addUniform.
  32658. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32659. * @param {Color3} color
  32660. */
  32661. UniformBuffer.prototype.addColor3 = function (name, color) {
  32662. var temp = new Array();
  32663. color.toArray(temp);
  32664. this.addUniform(name, temp);
  32665. };
  32666. /**
  32667. * Wrapper for addUniform.
  32668. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32669. * @param {Color3} color
  32670. * @param {number} alpha
  32671. */
  32672. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32673. var temp = new Array();
  32674. color.toArray(temp);
  32675. temp.push(alpha);
  32676. this.addUniform(name, temp);
  32677. };
  32678. /**
  32679. * Wrapper for addUniform.
  32680. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32681. * @param {Vector3} vector
  32682. */
  32683. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32684. var temp = new Array();
  32685. vector.toArray(temp);
  32686. this.addUniform(name, temp);
  32687. };
  32688. /**
  32689. * Wrapper for addUniform.
  32690. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32691. */
  32692. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32693. this.addUniform(name, 12);
  32694. };
  32695. /**
  32696. * Wrapper for addUniform.
  32697. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32698. */
  32699. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32700. this.addUniform(name, 8);
  32701. };
  32702. /**
  32703. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32704. */
  32705. UniformBuffer.prototype.create = function () {
  32706. if (this._noUBO) {
  32707. return;
  32708. }
  32709. if (this._buffer) {
  32710. return; // nothing to do
  32711. }
  32712. // See spec, alignment must be filled as a vec4
  32713. this._fillAlignment(4);
  32714. this._bufferData = new Float32Array(this._data);
  32715. this._rebuild();
  32716. this._needSync = true;
  32717. };
  32718. UniformBuffer.prototype._rebuild = function () {
  32719. if (this._noUBO) {
  32720. return;
  32721. }
  32722. if (this._dynamic) {
  32723. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32724. }
  32725. else {
  32726. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32727. }
  32728. };
  32729. /**
  32730. * Updates the WebGL Uniform Buffer on the GPU.
  32731. * If the `dynamic` flag is set to true, no cache comparison is done.
  32732. * Otherwise, the buffer will be updated only if the cache differs.
  32733. */
  32734. UniformBuffer.prototype.update = function () {
  32735. if (!this._buffer) {
  32736. this.create();
  32737. return;
  32738. }
  32739. if (!this._dynamic && !this._needSync) {
  32740. return;
  32741. }
  32742. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32743. this._needSync = false;
  32744. };
  32745. /**
  32746. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32747. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32748. * @param {number[]|Float32Array} data Flattened data
  32749. * @param {number} size Size of the data.
  32750. */
  32751. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32752. var location = this._uniformLocations[uniformName];
  32753. if (location === undefined) {
  32754. if (this._buffer) {
  32755. // Cannot add an uniform if the buffer is already created
  32756. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32757. return;
  32758. }
  32759. this.addUniform(uniformName, size);
  32760. location = this._uniformLocations[uniformName];
  32761. }
  32762. if (!this._buffer) {
  32763. this.create();
  32764. }
  32765. if (!this._dynamic) {
  32766. // Cache for static uniform buffers
  32767. var changed = false;
  32768. for (var i = 0; i < size; i++) {
  32769. if (this._bufferData[location + i] !== data[i]) {
  32770. changed = true;
  32771. this._bufferData[location + i] = data[i];
  32772. }
  32773. }
  32774. this._needSync = this._needSync || changed;
  32775. }
  32776. else {
  32777. // No cache for dynamic
  32778. for (var i = 0; i < size; i++) {
  32779. this._bufferData[location + i] = data[i];
  32780. }
  32781. }
  32782. };
  32783. // Update methods
  32784. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32785. // To match std140, matrix must be realigned
  32786. for (var i = 0; i < 3; i++) {
  32787. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32788. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32789. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32790. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32791. }
  32792. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32793. };
  32794. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32795. this._currentEffect.setMatrix3x3(name, matrix);
  32796. };
  32797. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32798. this._currentEffect.setMatrix2x2(name, matrix);
  32799. };
  32800. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32801. // To match std140, matrix must be realigned
  32802. for (var i = 0; i < 2; i++) {
  32803. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32804. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32805. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32806. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32807. }
  32808. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32809. };
  32810. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32811. this._currentEffect.setFloat(name, x);
  32812. };
  32813. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32814. UniformBuffer._tempBuffer[0] = x;
  32815. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32816. };
  32817. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32818. if (suffix === void 0) { suffix = ""; }
  32819. this._currentEffect.setFloat2(name + suffix, x, y);
  32820. };
  32821. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32822. if (suffix === void 0) { suffix = ""; }
  32823. UniformBuffer._tempBuffer[0] = x;
  32824. UniformBuffer._tempBuffer[1] = y;
  32825. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32826. };
  32827. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32828. if (suffix === void 0) { suffix = ""; }
  32829. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32830. };
  32831. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32832. if (suffix === void 0) { suffix = ""; }
  32833. UniformBuffer._tempBuffer[0] = x;
  32834. UniformBuffer._tempBuffer[1] = y;
  32835. UniformBuffer._tempBuffer[2] = z;
  32836. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32837. };
  32838. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32839. if (suffix === void 0) { suffix = ""; }
  32840. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32841. };
  32842. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32843. if (suffix === void 0) { suffix = ""; }
  32844. UniformBuffer._tempBuffer[0] = x;
  32845. UniformBuffer._tempBuffer[1] = y;
  32846. UniformBuffer._tempBuffer[2] = z;
  32847. UniformBuffer._tempBuffer[3] = w;
  32848. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32849. };
  32850. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32851. this._currentEffect.setMatrix(name, mat);
  32852. };
  32853. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32854. this.updateUniform(name, mat.toArray(), 16);
  32855. };
  32856. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32857. this._currentEffect.setVector3(name, vector);
  32858. };
  32859. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32860. vector.toArray(UniformBuffer._tempBuffer);
  32861. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32862. };
  32863. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32864. this._currentEffect.setVector4(name, vector);
  32865. };
  32866. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32867. vector.toArray(UniformBuffer._tempBuffer);
  32868. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32869. };
  32870. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32871. if (suffix === void 0) { suffix = ""; }
  32872. this._currentEffect.setColor3(name + suffix, color);
  32873. };
  32874. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32875. if (suffix === void 0) { suffix = ""; }
  32876. color.toArray(UniformBuffer._tempBuffer);
  32877. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32878. };
  32879. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32880. if (suffix === void 0) { suffix = ""; }
  32881. this._currentEffect.setColor4(name + suffix, color, alpha);
  32882. };
  32883. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32884. if (suffix === void 0) { suffix = ""; }
  32885. color.toArray(UniformBuffer._tempBuffer);
  32886. UniformBuffer._tempBuffer[3] = alpha;
  32887. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32888. };
  32889. /**
  32890. * Sets a sampler uniform on the effect.
  32891. * @param {string} name Name of the sampler.
  32892. * @param {Texture} texture
  32893. */
  32894. UniformBuffer.prototype.setTexture = function (name, texture) {
  32895. this._currentEffect.setTexture(name, texture);
  32896. };
  32897. /**
  32898. * Directly updates the value of the uniform in the cache AND on the GPU.
  32899. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32900. * @param {number[]|Float32Array} data Flattened data
  32901. */
  32902. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32903. this.updateUniform(uniformName, data, data.length);
  32904. this.update();
  32905. };
  32906. /**
  32907. * Binds this uniform buffer to an effect.
  32908. * @param {Effect} effect
  32909. * @param {string} name Name of the uniform block in the shader.
  32910. */
  32911. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32912. this._currentEffect = effect;
  32913. if (this._noUBO || !this._buffer) {
  32914. return;
  32915. }
  32916. effect.bindUniformBuffer(this._buffer, name);
  32917. };
  32918. /**
  32919. * Disposes the uniform buffer.
  32920. */
  32921. UniformBuffer.prototype.dispose = function () {
  32922. if (this._noUBO) {
  32923. return;
  32924. }
  32925. var index = this._engine._uniformBuffers.indexOf(this);
  32926. if (index !== -1) {
  32927. this._engine._uniformBuffers.splice(index, 1);
  32928. }
  32929. if (!this._buffer) {
  32930. return;
  32931. }
  32932. if (this._engine._releaseBuffer(this._buffer)) {
  32933. this._buffer = null;
  32934. }
  32935. };
  32936. // Pool for avoiding memory leaks
  32937. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32938. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32939. return UniformBuffer;
  32940. }());
  32941. BABYLON.UniformBuffer = UniformBuffer;
  32942. })(BABYLON || (BABYLON = {}));
  32943. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32944. "use strict";
  32945. var BABYLON;
  32946. (function (BABYLON) {
  32947. var VertexData = /** @class */ (function () {
  32948. function VertexData() {
  32949. }
  32950. VertexData.prototype.set = function (data, kind) {
  32951. switch (kind) {
  32952. case BABYLON.VertexBuffer.PositionKind:
  32953. this.positions = data;
  32954. break;
  32955. case BABYLON.VertexBuffer.NormalKind:
  32956. this.normals = data;
  32957. break;
  32958. case BABYLON.VertexBuffer.TangentKind:
  32959. this.tangents = data;
  32960. break;
  32961. case BABYLON.VertexBuffer.UVKind:
  32962. this.uvs = data;
  32963. break;
  32964. case BABYLON.VertexBuffer.UV2Kind:
  32965. this.uvs2 = data;
  32966. break;
  32967. case BABYLON.VertexBuffer.UV3Kind:
  32968. this.uvs3 = data;
  32969. break;
  32970. case BABYLON.VertexBuffer.UV4Kind:
  32971. this.uvs4 = data;
  32972. break;
  32973. case BABYLON.VertexBuffer.UV5Kind:
  32974. this.uvs5 = data;
  32975. break;
  32976. case BABYLON.VertexBuffer.UV6Kind:
  32977. this.uvs6 = data;
  32978. break;
  32979. case BABYLON.VertexBuffer.ColorKind:
  32980. this.colors = data;
  32981. break;
  32982. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32983. this.matricesIndices = data;
  32984. break;
  32985. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32986. this.matricesWeights = data;
  32987. break;
  32988. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32989. this.matricesIndicesExtra = data;
  32990. break;
  32991. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32992. this.matricesWeightsExtra = data;
  32993. break;
  32994. }
  32995. };
  32996. /**
  32997. * Associates the vertexData to the passed Mesh.
  32998. * Sets it as updatable or not (default `false`).
  32999. * Returns the VertexData.
  33000. */
  33001. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33002. this._applyTo(mesh, updatable);
  33003. return this;
  33004. };
  33005. /**
  33006. * Associates the vertexData to the passed Geometry.
  33007. * Sets it as updatable or not (default `false`).
  33008. * Returns the VertexData.
  33009. */
  33010. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33011. this._applyTo(geometry, updatable);
  33012. return this;
  33013. };
  33014. /**
  33015. * Updates the associated mesh.
  33016. * Returns the VertexData.
  33017. */
  33018. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33019. this._update(mesh);
  33020. return this;
  33021. };
  33022. /**
  33023. * Updates the associated geometry.
  33024. * Returns the VertexData.
  33025. */
  33026. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33027. this._update(geometry);
  33028. return this;
  33029. };
  33030. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33031. if (updatable === void 0) { updatable = false; }
  33032. if (this.positions) {
  33033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33034. }
  33035. if (this.normals) {
  33036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33037. }
  33038. if (this.tangents) {
  33039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  33040. }
  33041. if (this.uvs) {
  33042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33043. }
  33044. if (this.uvs2) {
  33045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33046. }
  33047. if (this.uvs3) {
  33048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33049. }
  33050. if (this.uvs4) {
  33051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33052. }
  33053. if (this.uvs5) {
  33054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33055. }
  33056. if (this.uvs6) {
  33057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33058. }
  33059. if (this.colors) {
  33060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33061. }
  33062. if (this.matricesIndices) {
  33063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33064. }
  33065. if (this.matricesWeights) {
  33066. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33067. }
  33068. if (this.matricesIndicesExtra) {
  33069. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33070. }
  33071. if (this.matricesWeightsExtra) {
  33072. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33073. }
  33074. if (this.indices) {
  33075. meshOrGeometry.setIndices(this.indices, null, updatable);
  33076. }
  33077. return this;
  33078. };
  33079. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33080. if (this.positions) {
  33081. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33082. }
  33083. if (this.normals) {
  33084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33085. }
  33086. if (this.tangents) {
  33087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33088. }
  33089. if (this.uvs) {
  33090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33091. }
  33092. if (this.uvs2) {
  33093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33094. }
  33095. if (this.uvs3) {
  33096. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33097. }
  33098. if (this.uvs4) {
  33099. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33100. }
  33101. if (this.uvs5) {
  33102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33103. }
  33104. if (this.uvs6) {
  33105. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33106. }
  33107. if (this.colors) {
  33108. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33109. }
  33110. if (this.matricesIndices) {
  33111. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33112. }
  33113. if (this.matricesWeights) {
  33114. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33115. }
  33116. if (this.matricesIndicesExtra) {
  33117. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33118. }
  33119. if (this.matricesWeightsExtra) {
  33120. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33121. }
  33122. if (this.indices) {
  33123. meshOrGeometry.setIndices(this.indices, null);
  33124. }
  33125. return this;
  33126. };
  33127. /**
  33128. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33129. * Returns the VertexData.
  33130. */
  33131. VertexData.prototype.transform = function (matrix) {
  33132. var transformed = BABYLON.Vector3.Zero();
  33133. var index;
  33134. if (this.positions) {
  33135. var position = BABYLON.Vector3.Zero();
  33136. for (index = 0; index < this.positions.length; index += 3) {
  33137. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33138. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33139. this.positions[index] = transformed.x;
  33140. this.positions[index + 1] = transformed.y;
  33141. this.positions[index + 2] = transformed.z;
  33142. }
  33143. }
  33144. if (this.normals) {
  33145. var normal = BABYLON.Vector3.Zero();
  33146. for (index = 0; index < this.normals.length; index += 3) {
  33147. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33148. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33149. this.normals[index] = transformed.x;
  33150. this.normals[index + 1] = transformed.y;
  33151. this.normals[index + 2] = transformed.z;
  33152. }
  33153. }
  33154. if (this.tangents) {
  33155. var tangent = BABYLON.Vector4.Zero();
  33156. var tangentTransformed = BABYLON.Vector4.Zero();
  33157. for (index = 0; index < this.tangents.length; index += 4) {
  33158. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33159. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33160. this.tangents[index] = tangentTransformed.x;
  33161. this.tangents[index + 1] = tangentTransformed.y;
  33162. this.tangents[index + 2] = tangentTransformed.z;
  33163. this.tangents[index + 3] = tangentTransformed.w;
  33164. }
  33165. }
  33166. return this;
  33167. };
  33168. /**
  33169. * Merges the passed VertexData into the current one.
  33170. * Returns the modified VertexData.
  33171. */
  33172. VertexData.prototype.merge = function (other) {
  33173. this._validate();
  33174. other._validate();
  33175. if (!this.normals !== !other.normals ||
  33176. !this.tangents !== !other.tangents ||
  33177. !this.uvs !== !other.uvs ||
  33178. !this.uvs2 !== !other.uvs2 ||
  33179. !this.uvs3 !== !other.uvs3 ||
  33180. !this.uvs4 !== !other.uvs4 ||
  33181. !this.uvs5 !== !other.uvs5 ||
  33182. !this.uvs6 !== !other.uvs6 ||
  33183. !this.colors !== !other.colors ||
  33184. !this.matricesIndices !== !other.matricesIndices ||
  33185. !this.matricesWeights !== !other.matricesWeights ||
  33186. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33187. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33188. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33189. }
  33190. if (other.indices) {
  33191. if (!this.indices) {
  33192. this.indices = [];
  33193. }
  33194. var offset = this.positions ? this.positions.length / 3 : 0;
  33195. for (var index = 0; index < other.indices.length; index++) {
  33196. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33197. this.indices.push(other.indices[index] + offset);
  33198. }
  33199. }
  33200. this.positions = this._mergeElement(this.positions, other.positions);
  33201. this.normals = this._mergeElement(this.normals, other.normals);
  33202. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33203. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33204. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33205. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33206. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33207. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33208. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33209. this.colors = this._mergeElement(this.colors, other.colors);
  33210. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33211. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33212. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33213. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33214. return this;
  33215. };
  33216. VertexData.prototype._mergeElement = function (source, other) {
  33217. if (!source) {
  33218. return other;
  33219. }
  33220. if (!other) {
  33221. return source;
  33222. }
  33223. var len = other.length + source.length;
  33224. var isSrcTypedArray = source instanceof Float32Array;
  33225. var isOthTypedArray = other instanceof Float32Array;
  33226. // use non-loop method when the source is Float32Array
  33227. if (isSrcTypedArray) {
  33228. var ret32 = new Float32Array(len);
  33229. ret32.set(source);
  33230. ret32.set(other, source.length);
  33231. return ret32;
  33232. // source is number[], when other is also use concat
  33233. }
  33234. else if (!isOthTypedArray) {
  33235. return source.concat(other);
  33236. // source is a number[], but other is a Float32Array, loop required
  33237. }
  33238. else {
  33239. var ret = source.slice(0); // copy source to a separate array
  33240. for (var i = 0, len = other.length; i < len; i++) {
  33241. ret.push(other[i]);
  33242. }
  33243. return ret;
  33244. }
  33245. };
  33246. VertexData.prototype._validate = function () {
  33247. if (!this.positions) {
  33248. throw new Error("Positions are required");
  33249. }
  33250. var getElementCount = function (kind, values) {
  33251. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33252. if ((values.length % stride) !== 0) {
  33253. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33254. }
  33255. return values.length / stride;
  33256. };
  33257. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33258. var validateElementCount = function (kind, values) {
  33259. var elementCount = getElementCount(kind, values);
  33260. if (elementCount !== positionsElementCount) {
  33261. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33262. }
  33263. };
  33264. if (this.normals)
  33265. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33266. if (this.tangents)
  33267. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33268. if (this.uvs)
  33269. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33270. if (this.uvs2)
  33271. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33272. if (this.uvs3)
  33273. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33274. if (this.uvs4)
  33275. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33276. if (this.uvs5)
  33277. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33278. if (this.uvs6)
  33279. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33280. if (this.colors)
  33281. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33282. if (this.matricesIndices)
  33283. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33284. if (this.matricesWeights)
  33285. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33286. if (this.matricesIndicesExtra)
  33287. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33288. if (this.matricesWeightsExtra)
  33289. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33290. };
  33291. /**
  33292. * Serializes the VertexData.
  33293. * Returns a serialized object.
  33294. */
  33295. VertexData.prototype.serialize = function () {
  33296. var serializationObject = this.serialize();
  33297. if (this.positions) {
  33298. serializationObject.positions = this.positions;
  33299. }
  33300. if (this.normals) {
  33301. serializationObject.normals = this.normals;
  33302. }
  33303. if (this.tangents) {
  33304. serializationObject.tangents = this.tangents;
  33305. }
  33306. if (this.uvs) {
  33307. serializationObject.uvs = this.uvs;
  33308. }
  33309. if (this.uvs2) {
  33310. serializationObject.uvs2 = this.uvs2;
  33311. }
  33312. if (this.uvs3) {
  33313. serializationObject.uvs3 = this.uvs3;
  33314. }
  33315. if (this.uvs4) {
  33316. serializationObject.uvs4 = this.uvs4;
  33317. }
  33318. if (this.uvs5) {
  33319. serializationObject.uvs5 = this.uvs5;
  33320. }
  33321. if (this.uvs6) {
  33322. serializationObject.uvs6 = this.uvs6;
  33323. }
  33324. if (this.colors) {
  33325. serializationObject.colors = this.colors;
  33326. }
  33327. if (this.matricesIndices) {
  33328. serializationObject.matricesIndices = this.matricesIndices;
  33329. serializationObject.matricesIndices._isExpanded = true;
  33330. }
  33331. if (this.matricesWeights) {
  33332. serializationObject.matricesWeights = this.matricesWeights;
  33333. }
  33334. if (this.matricesIndicesExtra) {
  33335. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33336. serializationObject.matricesIndicesExtra._isExpanded = true;
  33337. }
  33338. if (this.matricesWeightsExtra) {
  33339. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33340. }
  33341. serializationObject.indices = this.indices;
  33342. return serializationObject;
  33343. };
  33344. // Statics
  33345. /**
  33346. * Returns the object VertexData associated to the passed mesh.
  33347. */
  33348. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33349. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33350. };
  33351. /**
  33352. * Returns the object VertexData associated to the passed geometry.
  33353. */
  33354. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33355. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33356. };
  33357. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33358. var result = new VertexData();
  33359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33360. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33361. }
  33362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33363. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33364. }
  33365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33366. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33367. }
  33368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33369. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33370. }
  33371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33372. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33373. }
  33374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33375. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33376. }
  33377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33378. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33379. }
  33380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33381. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33382. }
  33383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33384. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33385. }
  33386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33387. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33388. }
  33389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33390. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33391. }
  33392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33393. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33394. }
  33395. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33396. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33397. }
  33398. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33399. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33400. }
  33401. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33402. return result;
  33403. };
  33404. /**
  33405. * Creates the vertexData of the Ribbon.
  33406. */
  33407. VertexData.CreateRibbon = function (options) {
  33408. var pathArray = options.pathArray;
  33409. var closeArray = options.closeArray || false;
  33410. var closePath = options.closePath || false;
  33411. var invertUV = options.invertUV || false;
  33412. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33413. var offset = options.offset || defaultOffset;
  33414. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33415. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33416. var customUV = options.uvs;
  33417. var customColors = options.colors;
  33418. var positions = [];
  33419. var indices = [];
  33420. var normals = [];
  33421. var uvs = [];
  33422. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33423. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33424. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33425. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33426. var minlg; // minimal length among all paths from pathArray
  33427. var lg = []; // array of path lengths : nb of vertex per path
  33428. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33429. var p; // path iterator
  33430. var i; // point iterator
  33431. var j; // point iterator
  33432. // if single path in pathArray
  33433. if (pathArray.length < 2) {
  33434. var ar1 = [];
  33435. var ar2 = [];
  33436. for (i = 0; i < pathArray[0].length - offset; i++) {
  33437. ar1.push(pathArray[0][i]);
  33438. ar2.push(pathArray[0][i + offset]);
  33439. }
  33440. pathArray = [ar1, ar2];
  33441. }
  33442. // positions and horizontal distances (u)
  33443. var idc = 0;
  33444. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33445. var path;
  33446. var l;
  33447. minlg = pathArray[0].length;
  33448. var vectlg;
  33449. var dist;
  33450. for (p = 0; p < pathArray.length; p++) {
  33451. uTotalDistance[p] = 0;
  33452. us[p] = [0];
  33453. path = pathArray[p];
  33454. l = path.length;
  33455. minlg = (minlg < l) ? minlg : l;
  33456. j = 0;
  33457. while (j < l) {
  33458. positions.push(path[j].x, path[j].y, path[j].z);
  33459. if (j > 0) {
  33460. vectlg = path[j].subtract(path[j - 1]).length();
  33461. dist = vectlg + uTotalDistance[p];
  33462. us[p].push(dist);
  33463. uTotalDistance[p] = dist;
  33464. }
  33465. j++;
  33466. }
  33467. if (closePath) {
  33468. j--;
  33469. positions.push(path[0].x, path[0].y, path[0].z);
  33470. vectlg = path[j].subtract(path[0]).length();
  33471. dist = vectlg + uTotalDistance[p];
  33472. us[p].push(dist);
  33473. uTotalDistance[p] = dist;
  33474. }
  33475. lg[p] = l + closePathCorr;
  33476. idx[p] = idc;
  33477. idc += (l + closePathCorr);
  33478. }
  33479. // vertical distances (v)
  33480. var path1;
  33481. var path2;
  33482. var vertex1 = null;
  33483. var vertex2 = null;
  33484. for (i = 0; i < minlg + closePathCorr; i++) {
  33485. vTotalDistance[i] = 0;
  33486. vs[i] = [0];
  33487. for (p = 0; p < pathArray.length - 1; p++) {
  33488. path1 = pathArray[p];
  33489. path2 = pathArray[p + 1];
  33490. if (i === minlg) {
  33491. vertex1 = path1[0];
  33492. vertex2 = path2[0];
  33493. }
  33494. else {
  33495. vertex1 = path1[i];
  33496. vertex2 = path2[i];
  33497. }
  33498. vectlg = vertex2.subtract(vertex1).length();
  33499. dist = vectlg + vTotalDistance[i];
  33500. vs[i].push(dist);
  33501. vTotalDistance[i] = dist;
  33502. }
  33503. if (closeArray && vertex2 && vertex1) {
  33504. path1 = pathArray[p];
  33505. path2 = pathArray[0];
  33506. if (i === minlg) {
  33507. vertex2 = path2[0];
  33508. }
  33509. vectlg = vertex2.subtract(vertex1).length();
  33510. dist = vectlg + vTotalDistance[i];
  33511. vTotalDistance[i] = dist;
  33512. }
  33513. }
  33514. // uvs
  33515. var u;
  33516. var v;
  33517. if (customUV) {
  33518. for (p = 0; p < customUV.length; p++) {
  33519. uvs.push(customUV[p].x, customUV[p].y);
  33520. }
  33521. }
  33522. else {
  33523. for (p = 0; p < pathArray.length; p++) {
  33524. for (i = 0; i < minlg + closePathCorr; i++) {
  33525. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33526. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33527. if (invertUV) {
  33528. uvs.push(v, u);
  33529. }
  33530. else {
  33531. uvs.push(u, v);
  33532. }
  33533. }
  33534. }
  33535. }
  33536. // indices
  33537. p = 0; // path index
  33538. var pi = 0; // positions array index
  33539. var l1 = lg[p] - 1; // path1 length
  33540. var l2 = lg[p + 1] - 1; // path2 length
  33541. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33542. var shft = idx[1] - idx[0]; // shift
  33543. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33544. while (pi <= min && p < path1nb) {
  33545. // 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
  33546. indices.push(pi, pi + shft, pi + 1);
  33547. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33548. pi += 1;
  33549. if (pi === min) {
  33550. p++;
  33551. if (p === lg.length - 1) {
  33552. shft = idx[0] - idx[p];
  33553. l1 = lg[p] - 1;
  33554. l2 = lg[0] - 1;
  33555. }
  33556. else {
  33557. shft = idx[p + 1] - idx[p];
  33558. l1 = lg[p] - 1;
  33559. l2 = lg[p + 1] - 1;
  33560. }
  33561. pi = idx[p];
  33562. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33563. }
  33564. }
  33565. // normals
  33566. VertexData.ComputeNormals(positions, indices, normals);
  33567. if (closePath) {
  33568. var indexFirst = 0;
  33569. var indexLast = 0;
  33570. for (p = 0; p < pathArray.length; p++) {
  33571. indexFirst = idx[p] * 3;
  33572. if (p + 1 < pathArray.length) {
  33573. indexLast = (idx[p + 1] - 1) * 3;
  33574. }
  33575. else {
  33576. indexLast = normals.length - 3;
  33577. }
  33578. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33579. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33580. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33581. normals[indexLast] = normals[indexFirst];
  33582. normals[indexLast + 1] = normals[indexFirst + 1];
  33583. normals[indexLast + 2] = normals[indexFirst + 2];
  33584. }
  33585. }
  33586. // sides
  33587. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33588. // Colors
  33589. var colors = null;
  33590. if (customColors) {
  33591. colors = new Float32Array(customColors.length * 4);
  33592. for (var c = 0; c < customColors.length; c++) {
  33593. colors[c * 4] = customColors[c].r;
  33594. colors[c * 4 + 1] = customColors[c].g;
  33595. colors[c * 4 + 2] = customColors[c].b;
  33596. colors[c * 4 + 3] = customColors[c].a;
  33597. }
  33598. }
  33599. // Result
  33600. var vertexData = new VertexData();
  33601. var positions32 = new Float32Array(positions);
  33602. var normals32 = new Float32Array(normals);
  33603. var uvs32 = new Float32Array(uvs);
  33604. vertexData.indices = indices;
  33605. vertexData.positions = positions32;
  33606. vertexData.normals = normals32;
  33607. vertexData.uvs = uvs32;
  33608. if (colors) {
  33609. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33610. }
  33611. if (closePath) {
  33612. vertexData._idx = idx;
  33613. }
  33614. return vertexData;
  33615. };
  33616. /**
  33617. * Creates the VertexData of the Box.
  33618. */
  33619. VertexData.CreateBox = function (options) {
  33620. var normalsSource = [
  33621. new BABYLON.Vector3(0, 0, 1),
  33622. new BABYLON.Vector3(0, 0, -1),
  33623. new BABYLON.Vector3(1, 0, 0),
  33624. new BABYLON.Vector3(-1, 0, 0),
  33625. new BABYLON.Vector3(0, 1, 0),
  33626. new BABYLON.Vector3(0, -1, 0)
  33627. ];
  33628. var indices = [];
  33629. var positions = [];
  33630. var normals = [];
  33631. var uvs = [];
  33632. var width = options.width || options.size || 1;
  33633. var height = options.height || options.size || 1;
  33634. var depth = options.depth || options.size || 1;
  33635. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33636. var faceUV = options.faceUV || new Array(6);
  33637. var faceColors = options.faceColors;
  33638. var colors = [];
  33639. // default face colors and UV if undefined
  33640. for (var f = 0; f < 6; f++) {
  33641. if (faceUV[f] === undefined) {
  33642. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33643. }
  33644. if (faceColors && faceColors[f] === undefined) {
  33645. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33646. }
  33647. }
  33648. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33649. // Create each face in turn.
  33650. for (var index = 0; index < normalsSource.length; index++) {
  33651. var normal = normalsSource[index];
  33652. // Get two vectors perpendicular to the face normal and to each other.
  33653. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33654. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33655. // Six indices (two triangles) per face.
  33656. var verticesLength = positions.length / 3;
  33657. indices.push(verticesLength);
  33658. indices.push(verticesLength + 1);
  33659. indices.push(verticesLength + 2);
  33660. indices.push(verticesLength);
  33661. indices.push(verticesLength + 2);
  33662. indices.push(verticesLength + 3);
  33663. // Four vertices per face.
  33664. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33665. positions.push(vertex.x, vertex.y, vertex.z);
  33666. normals.push(normal.x, normal.y, normal.z);
  33667. uvs.push(faceUV[index].z, faceUV[index].w);
  33668. if (faceColors) {
  33669. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33670. }
  33671. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33672. positions.push(vertex.x, vertex.y, vertex.z);
  33673. normals.push(normal.x, normal.y, normal.z);
  33674. uvs.push(faceUV[index].x, faceUV[index].w);
  33675. if (faceColors) {
  33676. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33677. }
  33678. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33679. positions.push(vertex.x, vertex.y, vertex.z);
  33680. normals.push(normal.x, normal.y, normal.z);
  33681. uvs.push(faceUV[index].x, faceUV[index].y);
  33682. if (faceColors) {
  33683. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33684. }
  33685. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33686. positions.push(vertex.x, vertex.y, vertex.z);
  33687. normals.push(normal.x, normal.y, normal.z);
  33688. uvs.push(faceUV[index].z, faceUV[index].y);
  33689. if (faceColors) {
  33690. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33691. }
  33692. }
  33693. // sides
  33694. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33695. // Result
  33696. var vertexData = new VertexData();
  33697. vertexData.indices = indices;
  33698. vertexData.positions = positions;
  33699. vertexData.normals = normals;
  33700. vertexData.uvs = uvs;
  33701. if (faceColors) {
  33702. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33703. vertexData.colors = totalColors;
  33704. }
  33705. return vertexData;
  33706. };
  33707. /**
  33708. * Creates the VertexData of the Sphere.
  33709. */
  33710. VertexData.CreateSphere = function (options) {
  33711. var segments = options.segments || 32;
  33712. var diameterX = options.diameterX || options.diameter || 1;
  33713. var diameterY = options.diameterY || options.diameter || 1;
  33714. var diameterZ = options.diameterZ || options.diameter || 1;
  33715. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33716. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33717. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33718. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33719. var totalZRotationSteps = 2 + segments;
  33720. var totalYRotationSteps = 2 * totalZRotationSteps;
  33721. var indices = [];
  33722. var positions = [];
  33723. var normals = [];
  33724. var uvs = [];
  33725. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33726. var normalizedZ = zRotationStep / totalZRotationSteps;
  33727. var angleZ = normalizedZ * Math.PI * slice;
  33728. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33729. var normalizedY = yRotationStep / totalYRotationSteps;
  33730. var angleY = normalizedY * Math.PI * 2 * arc;
  33731. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33732. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33733. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33734. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33735. var vertex = complete.multiply(radius);
  33736. var normal = complete.divide(radius).normalize();
  33737. positions.push(vertex.x, vertex.y, vertex.z);
  33738. normals.push(normal.x, normal.y, normal.z);
  33739. uvs.push(normalizedY, normalizedZ);
  33740. }
  33741. if (zRotationStep > 0) {
  33742. var verticesCount = positions.length / 3;
  33743. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33744. indices.push((firstIndex));
  33745. indices.push((firstIndex + 1));
  33746. indices.push(firstIndex + totalYRotationSteps + 1);
  33747. indices.push((firstIndex + totalYRotationSteps + 1));
  33748. indices.push((firstIndex + 1));
  33749. indices.push((firstIndex + totalYRotationSteps + 2));
  33750. }
  33751. }
  33752. }
  33753. // Sides
  33754. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33755. // Result
  33756. var vertexData = new VertexData();
  33757. vertexData.indices = indices;
  33758. vertexData.positions = positions;
  33759. vertexData.normals = normals;
  33760. vertexData.uvs = uvs;
  33761. return vertexData;
  33762. };
  33763. /**
  33764. * Creates the VertexData of the Cylinder or Cone.
  33765. */
  33766. VertexData.CreateCylinder = function (options) {
  33767. var height = options.height || 2;
  33768. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33769. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33770. var tessellation = options.tessellation || 24;
  33771. var subdivisions = options.subdivisions || 1;
  33772. var hasRings = options.hasRings ? true : false;
  33773. var enclose = options.enclose ? true : false;
  33774. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33775. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33776. var faceUV = options.faceUV || new Array(3);
  33777. var faceColors = options.faceColors;
  33778. // default face colors and UV if undefined
  33779. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33780. var ringNb = (hasRings) ? subdivisions : 1;
  33781. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33782. var f;
  33783. for (f = 0; f < surfaceNb; f++) {
  33784. if (faceColors && faceColors[f] === undefined) {
  33785. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33786. }
  33787. }
  33788. for (f = 0; f < surfaceNb; f++) {
  33789. if (faceUV && faceUV[f] === undefined) {
  33790. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33791. }
  33792. }
  33793. var indices = new Array();
  33794. var positions = new Array();
  33795. var normals = new Array();
  33796. var uvs = new Array();
  33797. var colors = new Array();
  33798. var angle_step = Math.PI * 2 * arc / tessellation;
  33799. var angle;
  33800. var h;
  33801. var radius;
  33802. var tan = (diameterBottom - diameterTop) / 2 / height;
  33803. var ringVertex = BABYLON.Vector3.Zero();
  33804. var ringNormal = BABYLON.Vector3.Zero();
  33805. var ringFirstVertex = BABYLON.Vector3.Zero();
  33806. var ringFirstNormal = BABYLON.Vector3.Zero();
  33807. var quadNormal = BABYLON.Vector3.Zero();
  33808. var Y = BABYLON.Axis.Y;
  33809. // positions, normals, uvs
  33810. var i;
  33811. var j;
  33812. var r;
  33813. var ringIdx = 1;
  33814. var s = 1; // surface index
  33815. var cs = 0;
  33816. var v = 0;
  33817. for (i = 0; i <= subdivisions; i++) {
  33818. h = i / subdivisions;
  33819. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33820. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33821. for (r = 0; r < ringIdx; r++) {
  33822. if (hasRings) {
  33823. s += r;
  33824. }
  33825. if (enclose) {
  33826. s += 2 * r;
  33827. }
  33828. for (j = 0; j <= tessellation; j++) {
  33829. angle = j * angle_step;
  33830. // position
  33831. ringVertex.x = Math.cos(-angle) * radius;
  33832. ringVertex.y = -height / 2 + h * height;
  33833. ringVertex.z = Math.sin(-angle) * radius;
  33834. // normal
  33835. if (diameterTop === 0 && i === subdivisions) {
  33836. // if no top cap, reuse former normals
  33837. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33838. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33839. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33840. }
  33841. else {
  33842. ringNormal.x = ringVertex.x;
  33843. ringNormal.z = ringVertex.z;
  33844. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33845. ringNormal.normalize();
  33846. }
  33847. // keep first ring vertex values for enclose
  33848. if (j === 0) {
  33849. ringFirstVertex.copyFrom(ringVertex);
  33850. ringFirstNormal.copyFrom(ringNormal);
  33851. }
  33852. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33853. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33854. if (hasRings) {
  33855. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33856. }
  33857. else {
  33858. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33859. }
  33860. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33861. if (faceColors) {
  33862. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33863. }
  33864. }
  33865. // if enclose, add four vertices and their dedicated normals
  33866. if (arc !== 1 && enclose) {
  33867. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33868. positions.push(0, ringVertex.y, 0);
  33869. positions.push(0, ringVertex.y, 0);
  33870. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33871. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33872. quadNormal.normalize();
  33873. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33874. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33875. quadNormal.normalize();
  33876. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33877. if (hasRings) {
  33878. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33879. }
  33880. else {
  33881. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33882. }
  33883. uvs.push(faceUV[s + 1].x, v);
  33884. uvs.push(faceUV[s + 1].z, v);
  33885. if (hasRings) {
  33886. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33887. }
  33888. else {
  33889. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33890. }
  33891. uvs.push(faceUV[s + 2].x, v);
  33892. uvs.push(faceUV[s + 2].z, v);
  33893. if (faceColors) {
  33894. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33895. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33896. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33897. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33898. }
  33899. }
  33900. if (cs !== s) {
  33901. cs = s;
  33902. }
  33903. }
  33904. }
  33905. // indices
  33906. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33907. var s;
  33908. i = 0;
  33909. for (s = 0; s < subdivisions; s++) {
  33910. var i0 = 0;
  33911. var i1 = 0;
  33912. var i2 = 0;
  33913. var i3 = 0;
  33914. for (j = 0; j < tessellation; j++) {
  33915. i0 = i * (e + 1) + j;
  33916. i1 = (i + 1) * (e + 1) + j;
  33917. i2 = i * (e + 1) + (j + 1);
  33918. i3 = (i + 1) * (e + 1) + (j + 1);
  33919. indices.push(i0, i1, i2);
  33920. indices.push(i3, i2, i1);
  33921. }
  33922. if (arc !== 1 && enclose) {
  33923. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33924. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33925. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33926. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33927. }
  33928. i = (hasRings) ? (i + 2) : (i + 1);
  33929. }
  33930. // Caps
  33931. var createCylinderCap = function (isTop) {
  33932. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33933. if (radius === 0) {
  33934. return;
  33935. }
  33936. // Cap positions, normals & uvs
  33937. var angle;
  33938. var circleVector;
  33939. var i;
  33940. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33941. var c = null;
  33942. if (faceColors) {
  33943. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33944. }
  33945. // cap center
  33946. var vbase = positions.length / 3;
  33947. var offset = isTop ? height / 2 : -height / 2;
  33948. var center = new BABYLON.Vector3(0, offset, 0);
  33949. positions.push(center.x, center.y, center.z);
  33950. normals.push(0, isTop ? 1 : -1, 0);
  33951. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33952. if (c) {
  33953. colors.push(c.r, c.g, c.b, c.a);
  33954. }
  33955. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33956. for (i = 0; i <= tessellation; i++) {
  33957. angle = Math.PI * 2 * i * arc / tessellation;
  33958. var cos = Math.cos(-angle);
  33959. var sin = Math.sin(-angle);
  33960. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33961. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33962. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33963. normals.push(0, isTop ? 1 : -1, 0);
  33964. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33965. if (c) {
  33966. colors.push(c.r, c.g, c.b, c.a);
  33967. }
  33968. }
  33969. // Cap indices
  33970. for (i = 0; i < tessellation; i++) {
  33971. if (!isTop) {
  33972. indices.push(vbase);
  33973. indices.push(vbase + (i + 1));
  33974. indices.push(vbase + (i + 2));
  33975. }
  33976. else {
  33977. indices.push(vbase);
  33978. indices.push(vbase + (i + 2));
  33979. indices.push(vbase + (i + 1));
  33980. }
  33981. }
  33982. };
  33983. // add caps to geometry
  33984. createCylinderCap(false);
  33985. createCylinderCap(true);
  33986. // Sides
  33987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33988. var vertexData = new VertexData();
  33989. vertexData.indices = indices;
  33990. vertexData.positions = positions;
  33991. vertexData.normals = normals;
  33992. vertexData.uvs = uvs;
  33993. if (faceColors) {
  33994. vertexData.colors = colors;
  33995. }
  33996. return vertexData;
  33997. };
  33998. /**
  33999. * Creates the VertexData of the Torus.
  34000. */
  34001. VertexData.CreateTorus = function (options) {
  34002. var indices = [];
  34003. var positions = [];
  34004. var normals = [];
  34005. var uvs = [];
  34006. var diameter = options.diameter || 1;
  34007. var thickness = options.thickness || 0.5;
  34008. var tessellation = options.tessellation || 16;
  34009. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34010. var stride = tessellation + 1;
  34011. for (var i = 0; i <= tessellation; i++) {
  34012. var u = i / tessellation;
  34013. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34014. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34015. for (var j = 0; j <= tessellation; j++) {
  34016. var v = 1 - j / tessellation;
  34017. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34018. var dx = Math.cos(innerAngle);
  34019. var dy = Math.sin(innerAngle);
  34020. // Create a vertex.
  34021. var normal = new BABYLON.Vector3(dx, dy, 0);
  34022. var position = normal.scale(thickness / 2);
  34023. var textureCoordinate = new BABYLON.Vector2(u, v);
  34024. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34025. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34026. positions.push(position.x, position.y, position.z);
  34027. normals.push(normal.x, normal.y, normal.z);
  34028. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34029. // And create indices for two triangles.
  34030. var nextI = (i + 1) % stride;
  34031. var nextJ = (j + 1) % stride;
  34032. indices.push(i * stride + j);
  34033. indices.push(i * stride + nextJ);
  34034. indices.push(nextI * stride + j);
  34035. indices.push(i * stride + nextJ);
  34036. indices.push(nextI * stride + nextJ);
  34037. indices.push(nextI * stride + j);
  34038. }
  34039. }
  34040. // Sides
  34041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34042. // Result
  34043. var vertexData = new VertexData();
  34044. vertexData.indices = indices;
  34045. vertexData.positions = positions;
  34046. vertexData.normals = normals;
  34047. vertexData.uvs = uvs;
  34048. return vertexData;
  34049. };
  34050. /**
  34051. * Creates the VertexData of the LineSystem.
  34052. */
  34053. VertexData.CreateLineSystem = function (options) {
  34054. var indices = [];
  34055. var positions = [];
  34056. var lines = options.lines;
  34057. var colors = options.colors;
  34058. var vertexColors = [];
  34059. var idx = 0;
  34060. for (var l = 0; l < lines.length; l++) {
  34061. var points = lines[l];
  34062. for (var index = 0; index < points.length; index++) {
  34063. positions.push(points[index].x, points[index].y, points[index].z);
  34064. if (colors) {
  34065. var color = colors[l];
  34066. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34067. }
  34068. if (index > 0) {
  34069. indices.push(idx - 1);
  34070. indices.push(idx);
  34071. }
  34072. idx++;
  34073. }
  34074. }
  34075. var vertexData = new VertexData();
  34076. vertexData.indices = indices;
  34077. vertexData.positions = positions;
  34078. if (colors) {
  34079. vertexData.colors = vertexColors;
  34080. }
  34081. return vertexData;
  34082. };
  34083. /**
  34084. * Create the VertexData of the DashedLines.
  34085. */
  34086. VertexData.CreateDashedLines = function (options) {
  34087. var dashSize = options.dashSize || 3;
  34088. var gapSize = options.gapSize || 1;
  34089. var dashNb = options.dashNb || 200;
  34090. var points = options.points;
  34091. var positions = new Array();
  34092. var indices = new Array();
  34093. var curvect = BABYLON.Vector3.Zero();
  34094. var lg = 0;
  34095. var nb = 0;
  34096. var shft = 0;
  34097. var dashshft = 0;
  34098. var curshft = 0;
  34099. var idx = 0;
  34100. var i = 0;
  34101. for (i = 0; i < points.length - 1; i++) {
  34102. points[i + 1].subtractToRef(points[i], curvect);
  34103. lg += curvect.length();
  34104. }
  34105. shft = lg / dashNb;
  34106. dashshft = dashSize * shft / (dashSize + gapSize);
  34107. for (i = 0; i < points.length - 1; i++) {
  34108. points[i + 1].subtractToRef(points[i], curvect);
  34109. nb = Math.floor(curvect.length() / shft);
  34110. curvect.normalize();
  34111. for (var j = 0; j < nb; j++) {
  34112. curshft = shft * j;
  34113. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34114. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34115. indices.push(idx, idx + 1);
  34116. idx += 2;
  34117. }
  34118. }
  34119. // Result
  34120. var vertexData = new VertexData();
  34121. vertexData.positions = positions;
  34122. vertexData.indices = indices;
  34123. return vertexData;
  34124. };
  34125. /**
  34126. * Creates the VertexData of the Ground.
  34127. */
  34128. VertexData.CreateGround = function (options) {
  34129. var indices = [];
  34130. var positions = [];
  34131. var normals = [];
  34132. var uvs = [];
  34133. var row, col;
  34134. var width = options.width || 1;
  34135. var height = options.height || 1;
  34136. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34137. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34138. for (row = 0; row <= subdivisionsY; row++) {
  34139. for (col = 0; col <= subdivisionsX; col++) {
  34140. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34141. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34142. positions.push(position.x, position.y, position.z);
  34143. normals.push(normal.x, normal.y, normal.z);
  34144. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34145. }
  34146. }
  34147. for (row = 0; row < subdivisionsY; row++) {
  34148. for (col = 0; col < subdivisionsX; col++) {
  34149. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34150. indices.push(col + 1 + row * (subdivisionsX + 1));
  34151. indices.push(col + row * (subdivisionsX + 1));
  34152. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34153. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34154. indices.push(col + row * (subdivisionsX + 1));
  34155. }
  34156. }
  34157. // Result
  34158. var vertexData = new VertexData();
  34159. vertexData.indices = indices;
  34160. vertexData.positions = positions;
  34161. vertexData.normals = normals;
  34162. vertexData.uvs = uvs;
  34163. return vertexData;
  34164. };
  34165. /**
  34166. * Creates the VertexData of the TiledGround.
  34167. */
  34168. VertexData.CreateTiledGround = function (options) {
  34169. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34170. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34171. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34172. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34173. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34174. var precision = options.precision || { w: 1, h: 1 };
  34175. var indices = new Array();
  34176. var positions = new Array();
  34177. var normals = new Array();
  34178. var uvs = new Array();
  34179. var row, col, tileRow, tileCol;
  34180. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34181. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34182. precision.w = (precision.w < 1) ? 1 : precision.w;
  34183. precision.h = (precision.h < 1) ? 1 : precision.h;
  34184. var tileSize = {
  34185. 'w': (xmax - xmin) / subdivisions.w,
  34186. 'h': (zmax - zmin) / subdivisions.h
  34187. };
  34188. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34189. // Indices
  34190. var base = positions.length / 3;
  34191. var rowLength = precision.w + 1;
  34192. for (row = 0; row < precision.h; row++) {
  34193. for (col = 0; col < precision.w; col++) {
  34194. var square = [
  34195. base + col + row * rowLength,
  34196. base + (col + 1) + row * rowLength,
  34197. base + (col + 1) + (row + 1) * rowLength,
  34198. base + col + (row + 1) * rowLength
  34199. ];
  34200. indices.push(square[1]);
  34201. indices.push(square[2]);
  34202. indices.push(square[3]);
  34203. indices.push(square[0]);
  34204. indices.push(square[1]);
  34205. indices.push(square[3]);
  34206. }
  34207. }
  34208. // Position, normals and uvs
  34209. var position = BABYLON.Vector3.Zero();
  34210. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34211. for (row = 0; row <= precision.h; row++) {
  34212. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34213. for (col = 0; col <= precision.w; col++) {
  34214. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34215. position.y = 0;
  34216. positions.push(position.x, position.y, position.z);
  34217. normals.push(normal.x, normal.y, normal.z);
  34218. uvs.push(col / precision.w, row / precision.h);
  34219. }
  34220. }
  34221. }
  34222. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34223. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34224. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34225. }
  34226. }
  34227. // Result
  34228. var vertexData = new VertexData();
  34229. vertexData.indices = indices;
  34230. vertexData.positions = positions;
  34231. vertexData.normals = normals;
  34232. vertexData.uvs = uvs;
  34233. return vertexData;
  34234. };
  34235. /**
  34236. * Creates the VertexData of the Ground designed from a heightmap.
  34237. */
  34238. VertexData.CreateGroundFromHeightMap = function (options) {
  34239. var indices = [];
  34240. var positions = [];
  34241. var normals = [];
  34242. var uvs = [];
  34243. var row, col;
  34244. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34245. // Vertices
  34246. for (row = 0; row <= options.subdivisions; row++) {
  34247. for (col = 0; col <= options.subdivisions; col++) {
  34248. 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));
  34249. // Compute height
  34250. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34251. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34252. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34253. var r = options.buffer[pos] / 255.0;
  34254. var g = options.buffer[pos + 1] / 255.0;
  34255. var b = options.buffer[pos + 2] / 255.0;
  34256. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34257. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34258. // Add vertex
  34259. positions.push(position.x, position.y, position.z);
  34260. normals.push(0, 0, 0);
  34261. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34262. }
  34263. }
  34264. // Indices
  34265. for (row = 0; row < options.subdivisions; row++) {
  34266. for (col = 0; col < options.subdivisions; col++) {
  34267. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34268. indices.push(col + 1 + row * (options.subdivisions + 1));
  34269. indices.push(col + row * (options.subdivisions + 1));
  34270. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34271. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34272. indices.push(col + row * (options.subdivisions + 1));
  34273. }
  34274. }
  34275. // Normals
  34276. VertexData.ComputeNormals(positions, indices, normals);
  34277. // Result
  34278. var vertexData = new VertexData();
  34279. vertexData.indices = indices;
  34280. vertexData.positions = positions;
  34281. vertexData.normals = normals;
  34282. vertexData.uvs = uvs;
  34283. return vertexData;
  34284. };
  34285. /**
  34286. * Creates the VertexData of the Plane.
  34287. */
  34288. VertexData.CreatePlane = function (options) {
  34289. var indices = [];
  34290. var positions = [];
  34291. var normals = [];
  34292. var uvs = [];
  34293. var width = options.width || options.size || 1;
  34294. var height = options.height || options.size || 1;
  34295. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34296. // Vertices
  34297. var halfWidth = width / 2.0;
  34298. var halfHeight = height / 2.0;
  34299. positions.push(-halfWidth, -halfHeight, 0);
  34300. normals.push(0, 0, -1.0);
  34301. uvs.push(0.0, 0.0);
  34302. positions.push(halfWidth, -halfHeight, 0);
  34303. normals.push(0, 0, -1.0);
  34304. uvs.push(1.0, 0.0);
  34305. positions.push(halfWidth, halfHeight, 0);
  34306. normals.push(0, 0, -1.0);
  34307. uvs.push(1.0, 1.0);
  34308. positions.push(-halfWidth, halfHeight, 0);
  34309. normals.push(0, 0, -1.0);
  34310. uvs.push(0.0, 1.0);
  34311. // Indices
  34312. indices.push(0);
  34313. indices.push(1);
  34314. indices.push(2);
  34315. indices.push(0);
  34316. indices.push(2);
  34317. indices.push(3);
  34318. // Sides
  34319. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34320. // Result
  34321. var vertexData = new VertexData();
  34322. vertexData.indices = indices;
  34323. vertexData.positions = positions;
  34324. vertexData.normals = normals;
  34325. vertexData.uvs = uvs;
  34326. return vertexData;
  34327. };
  34328. /**
  34329. * Creates the VertexData of the Disc or regular Polygon.
  34330. */
  34331. VertexData.CreateDisc = function (options) {
  34332. var positions = new Array();
  34333. var indices = new Array();
  34334. var normals = new Array();
  34335. var uvs = new Array();
  34336. var radius = options.radius || 0.5;
  34337. var tessellation = options.tessellation || 64;
  34338. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34339. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34340. // positions and uvs
  34341. positions.push(0, 0, 0); // disc center first
  34342. uvs.push(0.5, 0.5);
  34343. var theta = Math.PI * 2 * arc;
  34344. var step = theta / tessellation;
  34345. for (var a = 0; a < theta; a += step) {
  34346. var x = Math.cos(a);
  34347. var y = Math.sin(a);
  34348. var u = (x + 1) / 2;
  34349. var v = (1 - y) / 2;
  34350. positions.push(radius * x, radius * y, 0);
  34351. uvs.push(u, v);
  34352. }
  34353. if (arc === 1) {
  34354. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34355. uvs.push(uvs[2], uvs[3]);
  34356. }
  34357. //indices
  34358. var vertexNb = positions.length / 3;
  34359. for (var i = 1; i < vertexNb - 1; i++) {
  34360. indices.push(i + 1, 0, i);
  34361. }
  34362. // result
  34363. VertexData.ComputeNormals(positions, indices, normals);
  34364. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34365. var vertexData = new VertexData();
  34366. vertexData.indices = indices;
  34367. vertexData.positions = positions;
  34368. vertexData.normals = normals;
  34369. vertexData.uvs = uvs;
  34370. return vertexData;
  34371. };
  34372. /**
  34373. * Re-creates the VertexData of the Polygon for sideOrientation.
  34374. */
  34375. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34376. var faceUV = fUV || new Array(3);
  34377. var faceColors = fColors;
  34378. var colors = [];
  34379. // default face colors and UV if undefined
  34380. for (var f = 0; f < 3; f++) {
  34381. if (faceUV[f] === undefined) {
  34382. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34383. }
  34384. if (faceColors && faceColors[f] === undefined) {
  34385. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34386. }
  34387. }
  34388. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34389. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34390. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34391. var indices = polygon.getIndices();
  34392. // set face colours and textures
  34393. var idx = 0;
  34394. var face = 0;
  34395. for (var index = 0; index < normals.length; index += 3) {
  34396. //Edge Face no. 1
  34397. if (Math.abs(normals[index + 1]) < 0.001) {
  34398. face = 1;
  34399. }
  34400. //Top Face no. 0
  34401. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34402. face = 0;
  34403. }
  34404. //Bottom Face no. 2
  34405. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34406. face = 2;
  34407. }
  34408. idx = index / 3;
  34409. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34410. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34411. if (faceColors) {
  34412. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34413. }
  34414. }
  34415. // sides
  34416. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34417. // Result
  34418. var vertexData = new VertexData();
  34419. vertexData.indices = indices;
  34420. vertexData.positions = positions;
  34421. vertexData.normals = normals;
  34422. vertexData.uvs = uvs;
  34423. if (faceColors) {
  34424. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34425. vertexData.colors = totalColors;
  34426. }
  34427. return vertexData;
  34428. };
  34429. /**
  34430. * Creates the VertexData of the IcoSphere.
  34431. */
  34432. VertexData.CreateIcoSphere = function (options) {
  34433. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34434. var radius = options.radius || 1;
  34435. var flat = (options.flat === undefined) ? true : options.flat;
  34436. var subdivisions = options.subdivisions || 4;
  34437. var radiusX = options.radiusX || radius;
  34438. var radiusY = options.radiusY || radius;
  34439. var radiusZ = options.radiusZ || radius;
  34440. var t = (1 + Math.sqrt(5)) / 2;
  34441. // 12 vertex x,y,z
  34442. var ico_vertices = [
  34443. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34444. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34445. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34446. ];
  34447. // index of 3 vertex makes a face of icopshere
  34448. var ico_indices = [
  34449. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34450. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34451. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34452. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34453. ];
  34454. // vertex for uv have aliased position, not for UV
  34455. var vertices_unalias_id = [
  34456. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34457. // vertex alias
  34458. 0,
  34459. 2,
  34460. 3,
  34461. 3,
  34462. 3,
  34463. 4,
  34464. 7,
  34465. 8,
  34466. 9,
  34467. 9,
  34468. 10,
  34469. 11 // 23: B + 12
  34470. ];
  34471. // uv as integer step (not pixels !)
  34472. var ico_vertexuv = [
  34473. 5, 1, 3, 1, 6, 4, 0, 0,
  34474. 5, 3, 4, 2, 2, 2, 4, 0,
  34475. 2, 0, 1, 1, 6, 0, 6, 2,
  34476. // vertex alias (for same vertex on different faces)
  34477. 0, 4,
  34478. 3, 3,
  34479. 4, 4,
  34480. 3, 1,
  34481. 4, 2,
  34482. 4, 4,
  34483. 0, 2,
  34484. 1, 1,
  34485. 2, 2,
  34486. 3, 3,
  34487. 1, 3,
  34488. 2, 4 // 23: B + 12
  34489. ];
  34490. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34491. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34492. // First island of uv mapping
  34493. // v = 4h 3+ 2
  34494. // v = 3h 9+ 4
  34495. // v = 2h 9+ 5 B
  34496. // v = 1h 9 1 0
  34497. // v = 0h 3 8 7 A
  34498. // u = 0 1 2 3 4 5 6 *a
  34499. // Second island of uv mapping
  34500. // v = 4h 0+ B+ 4+
  34501. // v = 3h A+ 2+
  34502. // v = 2h 7+ 6 3+
  34503. // v = 1h 8+ 3+
  34504. // v = 0h
  34505. // u = 0 1 2 3 4 5 6 *a
  34506. // Face layout on texture UV mapping
  34507. // ============
  34508. // \ 4 /\ 16 / ======
  34509. // \ / \ / /\ 11 /
  34510. // \/ 7 \/ / \ /
  34511. // ======= / 10 \/
  34512. // /\ 17 /\ =======
  34513. // / \ / \ \ 15 /\
  34514. // / 8 \/ 12 \ \ / \
  34515. // ============ \/ 6 \
  34516. // \ 18 /\ ============
  34517. // \ / \ \ 5 /\ 0 /
  34518. // \/ 13 \ \ / \ /
  34519. // ======= \/ 1 \/
  34520. // =============
  34521. // /\ 19 /\ 2 /\
  34522. // / \ / \ / \
  34523. // / 14 \/ 9 \/ 3 \
  34524. // ===================
  34525. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34526. var ustep = 138 / 1024;
  34527. var vstep = 239 / 1024;
  34528. var uoffset = 60 / 1024;
  34529. var voffset = 26 / 1024;
  34530. // Second island should have margin, not to touch the first island
  34531. // avoid any borderline artefact in pixel rounding
  34532. var island_u_offset = -40 / 1024;
  34533. var island_v_offset = +20 / 1024;
  34534. // face is either island 0 or 1 :
  34535. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34536. var island = [
  34537. 0, 0, 0, 0, 1,
  34538. 0, 0, 1, 1, 0,
  34539. 0, 0, 1, 1, 0,
  34540. 0, 1, 1, 1, 0 // 15 - 19
  34541. ];
  34542. var indices = new Array();
  34543. var positions = new Array();
  34544. var normals = new Array();
  34545. var uvs = new Array();
  34546. var current_indice = 0;
  34547. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34548. var face_vertex_pos = new Array(3);
  34549. var face_vertex_uv = new Array(3);
  34550. var v012;
  34551. for (v012 = 0; v012 < 3; v012++) {
  34552. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34553. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34554. }
  34555. // create all with normals
  34556. for (var face = 0; face < 20; face++) {
  34557. // 3 vertex per face
  34558. for (v012 = 0; v012 < 3; v012++) {
  34559. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34560. var v_id = ico_indices[3 * face + v012];
  34561. // vertex have 3D position (x,y,z)
  34562. 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]);
  34563. // Normalize to get normal, then scale to radius
  34564. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34565. // uv Coordinates from vertex ID
  34566. 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);
  34567. }
  34568. // Subdivide the face (interpolate pos, norm, uv)
  34569. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34570. // - norm is linear interpolation of vertex corner normal
  34571. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34572. // - uv is linear interpolation
  34573. //
  34574. // Topology is as below for sub-divide by 2
  34575. // vertex shown as v0,v1,v2
  34576. // interp index is i1 to progress in range [v0,v1[
  34577. // interp index is i2 to progress in range [v0,v2[
  34578. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34579. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34580. //
  34581. //
  34582. // i2 v2
  34583. // ^ ^
  34584. // / / \
  34585. // / / \
  34586. // / / \
  34587. // / / (0,1) \
  34588. // / #---------\
  34589. // / / \ (0,0)'/ \
  34590. // / / \ / \
  34591. // / / \ / \
  34592. // / / (0,0) \ / (1,0) \
  34593. // / #---------#---------\
  34594. // v0 v1
  34595. //
  34596. // --------------------> i1
  34597. //
  34598. // interp of (i1,i2):
  34599. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34600. // along i1 : lerp(x0,x1, i1/(S-i2))
  34601. //
  34602. // centroid of triangle is needed to get help normal computation
  34603. // (c1,c2) are used for centroid location
  34604. var interp_vertex = function (i1, i2, c1, c2) {
  34605. // vertex is interpolated from
  34606. // - face_vertex_pos[0..2]
  34607. // - face_vertex_uv[0..2]
  34608. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34609. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34610. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34611. pos_interp.normalize();
  34612. var vertex_normal;
  34613. if (flat) {
  34614. // in flat mode, recalculate normal as face centroid normal
  34615. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34616. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34617. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34618. }
  34619. else {
  34620. // in smooth mode, recalculate normal from each single vertex position
  34621. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34622. }
  34623. // Vertex normal need correction due to X,Y,Z radius scaling
  34624. vertex_normal.x /= radiusX;
  34625. vertex_normal.y /= radiusY;
  34626. vertex_normal.z /= radiusZ;
  34627. vertex_normal.normalize();
  34628. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34629. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34630. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34631. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34632. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34633. uvs.push(uv_interp.x, uv_interp.y);
  34634. // push each vertex has member of a face
  34635. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34636. indices.push(current_indice);
  34637. current_indice++;
  34638. };
  34639. for (var i2 = 0; i2 < subdivisions; i2++) {
  34640. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34641. // face : (i1,i2) for /\ :
  34642. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34643. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34644. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34645. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34646. if (i1 + i2 + 1 < subdivisions) {
  34647. // face : (i1,i2)' for \/ :
  34648. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34649. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34650. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34651. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34652. }
  34653. }
  34654. }
  34655. }
  34656. // Sides
  34657. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34658. // Result
  34659. var vertexData = new VertexData();
  34660. vertexData.indices = indices;
  34661. vertexData.positions = positions;
  34662. vertexData.normals = normals;
  34663. vertexData.uvs = uvs;
  34664. return vertexData;
  34665. };
  34666. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34667. /**
  34668. * Creates the VertexData of the Polyhedron.
  34669. */
  34670. VertexData.CreatePolyhedron = function (options) {
  34671. // provided polyhedron types :
  34672. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34673. // 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)
  34674. var polyhedra = [];
  34675. 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]] };
  34676. 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]] };
  34677. polyhedra[2] = {
  34678. 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]],
  34679. 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]]
  34680. };
  34681. polyhedra[3] = {
  34682. 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]],
  34683. 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]]
  34684. };
  34685. polyhedra[4] = {
  34686. 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]],
  34687. 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]]
  34688. };
  34689. 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]] };
  34690. 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]] };
  34691. 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]] };
  34692. 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]] };
  34693. 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]] };
  34694. 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]] };
  34695. 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]] };
  34696. 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]] };
  34697. 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]] };
  34698. polyhedra[14] = {
  34699. 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]],
  34700. 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]]
  34701. };
  34702. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34703. var size = options.size;
  34704. var sizeX = options.sizeX || size || 1;
  34705. var sizeY = options.sizeY || size || 1;
  34706. var sizeZ = options.sizeZ || size || 1;
  34707. var data = options.custom || polyhedra[type];
  34708. var nbfaces = data.face.length;
  34709. var faceUV = options.faceUV || new Array(nbfaces);
  34710. var faceColors = options.faceColors;
  34711. var flat = (options.flat === undefined) ? true : options.flat;
  34712. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34713. var positions = new Array();
  34714. var indices = new Array();
  34715. var normals = new Array();
  34716. var uvs = new Array();
  34717. var colors = new Array();
  34718. var index = 0;
  34719. var faceIdx = 0; // face cursor in the array "indexes"
  34720. var indexes = new Array();
  34721. var i = 0;
  34722. var f = 0;
  34723. var u, v, ang, x, y, tmp;
  34724. // default face colors and UV if undefined
  34725. if (flat) {
  34726. for (f = 0; f < nbfaces; f++) {
  34727. if (faceColors && faceColors[f] === undefined) {
  34728. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34729. }
  34730. if (faceUV && faceUV[f] === undefined) {
  34731. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34732. }
  34733. }
  34734. }
  34735. if (!flat) {
  34736. for (i = 0; i < data.vertex.length; i++) {
  34737. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34738. uvs.push(0, 0);
  34739. }
  34740. for (f = 0; f < nbfaces; f++) {
  34741. for (i = 0; i < data.face[f].length - 2; i++) {
  34742. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34743. }
  34744. }
  34745. }
  34746. else {
  34747. for (f = 0; f < nbfaces; f++) {
  34748. var fl = data.face[f].length; // number of vertices of the current face
  34749. ang = 2 * Math.PI / fl;
  34750. x = 0.5 * Math.tan(ang / 2);
  34751. y = 0.5;
  34752. // positions, uvs, colors
  34753. for (i = 0; i < fl; i++) {
  34754. // positions
  34755. 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);
  34756. indexes.push(index);
  34757. index++;
  34758. // uvs
  34759. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34760. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34761. uvs.push(u, v);
  34762. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34763. y = x * Math.sin(ang) + y * Math.cos(ang);
  34764. x = tmp;
  34765. // colors
  34766. if (faceColors) {
  34767. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34768. }
  34769. }
  34770. // indices from indexes
  34771. for (i = 0; i < fl - 2; i++) {
  34772. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34773. }
  34774. faceIdx += fl;
  34775. }
  34776. }
  34777. VertexData.ComputeNormals(positions, indices, normals);
  34778. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34779. var vertexData = new VertexData();
  34780. vertexData.positions = positions;
  34781. vertexData.indices = indices;
  34782. vertexData.normals = normals;
  34783. vertexData.uvs = uvs;
  34784. if (faceColors && flat) {
  34785. vertexData.colors = colors;
  34786. }
  34787. return vertexData;
  34788. };
  34789. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34790. /**
  34791. * Creates the VertexData of the Torus Knot.
  34792. */
  34793. VertexData.CreateTorusKnot = function (options) {
  34794. var indices = new Array();
  34795. var positions = new Array();
  34796. var normals = new Array();
  34797. var uvs = new Array();
  34798. var radius = options.radius || 2;
  34799. var tube = options.tube || 0.5;
  34800. var radialSegments = options.radialSegments || 32;
  34801. var tubularSegments = options.tubularSegments || 32;
  34802. var p = options.p || 2;
  34803. var q = options.q || 3;
  34804. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34805. // Helper
  34806. var getPos = function (angle) {
  34807. var cu = Math.cos(angle);
  34808. var su = Math.sin(angle);
  34809. var quOverP = q / p * angle;
  34810. var cs = Math.cos(quOverP);
  34811. var tx = radius * (2 + cs) * 0.5 * cu;
  34812. var ty = radius * (2 + cs) * su * 0.5;
  34813. var tz = radius * Math.sin(quOverP) * 0.5;
  34814. return new BABYLON.Vector3(tx, ty, tz);
  34815. };
  34816. // Vertices
  34817. var i;
  34818. var j;
  34819. for (i = 0; i <= radialSegments; i++) {
  34820. var modI = i % radialSegments;
  34821. var u = modI / radialSegments * 2 * p * Math.PI;
  34822. var p1 = getPos(u);
  34823. var p2 = getPos(u + 0.01);
  34824. var tang = p2.subtract(p1);
  34825. var n = p2.add(p1);
  34826. var bitan = BABYLON.Vector3.Cross(tang, n);
  34827. n = BABYLON.Vector3.Cross(bitan, tang);
  34828. bitan.normalize();
  34829. n.normalize();
  34830. for (j = 0; j < tubularSegments; j++) {
  34831. var modJ = j % tubularSegments;
  34832. var v = modJ / tubularSegments * 2 * Math.PI;
  34833. var cx = -tube * Math.cos(v);
  34834. var cy = tube * Math.sin(v);
  34835. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34836. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34837. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34838. uvs.push(i / radialSegments);
  34839. uvs.push(j / tubularSegments);
  34840. }
  34841. }
  34842. for (i = 0; i < radialSegments; i++) {
  34843. for (j = 0; j < tubularSegments; j++) {
  34844. var jNext = (j + 1) % tubularSegments;
  34845. var a = i * tubularSegments + j;
  34846. var b = (i + 1) * tubularSegments + j;
  34847. var c = (i + 1) * tubularSegments + jNext;
  34848. var d = i * tubularSegments + jNext;
  34849. indices.push(d);
  34850. indices.push(b);
  34851. indices.push(a);
  34852. indices.push(d);
  34853. indices.push(c);
  34854. indices.push(b);
  34855. }
  34856. }
  34857. // Normals
  34858. VertexData.ComputeNormals(positions, indices, normals);
  34859. // Sides
  34860. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34861. // Result
  34862. var vertexData = new VertexData();
  34863. vertexData.indices = indices;
  34864. vertexData.positions = positions;
  34865. vertexData.normals = normals;
  34866. vertexData.uvs = uvs;
  34867. return vertexData;
  34868. };
  34869. // Tools
  34870. /**
  34871. * @param {any} - positions (number[] or Float32Array)
  34872. * @param {any} - indices (number[] or Uint16Array)
  34873. * @param {any} - normals (number[] or Float32Array)
  34874. * options (optional) :
  34875. * facetPositions : optional array of facet positions (vector3)
  34876. * facetNormals : optional array of facet normals (vector3)
  34877. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34878. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34879. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34880. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34881. * bInfo : optional bounding info, required for facetPartitioning computation
  34882. * useRightHandedSystem: optional boolean to for right handed system computation
  34883. * depthSort : optional boolean to enable the facet depth sort computation
  34884. * distanceTo : optional Vector3 to compute the facet depth from this location
  34885. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34886. */
  34887. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34888. // temporary scalar variables
  34889. var index = 0; // facet index
  34890. var p1p2x = 0.0; // p1p2 vector x coordinate
  34891. var p1p2y = 0.0; // p1p2 vector y coordinate
  34892. var p1p2z = 0.0; // p1p2 vector z coordinate
  34893. var p3p2x = 0.0; // p3p2 vector x coordinate
  34894. var p3p2y = 0.0; // p3p2 vector y coordinate
  34895. var p3p2z = 0.0; // p3p2 vector z coordinate
  34896. var faceNormalx = 0.0; // facet normal x coordinate
  34897. var faceNormaly = 0.0; // facet normal y coordinate
  34898. var faceNormalz = 0.0; // facet normal z coordinate
  34899. var length = 0.0; // facet normal length before normalization
  34900. var v1x = 0; // vector1 x index in the positions array
  34901. var v1y = 0; // vector1 y index in the positions array
  34902. var v1z = 0; // vector1 z index in the positions array
  34903. var v2x = 0; // vector2 x index in the positions array
  34904. var v2y = 0; // vector2 y index in the positions array
  34905. var v2z = 0; // vector2 z index in the positions array
  34906. var v3x = 0; // vector3 x index in the positions array
  34907. var v3y = 0; // vector3 y index in the positions array
  34908. var v3z = 0; // vector3 z index in the positions array
  34909. var computeFacetNormals = false;
  34910. var computeFacetPositions = false;
  34911. var computeFacetPartitioning = false;
  34912. var computeDepthSort = false;
  34913. var faceNormalSign = 1;
  34914. var ratio = 0;
  34915. var distanceTo = null;
  34916. if (options) {
  34917. computeFacetNormals = (options.facetNormals) ? true : false;
  34918. computeFacetPositions = (options.facetPositions) ? true : false;
  34919. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34920. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34921. ratio = options.ratio || 0;
  34922. computeDepthSort = (options.depthSort) ? true : false;
  34923. distanceTo = (options.distanceTo);
  34924. if (computeDepthSort) {
  34925. if (distanceTo === undefined) {
  34926. distanceTo = BABYLON.Vector3.Zero();
  34927. }
  34928. var depthSortedFacets = options.depthSortedFacets;
  34929. }
  34930. }
  34931. // facetPartitioning reinit if needed
  34932. var xSubRatio = 0;
  34933. var ySubRatio = 0;
  34934. var zSubRatio = 0;
  34935. var subSq = 0;
  34936. if (computeFacetPartitioning && options && options.bbSize) {
  34937. var ox = 0; // X partitioning index for facet position
  34938. var oy = 0; // Y partinioning index for facet position
  34939. var oz = 0; // Z partinioning index for facet position
  34940. var b1x = 0; // X partitioning index for facet v1 vertex
  34941. var b1y = 0; // Y partitioning index for facet v1 vertex
  34942. var b1z = 0; // z partitioning index for facet v1 vertex
  34943. var b2x = 0; // X partitioning index for facet v2 vertex
  34944. var b2y = 0; // Y partitioning index for facet v2 vertex
  34945. var b2z = 0; // Z partitioning index for facet v2 vertex
  34946. var b3x = 0; // X partitioning index for facet v3 vertex
  34947. var b3y = 0; // Y partitioning index for facet v3 vertex
  34948. var b3z = 0; // Z partitioning index for facet v3 vertex
  34949. var block_idx_o = 0; // facet barycenter block index
  34950. var block_idx_v1 = 0; // v1 vertex block index
  34951. var block_idx_v2 = 0; // v2 vertex block index
  34952. var block_idx_v3 = 0; // v3 vertex block index
  34953. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34954. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34955. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34956. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34957. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34958. subSq = options.subDiv.max * options.subDiv.max;
  34959. options.facetPartitioning.length = 0;
  34960. }
  34961. // reset the normals
  34962. for (index = 0; index < positions.length; index++) {
  34963. normals[index] = 0.0;
  34964. }
  34965. // Loop : 1 indice triplet = 1 facet
  34966. var nbFaces = (indices.length / 3) | 0;
  34967. for (index = 0; index < nbFaces; index++) {
  34968. // get the indexes of the coordinates of each vertex of the facet
  34969. v1x = indices[index * 3] * 3;
  34970. v1y = v1x + 1;
  34971. v1z = v1x + 2;
  34972. v2x = indices[index * 3 + 1] * 3;
  34973. v2y = v2x + 1;
  34974. v2z = v2x + 2;
  34975. v3x = indices[index * 3 + 2] * 3;
  34976. v3y = v3x + 1;
  34977. v3z = v3x + 2;
  34978. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34979. p1p2y = positions[v1y] - positions[v2y];
  34980. p1p2z = positions[v1z] - positions[v2z];
  34981. p3p2x = positions[v3x] - positions[v2x];
  34982. p3p2y = positions[v3y] - positions[v2y];
  34983. p3p2z = positions[v3z] - positions[v2z];
  34984. // compute the face normal with the cross product
  34985. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34986. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34987. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34988. // normalize this normal and store it in the array facetData
  34989. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34990. length = (length === 0) ? 1.0 : length;
  34991. faceNormalx /= length;
  34992. faceNormaly /= length;
  34993. faceNormalz /= length;
  34994. if (computeFacetNormals && options) {
  34995. options.facetNormals[index].x = faceNormalx;
  34996. options.facetNormals[index].y = faceNormaly;
  34997. options.facetNormals[index].z = faceNormalz;
  34998. }
  34999. if (computeFacetPositions && options) {
  35000. // compute and the facet barycenter coordinates in the array facetPositions
  35001. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  35002. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35003. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35004. }
  35005. if (computeFacetPartitioning && options) {
  35006. // store the facet indexes in arrays in the main facetPartitioning array :
  35007. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35008. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  35009. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  35010. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  35011. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35012. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35013. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35014. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35015. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35016. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35017. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35018. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35019. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35020. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35021. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35022. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35023. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35024. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35025. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35026. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35027. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35028. // push each facet index in each block containing the vertex
  35029. options.facetPartitioning[block_idx_v1].push(index);
  35030. if (block_idx_v2 != block_idx_v1) {
  35031. options.facetPartitioning[block_idx_v2].push(index);
  35032. }
  35033. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35034. options.facetPartitioning[block_idx_v3].push(index);
  35035. }
  35036. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35037. options.facetPartitioning[block_idx_o].push(index);
  35038. }
  35039. }
  35040. if (computeDepthSort && options && options.facetPositions) {
  35041. var dsf = depthSortedFacets[index];
  35042. dsf.ind = index * 3;
  35043. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35044. }
  35045. // compute the normals anyway
  35046. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35047. normals[v1y] += faceNormaly;
  35048. normals[v1z] += faceNormalz;
  35049. normals[v2x] += faceNormalx;
  35050. normals[v2y] += faceNormaly;
  35051. normals[v2z] += faceNormalz;
  35052. normals[v3x] += faceNormalx;
  35053. normals[v3y] += faceNormaly;
  35054. normals[v3z] += faceNormalz;
  35055. }
  35056. // last normalization of each normal
  35057. for (index = 0; index < normals.length / 3; index++) {
  35058. faceNormalx = normals[index * 3];
  35059. faceNormaly = normals[index * 3 + 1];
  35060. faceNormalz = normals[index * 3 + 2];
  35061. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35062. length = (length === 0) ? 1.0 : length;
  35063. faceNormalx /= length;
  35064. faceNormaly /= length;
  35065. faceNormalz /= length;
  35066. normals[index * 3] = faceNormalx;
  35067. normals[index * 3 + 1] = faceNormaly;
  35068. normals[index * 3 + 2] = faceNormalz;
  35069. }
  35070. };
  35071. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35072. var li = indices.length;
  35073. var ln = normals.length;
  35074. var i;
  35075. var n;
  35076. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35077. switch (sideOrientation) {
  35078. case BABYLON.Mesh.FRONTSIDE:
  35079. // nothing changed
  35080. break;
  35081. case BABYLON.Mesh.BACKSIDE:
  35082. var tmp;
  35083. // indices
  35084. for (i = 0; i < li; i += 3) {
  35085. tmp = indices[i];
  35086. indices[i] = indices[i + 2];
  35087. indices[i + 2] = tmp;
  35088. }
  35089. // normals
  35090. for (n = 0; n < ln; n++) {
  35091. normals[n] = -normals[n];
  35092. }
  35093. break;
  35094. case BABYLON.Mesh.DOUBLESIDE:
  35095. // positions
  35096. var lp = positions.length;
  35097. var l = lp / 3;
  35098. for (var p = 0; p < lp; p++) {
  35099. positions[lp + p] = positions[p];
  35100. }
  35101. // indices
  35102. for (i = 0; i < li; i += 3) {
  35103. indices[i + li] = indices[i + 2] + l;
  35104. indices[i + 1 + li] = indices[i + 1] + l;
  35105. indices[i + 2 + li] = indices[i] + l;
  35106. }
  35107. // normals
  35108. for (n = 0; n < ln; n++) {
  35109. normals[ln + n] = -normals[n];
  35110. }
  35111. // uvs
  35112. var lu = uvs.length;
  35113. var u = 0;
  35114. for (u = 0; u < lu; u++) {
  35115. uvs[u + lu] = uvs[u];
  35116. }
  35117. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35118. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35119. u = 0;
  35120. for (i = 0; i < lu / 2; i++) {
  35121. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35122. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35123. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35124. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35125. u += 2;
  35126. }
  35127. break;
  35128. }
  35129. };
  35130. /**
  35131. * Creates a new VertexData from the imported parameters.
  35132. */
  35133. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35134. var vertexData = new VertexData();
  35135. // positions
  35136. var positions = parsedVertexData.positions;
  35137. if (positions) {
  35138. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35139. }
  35140. // normals
  35141. var normals = parsedVertexData.normals;
  35142. if (normals) {
  35143. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35144. }
  35145. // tangents
  35146. var tangents = parsedVertexData.tangents;
  35147. if (tangents) {
  35148. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35149. }
  35150. // uvs
  35151. var uvs = parsedVertexData.uvs;
  35152. if (uvs) {
  35153. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35154. }
  35155. // uv2s
  35156. var uv2s = parsedVertexData.uv2s;
  35157. if (uv2s) {
  35158. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35159. }
  35160. // uv3s
  35161. var uv3s = parsedVertexData.uv3s;
  35162. if (uv3s) {
  35163. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35164. }
  35165. // uv4s
  35166. var uv4s = parsedVertexData.uv4s;
  35167. if (uv4s) {
  35168. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35169. }
  35170. // uv5s
  35171. var uv5s = parsedVertexData.uv5s;
  35172. if (uv5s) {
  35173. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35174. }
  35175. // uv6s
  35176. var uv6s = parsedVertexData.uv6s;
  35177. if (uv6s) {
  35178. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35179. }
  35180. // colors
  35181. var colors = parsedVertexData.colors;
  35182. if (colors) {
  35183. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35184. }
  35185. // matricesIndices
  35186. var matricesIndices = parsedVertexData.matricesIndices;
  35187. if (matricesIndices) {
  35188. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35189. }
  35190. // matricesWeights
  35191. var matricesWeights = parsedVertexData.matricesWeights;
  35192. if (matricesWeights) {
  35193. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35194. }
  35195. // indices
  35196. var indices = parsedVertexData.indices;
  35197. if (indices) {
  35198. vertexData.indices = indices;
  35199. }
  35200. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35201. };
  35202. return VertexData;
  35203. }());
  35204. BABYLON.VertexData = VertexData;
  35205. })(BABYLON || (BABYLON = {}));
  35206. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35207. "use strict";
  35208. var BABYLON;
  35209. (function (BABYLON) {
  35210. /**
  35211. * Class used to store geometry data (vertex buffers + index buffer)
  35212. */
  35213. var Geometry = /** @class */ (function () {
  35214. /**
  35215. * Creates a new geometry
  35216. * @param id defines the unique ID
  35217. * @param scene defines the hosting scene
  35218. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35219. * @param updatable defines if geometry must be updatable (false by default)
  35220. * @param mesh defines the mesh that will be associated with the geometry
  35221. */
  35222. function Geometry(id, scene, vertexData, updatable, mesh) {
  35223. if (updatable === void 0) { updatable = false; }
  35224. if (mesh === void 0) { mesh = null; }
  35225. /**
  35226. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35227. */
  35228. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35229. this._totalVertices = 0;
  35230. this._isDisposed = false;
  35231. this._indexBufferIsUpdatable = false;
  35232. this.id = id;
  35233. this._engine = scene.getEngine();
  35234. this._meshes = [];
  35235. this._scene = scene;
  35236. //Init vertex buffer cache
  35237. this._vertexBuffers = {};
  35238. this._indices = [];
  35239. this._updatable = updatable;
  35240. // vertexData
  35241. if (vertexData) {
  35242. this.setAllVerticesData(vertexData, updatable);
  35243. }
  35244. else {
  35245. this._totalVertices = 0;
  35246. this._indices = [];
  35247. }
  35248. if (this._engine.getCaps().vertexArrayObject) {
  35249. this._vertexArrayObjects = {};
  35250. }
  35251. // applyToMesh
  35252. if (mesh) {
  35253. if (mesh.getClassName() === "LinesMesh") {
  35254. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35255. this.updateExtend();
  35256. }
  35257. this.applyToMesh(mesh);
  35258. mesh.computeWorldMatrix(true);
  35259. }
  35260. }
  35261. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35262. /**
  35263. * 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
  35264. */
  35265. get: function () {
  35266. return this._boundingBias;
  35267. },
  35268. /**
  35269. * 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
  35270. */
  35271. set: function (value) {
  35272. if (this._boundingBias && this._boundingBias.equals(value)) {
  35273. return;
  35274. }
  35275. this._boundingBias = value.clone();
  35276. this.updateBoundingInfo(true, null);
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. /**
  35282. * Static function used to attach a new empty geometry to a mesh
  35283. * @param mesh defines the mesh to attach the geometry to
  35284. * @returns the new {BABYLON.Geometry}
  35285. */
  35286. Geometry.CreateGeometryForMesh = function (mesh) {
  35287. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35288. geometry.applyToMesh(mesh);
  35289. return geometry;
  35290. };
  35291. Object.defineProperty(Geometry.prototype, "extend", {
  35292. /**
  35293. * Gets the current extend of the geometry
  35294. */
  35295. get: function () {
  35296. return this._extend;
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. /**
  35302. * Gets the hosting scene
  35303. * @returns the hosting {BABYLON.Scene}
  35304. */
  35305. Geometry.prototype.getScene = function () {
  35306. return this._scene;
  35307. };
  35308. /**
  35309. * Gets the hosting engine
  35310. * @returns the hosting {BABYLON.Engine}
  35311. */
  35312. Geometry.prototype.getEngine = function () {
  35313. return this._engine;
  35314. };
  35315. /**
  35316. * Defines if the geometry is ready to use
  35317. * @returns true if the geometry is ready to be used
  35318. */
  35319. Geometry.prototype.isReady = function () {
  35320. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35321. };
  35322. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35323. /**
  35324. * Gets a value indicating that the geometry should not be serialized
  35325. */
  35326. get: function () {
  35327. for (var index = 0; index < this._meshes.length; index++) {
  35328. if (!this._meshes[index].doNotSerialize) {
  35329. return false;
  35330. }
  35331. }
  35332. return true;
  35333. },
  35334. enumerable: true,
  35335. configurable: true
  35336. });
  35337. /** @ignore */
  35338. Geometry.prototype._rebuild = function () {
  35339. if (this._vertexArrayObjects) {
  35340. this._vertexArrayObjects = {};
  35341. }
  35342. // Index buffer
  35343. if (this._meshes.length !== 0 && this._indices) {
  35344. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35345. }
  35346. // Vertex buffers
  35347. for (var key in this._vertexBuffers) {
  35348. var vertexBuffer = this._vertexBuffers[key];
  35349. vertexBuffer._rebuild();
  35350. }
  35351. };
  35352. /**
  35353. * Affects all gemetry data in one call
  35354. * @param vertexData defines the geometry data
  35355. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35356. */
  35357. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35358. vertexData.applyToGeometry(this, updatable);
  35359. this.notifyUpdate();
  35360. };
  35361. /**
  35362. * Set specific vertex data
  35363. * @param kind defines the data kind (Position, normal, etc...)
  35364. * @param data defines the vertex data to use
  35365. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35366. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35367. */
  35368. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35369. if (updatable === void 0) { updatable = false; }
  35370. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35371. this.setVerticesBuffer(buffer);
  35372. };
  35373. /**
  35374. * Removes a specific vertex data
  35375. * @param kind defines the data kind (Position, normal, etc...)
  35376. */
  35377. Geometry.prototype.removeVerticesData = function (kind) {
  35378. if (this._vertexBuffers[kind]) {
  35379. this._vertexBuffers[kind].dispose();
  35380. delete this._vertexBuffers[kind];
  35381. }
  35382. };
  35383. /**
  35384. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35385. * @param buffer defines the vertex buffer to use
  35386. */
  35387. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35388. var kind = buffer.getKind();
  35389. if (this._vertexBuffers[kind]) {
  35390. this._vertexBuffers[kind].dispose();
  35391. }
  35392. this._vertexBuffers[kind] = buffer;
  35393. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35394. var data = buffer.getData();
  35395. var stride = buffer.getStrideSize();
  35396. this._totalVertices = data.length / stride;
  35397. this.updateExtend(data, stride);
  35398. this._resetPointsArrayCache();
  35399. var meshes = this._meshes;
  35400. var numOfMeshes = meshes.length;
  35401. for (var index = 0; index < numOfMeshes; index++) {
  35402. var mesh = meshes[index];
  35403. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35404. mesh._createGlobalSubMesh(false);
  35405. mesh.computeWorldMatrix(true);
  35406. }
  35407. }
  35408. this.notifyUpdate(kind);
  35409. if (this._vertexArrayObjects) {
  35410. this._disposeVertexArrayObjects();
  35411. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35412. }
  35413. };
  35414. /**
  35415. * Update a specific vertex buffer
  35416. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35417. * It will do nothing if the buffer is not updatable
  35418. * @param kind defines the data kind (Position, normal, etc...)
  35419. * @param data defines the data to use
  35420. * @param offset defines the offset in the target buffer where to store the data
  35421. */
  35422. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35423. var vertexBuffer = this.getVertexBuffer(kind);
  35424. if (!vertexBuffer) {
  35425. return;
  35426. }
  35427. vertexBuffer.updateDirectly(data, offset);
  35428. this.notifyUpdate(kind);
  35429. };
  35430. /**
  35431. * Update a specific vertex buffer
  35432. * This function will create a new buffer if the current one is not updatable
  35433. * @param kind defines the data kind (Position, normal, etc...)
  35434. * @param data defines the data to use
  35435. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35436. */
  35437. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35438. if (updateExtends === void 0) { updateExtends = false; }
  35439. var vertexBuffer = this.getVertexBuffer(kind);
  35440. if (!vertexBuffer) {
  35441. return;
  35442. }
  35443. vertexBuffer.update(data);
  35444. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35445. var stride = vertexBuffer.getStrideSize();
  35446. this._totalVertices = data.length / stride;
  35447. this.updateBoundingInfo(updateExtends, data);
  35448. }
  35449. this.notifyUpdate(kind);
  35450. };
  35451. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35452. if (updateExtends) {
  35453. this.updateExtend(data);
  35454. }
  35455. var meshes = this._meshes;
  35456. var numOfMeshes = meshes.length;
  35457. this._resetPointsArrayCache();
  35458. for (var index = 0; index < numOfMeshes; index++) {
  35459. var mesh = meshes[index];
  35460. if (updateExtends) {
  35461. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35462. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35463. var subMesh = mesh.subMeshes[subIndex];
  35464. subMesh.refreshBoundingInfo();
  35465. }
  35466. }
  35467. }
  35468. };
  35469. /** @ignore */
  35470. Geometry.prototype._bind = function (effect, indexToBind) {
  35471. if (!effect) {
  35472. return;
  35473. }
  35474. if (indexToBind === undefined) {
  35475. indexToBind = this._indexBuffer;
  35476. }
  35477. var vbs = this.getVertexBuffers();
  35478. if (!vbs) {
  35479. return;
  35480. }
  35481. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35482. this._engine.bindBuffers(vbs, indexToBind, effect);
  35483. return;
  35484. }
  35485. // Using VAO
  35486. if (!this._vertexArrayObjects[effect.key]) {
  35487. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35488. }
  35489. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35490. };
  35491. /**
  35492. * Gets total number of vertices
  35493. * @returns the total number of vertices
  35494. */
  35495. Geometry.prototype.getTotalVertices = function () {
  35496. if (!this.isReady()) {
  35497. return 0;
  35498. }
  35499. return this._totalVertices;
  35500. };
  35501. /**
  35502. * Gets a specific vertex data attached to this geometry
  35503. * @param kind defines the data kind (Position, normal, etc...)
  35504. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35505. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35506. * @returns a float array containing vertex data
  35507. */
  35508. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35509. var vertexBuffer = this.getVertexBuffer(kind);
  35510. if (!vertexBuffer) {
  35511. return null;
  35512. }
  35513. var orig = vertexBuffer.getData();
  35514. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35515. return orig;
  35516. }
  35517. else {
  35518. var len = orig.length;
  35519. var copy = [];
  35520. for (var i = 0; i < len; i++) {
  35521. copy.push(orig[i]);
  35522. }
  35523. return copy;
  35524. }
  35525. };
  35526. /**
  35527. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35528. * @param kind defines the data kind (Position, normal, etc...)
  35529. * @returns true if the vertex buffer with the specified kind is updatable
  35530. */
  35531. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35532. var vb = this._vertexBuffers[kind];
  35533. if (!vb) {
  35534. return false;
  35535. }
  35536. return vb.isUpdatable();
  35537. };
  35538. /**
  35539. * Gets a specific vertex buffer
  35540. * @param kind defines the data kind (Position, normal, etc...)
  35541. * @returns a {BABYLON.VertexBuffer}
  35542. */
  35543. Geometry.prototype.getVertexBuffer = function (kind) {
  35544. if (!this.isReady()) {
  35545. return null;
  35546. }
  35547. return this._vertexBuffers[kind];
  35548. };
  35549. /**
  35550. * Returns all vertex buffers
  35551. * @return an object holding all vertex buffers indexed by kind
  35552. */
  35553. Geometry.prototype.getVertexBuffers = function () {
  35554. if (!this.isReady()) {
  35555. return null;
  35556. }
  35557. return this._vertexBuffers;
  35558. };
  35559. /**
  35560. * Gets a boolean indicating if specific vertex buffer is present
  35561. * @param kind defines the data kind (Position, normal, etc...)
  35562. * @returns true if data is present
  35563. */
  35564. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35565. if (!this._vertexBuffers) {
  35566. if (this._delayInfo) {
  35567. return this._delayInfo.indexOf(kind) !== -1;
  35568. }
  35569. return false;
  35570. }
  35571. return this._vertexBuffers[kind] !== undefined;
  35572. };
  35573. /**
  35574. * Gets a list of all attached data kinds (Position, normal, etc...)
  35575. * @returns a list of string containing all kinds
  35576. */
  35577. Geometry.prototype.getVerticesDataKinds = function () {
  35578. var result = [];
  35579. var kind;
  35580. if (!this._vertexBuffers && this._delayInfo) {
  35581. for (kind in this._delayInfo) {
  35582. result.push(kind);
  35583. }
  35584. }
  35585. else {
  35586. for (kind in this._vertexBuffers) {
  35587. result.push(kind);
  35588. }
  35589. }
  35590. return result;
  35591. };
  35592. /**
  35593. * Update index buffer
  35594. * @param indices defines the indices to store in the index buffer
  35595. * @param offset defines the offset in the target buffer where to store the data
  35596. */
  35597. Geometry.prototype.updateIndices = function (indices, offset) {
  35598. if (!this._indexBuffer) {
  35599. return;
  35600. }
  35601. if (!this._indexBufferIsUpdatable) {
  35602. this.setIndices(indices, null, true);
  35603. }
  35604. else {
  35605. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35606. }
  35607. };
  35608. /**
  35609. * Creates a new index buffer
  35610. * @param indices defines the indices to store in the index buffer
  35611. * @param totalVertices defines the total number of vertices (could be null)
  35612. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35613. */
  35614. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35615. if (totalVertices === void 0) { totalVertices = null; }
  35616. if (updatable === void 0) { updatable = false; }
  35617. if (this._indexBuffer) {
  35618. this._engine._releaseBuffer(this._indexBuffer);
  35619. }
  35620. this._disposeVertexArrayObjects();
  35621. this._indices = indices;
  35622. this._indexBufferIsUpdatable = updatable;
  35623. if (this._meshes.length !== 0 && this._indices) {
  35624. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35625. }
  35626. if (totalVertices != undefined) {
  35627. this._totalVertices = totalVertices;
  35628. }
  35629. var meshes = this._meshes;
  35630. var numOfMeshes = meshes.length;
  35631. for (var index = 0; index < numOfMeshes; index++) {
  35632. meshes[index]._createGlobalSubMesh(true);
  35633. }
  35634. this.notifyUpdate();
  35635. };
  35636. /**
  35637. * Return the total number of indices
  35638. * @returns the total number of indices
  35639. */
  35640. Geometry.prototype.getTotalIndices = function () {
  35641. if (!this.isReady()) {
  35642. return 0;
  35643. }
  35644. return this._indices.length;
  35645. };
  35646. /**
  35647. * Gets the index buffer array
  35648. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35649. * @returns the index buffer array
  35650. */
  35651. Geometry.prototype.getIndices = function (copyWhenShared) {
  35652. if (!this.isReady()) {
  35653. return null;
  35654. }
  35655. var orig = this._indices;
  35656. if (!copyWhenShared || this._meshes.length === 1) {
  35657. return orig;
  35658. }
  35659. else {
  35660. var len = orig.length;
  35661. var copy = [];
  35662. for (var i = 0; i < len; i++) {
  35663. copy.push(orig[i]);
  35664. }
  35665. return copy;
  35666. }
  35667. };
  35668. /**
  35669. * Gets the index buffer
  35670. * @return the index buffer
  35671. */
  35672. Geometry.prototype.getIndexBuffer = function () {
  35673. if (!this.isReady()) {
  35674. return null;
  35675. }
  35676. return this._indexBuffer;
  35677. };
  35678. /** @ignore */
  35679. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35680. if (effect === void 0) { effect = null; }
  35681. if (!effect || !this._vertexArrayObjects) {
  35682. return;
  35683. }
  35684. if (this._vertexArrayObjects[effect.key]) {
  35685. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35686. delete this._vertexArrayObjects[effect.key];
  35687. }
  35688. };
  35689. /**
  35690. * Release the associated resources for a specific mesh
  35691. * @param mesh defines the source mesh
  35692. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35693. */
  35694. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35695. var meshes = this._meshes;
  35696. var index = meshes.indexOf(mesh);
  35697. if (index === -1) {
  35698. return;
  35699. }
  35700. meshes.splice(index, 1);
  35701. mesh._geometry = null;
  35702. if (meshes.length === 0 && shouldDispose) {
  35703. this.dispose();
  35704. }
  35705. };
  35706. /**
  35707. * Apply current geometry to a given mesh
  35708. * @param mesh defines the mesh to apply geometry to
  35709. */
  35710. Geometry.prototype.applyToMesh = function (mesh) {
  35711. if (mesh._geometry === this) {
  35712. return;
  35713. }
  35714. var previousGeometry = mesh._geometry;
  35715. if (previousGeometry) {
  35716. previousGeometry.releaseForMesh(mesh);
  35717. }
  35718. var meshes = this._meshes;
  35719. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35720. mesh._geometry = this;
  35721. this._scene.pushGeometry(this);
  35722. meshes.push(mesh);
  35723. if (this.isReady()) {
  35724. this._applyToMesh(mesh);
  35725. }
  35726. else {
  35727. mesh._boundingInfo = this._boundingInfo;
  35728. }
  35729. };
  35730. Geometry.prototype.updateExtend = function (data, stride) {
  35731. if (data === void 0) { data = null; }
  35732. if (!data) {
  35733. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35734. }
  35735. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35736. };
  35737. Geometry.prototype._applyToMesh = function (mesh) {
  35738. var numOfMeshes = this._meshes.length;
  35739. // vertexBuffers
  35740. for (var kind in this._vertexBuffers) {
  35741. if (numOfMeshes === 1) {
  35742. this._vertexBuffers[kind].create();
  35743. }
  35744. var buffer = this._vertexBuffers[kind].getBuffer();
  35745. if (buffer)
  35746. buffer.references = numOfMeshes;
  35747. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35748. if (!this._extend) {
  35749. this.updateExtend(this._vertexBuffers[kind].getData());
  35750. }
  35751. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35752. mesh._createGlobalSubMesh(false);
  35753. //bounding info was just created again, world matrix should be applied again.
  35754. mesh._updateBoundingInfo();
  35755. }
  35756. }
  35757. // indexBuffer
  35758. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35759. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35760. }
  35761. if (this._indexBuffer) {
  35762. this._indexBuffer.references = numOfMeshes;
  35763. }
  35764. };
  35765. Geometry.prototype.notifyUpdate = function (kind) {
  35766. if (this.onGeometryUpdated) {
  35767. this.onGeometryUpdated(this, kind);
  35768. }
  35769. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35770. var mesh = _a[_i];
  35771. mesh._markSubMeshesAsAttributesDirty();
  35772. }
  35773. };
  35774. /**
  35775. * Load the geometry if it was flagged as delay loaded
  35776. * @param scene defines the hosting scene
  35777. * @param onLoaded defines a callback called when the geometry is loaded
  35778. */
  35779. Geometry.prototype.load = function (scene, onLoaded) {
  35780. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35781. return;
  35782. }
  35783. if (this.isReady()) {
  35784. if (onLoaded) {
  35785. onLoaded();
  35786. }
  35787. return;
  35788. }
  35789. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35790. this._queueLoad(scene, onLoaded);
  35791. };
  35792. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35793. var _this = this;
  35794. if (!this.delayLoadingFile) {
  35795. return;
  35796. }
  35797. scene._addPendingData(this);
  35798. scene._loadFile(this.delayLoadingFile, function (data) {
  35799. if (!_this._delayLoadingFunction) {
  35800. return;
  35801. }
  35802. _this._delayLoadingFunction(JSON.parse(data), _this);
  35803. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35804. _this._delayInfo = [];
  35805. scene._removePendingData(_this);
  35806. var meshes = _this._meshes;
  35807. var numOfMeshes = meshes.length;
  35808. for (var index = 0; index < numOfMeshes; index++) {
  35809. _this._applyToMesh(meshes[index]);
  35810. }
  35811. if (onLoaded) {
  35812. onLoaded();
  35813. }
  35814. }, undefined, true);
  35815. };
  35816. /**
  35817. * Invert the geometry to move from a right handed system to a left handed one.
  35818. */
  35819. Geometry.prototype.toLeftHanded = function () {
  35820. // Flip faces
  35821. var tIndices = this.getIndices(false);
  35822. if (tIndices != null && tIndices.length > 0) {
  35823. for (var i = 0; i < tIndices.length; i += 3) {
  35824. var tTemp = tIndices[i + 0];
  35825. tIndices[i + 0] = tIndices[i + 2];
  35826. tIndices[i + 2] = tTemp;
  35827. }
  35828. this.setIndices(tIndices);
  35829. }
  35830. // Negate position.z
  35831. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35832. if (tPositions != null && tPositions.length > 0) {
  35833. for (var i = 0; i < tPositions.length; i += 3) {
  35834. tPositions[i + 2] = -tPositions[i + 2];
  35835. }
  35836. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35837. }
  35838. // Negate normal.z
  35839. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35840. if (tNormals != null && tNormals.length > 0) {
  35841. for (var i = 0; i < tNormals.length; i += 3) {
  35842. tNormals[i + 2] = -tNormals[i + 2];
  35843. }
  35844. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35845. }
  35846. };
  35847. // Cache
  35848. /** @ignore */
  35849. Geometry.prototype._resetPointsArrayCache = function () {
  35850. this._positions = null;
  35851. };
  35852. /** @ignore */
  35853. Geometry.prototype._generatePointsArray = function () {
  35854. if (this._positions)
  35855. return true;
  35856. this._positions = [];
  35857. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35858. if (!data) {
  35859. return false;
  35860. }
  35861. for (var index = 0; index < data.length; index += 3) {
  35862. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35863. }
  35864. return true;
  35865. };
  35866. /**
  35867. * Gets a value indicating if the geometry is disposed
  35868. * @returns true if the geometry was disposed
  35869. */
  35870. Geometry.prototype.isDisposed = function () {
  35871. return this._isDisposed;
  35872. };
  35873. Geometry.prototype._disposeVertexArrayObjects = function () {
  35874. if (this._vertexArrayObjects) {
  35875. for (var kind in this._vertexArrayObjects) {
  35876. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35877. }
  35878. this._vertexArrayObjects = {};
  35879. }
  35880. };
  35881. /**
  35882. * Free all associated resources
  35883. */
  35884. Geometry.prototype.dispose = function () {
  35885. var meshes = this._meshes;
  35886. var numOfMeshes = meshes.length;
  35887. var index;
  35888. for (index = 0; index < numOfMeshes; index++) {
  35889. this.releaseForMesh(meshes[index]);
  35890. }
  35891. this._meshes = [];
  35892. this._disposeVertexArrayObjects();
  35893. for (var kind in this._vertexBuffers) {
  35894. this._vertexBuffers[kind].dispose();
  35895. }
  35896. this._vertexBuffers = {};
  35897. this._totalVertices = 0;
  35898. if (this._indexBuffer) {
  35899. this._engine._releaseBuffer(this._indexBuffer);
  35900. }
  35901. this._indexBuffer = null;
  35902. this._indices = [];
  35903. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35904. this.delayLoadingFile = null;
  35905. this._delayLoadingFunction = null;
  35906. this._delayInfo = [];
  35907. this._boundingInfo = null;
  35908. this._scene.removeGeometry(this);
  35909. this._isDisposed = true;
  35910. };
  35911. /**
  35912. * Clone the current geometry into a new geometry
  35913. * @param id defines the unique ID of the new geometry
  35914. * @returns a new geometry object
  35915. */
  35916. Geometry.prototype.copy = function (id) {
  35917. var vertexData = new BABYLON.VertexData();
  35918. vertexData.indices = [];
  35919. var indices = this.getIndices();
  35920. if (indices) {
  35921. for (var index = 0; index < indices.length; index++) {
  35922. vertexData.indices.push(indices[index]);
  35923. }
  35924. }
  35925. var updatable = false;
  35926. var stopChecking = false;
  35927. var kind;
  35928. for (kind in this._vertexBuffers) {
  35929. // using slice() to make a copy of the array and not just reference it
  35930. var data = this.getVerticesData(kind);
  35931. if (data instanceof Float32Array) {
  35932. vertexData.set(new Float32Array(data), kind);
  35933. }
  35934. else {
  35935. vertexData.set(data.slice(0), kind);
  35936. }
  35937. if (!stopChecking) {
  35938. var vb = this.getVertexBuffer(kind);
  35939. if (vb) {
  35940. updatable = vb.isUpdatable();
  35941. stopChecking = !updatable;
  35942. }
  35943. }
  35944. }
  35945. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35946. geometry.delayLoadState = this.delayLoadState;
  35947. geometry.delayLoadingFile = this.delayLoadingFile;
  35948. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35949. for (kind in this._delayInfo) {
  35950. geometry._delayInfo = geometry._delayInfo || [];
  35951. geometry._delayInfo.push(kind);
  35952. }
  35953. // Bounding info
  35954. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35955. return geometry;
  35956. };
  35957. /**
  35958. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35959. * @return a JSON representation of the current geometry data (without the vertices data)
  35960. */
  35961. Geometry.prototype.serialize = function () {
  35962. var serializationObject = {};
  35963. serializationObject.id = this.id;
  35964. serializationObject.updatable = this._updatable;
  35965. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35966. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35967. }
  35968. return serializationObject;
  35969. };
  35970. Geometry.prototype.toNumberArray = function (origin) {
  35971. if (Array.isArray(origin)) {
  35972. return origin;
  35973. }
  35974. else {
  35975. return Array.prototype.slice.call(origin);
  35976. }
  35977. };
  35978. /**
  35979. * Serialize all vertices data into a JSON oject
  35980. * @returns a JSON representation of the current geometry data
  35981. */
  35982. Geometry.prototype.serializeVerticeData = function () {
  35983. var serializationObject = this.serialize();
  35984. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35985. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35986. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35987. serializationObject.positions._updatable = true;
  35988. }
  35989. }
  35990. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35991. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35992. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35993. serializationObject.normals._updatable = true;
  35994. }
  35995. }
  35996. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35997. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35998. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35999. serializationObject.tangets._updatable = true;
  36000. }
  36001. }
  36002. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36003. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  36004. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  36005. serializationObject.uvs._updatable = true;
  36006. }
  36007. }
  36008. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36009. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  36010. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  36011. serializationObject.uv2s._updatable = true;
  36012. }
  36013. }
  36014. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36015. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  36016. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  36017. serializationObject.uv3s._updatable = true;
  36018. }
  36019. }
  36020. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36021. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  36022. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  36023. serializationObject.uv4s._updatable = true;
  36024. }
  36025. }
  36026. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36027. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  36028. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  36029. serializationObject.uv5s._updatable = true;
  36030. }
  36031. }
  36032. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36033. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  36034. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  36035. serializationObject.uv6s._updatable = true;
  36036. }
  36037. }
  36038. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36039. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  36040. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  36041. serializationObject.colors._updatable = true;
  36042. }
  36043. }
  36044. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36045. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  36046. serializationObject.matricesIndices._isExpanded = true;
  36047. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36048. serializationObject.matricesIndices._updatable = true;
  36049. }
  36050. }
  36051. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36052. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36053. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36054. serializationObject.matricesWeights._updatable = true;
  36055. }
  36056. }
  36057. serializationObject.indices = this.toNumberArray(this.getIndices());
  36058. return serializationObject;
  36059. };
  36060. // Statics
  36061. /**
  36062. * Extracts a clone of a mesh geometry
  36063. * @param mesh defines the source mesh
  36064. * @param id defines the unique ID of the new geometry object
  36065. * @returns the new geometry object
  36066. */
  36067. Geometry.ExtractFromMesh = function (mesh, id) {
  36068. var geometry = mesh._geometry;
  36069. if (!geometry) {
  36070. return null;
  36071. }
  36072. return geometry.copy(id);
  36073. };
  36074. /**
  36075. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36076. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36077. * Be aware Math.random() could cause collisions, but:
  36078. * "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"
  36079. * @returns a string containing a new GUID
  36080. */
  36081. Geometry.RandomId = function () {
  36082. return BABYLON.Tools.RandomId();
  36083. };
  36084. /** @ignore */
  36085. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36086. var scene = mesh.getScene();
  36087. // Geometry
  36088. var geometryId = parsedGeometry.geometryId;
  36089. if (geometryId) {
  36090. var geometry = scene.getGeometryByID(geometryId);
  36091. if (geometry) {
  36092. geometry.applyToMesh(mesh);
  36093. }
  36094. }
  36095. else if (parsedGeometry instanceof ArrayBuffer) {
  36096. var binaryInfo = mesh._binaryInfo;
  36097. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36098. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36099. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36100. }
  36101. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36102. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36103. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36104. }
  36105. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36106. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36107. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36108. }
  36109. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36110. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36111. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36112. }
  36113. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36114. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36115. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36116. }
  36117. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36118. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36119. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36120. }
  36121. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36122. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36123. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36124. }
  36125. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36126. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36127. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36128. }
  36129. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36130. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36131. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36132. }
  36133. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36134. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36135. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36136. }
  36137. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36138. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36140. }
  36141. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36142. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36143. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36144. }
  36145. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36146. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36147. mesh.setIndices(indicesData, null);
  36148. }
  36149. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36150. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36151. mesh.subMeshes = [];
  36152. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36153. var materialIndex = subMeshesData[(i * 5) + 0];
  36154. var verticesStart = subMeshesData[(i * 5) + 1];
  36155. var verticesCount = subMeshesData[(i * 5) + 2];
  36156. var indexStart = subMeshesData[(i * 5) + 3];
  36157. var indexCount = subMeshesData[(i * 5) + 4];
  36158. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36159. }
  36160. }
  36161. }
  36162. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36163. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36164. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36165. if (parsedGeometry.tangents) {
  36166. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36167. }
  36168. if (parsedGeometry.uvs) {
  36169. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36170. }
  36171. if (parsedGeometry.uvs2) {
  36172. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36173. }
  36174. if (parsedGeometry.uvs3) {
  36175. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36176. }
  36177. if (parsedGeometry.uvs4) {
  36178. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36179. }
  36180. if (parsedGeometry.uvs5) {
  36181. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36182. }
  36183. if (parsedGeometry.uvs6) {
  36184. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36185. }
  36186. if (parsedGeometry.colors) {
  36187. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36188. }
  36189. if (parsedGeometry.matricesIndices) {
  36190. if (!parsedGeometry.matricesIndices._isExpanded) {
  36191. var floatIndices = [];
  36192. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36193. var matricesIndex = parsedGeometry.matricesIndices[i];
  36194. floatIndices.push(matricesIndex & 0x000000FF);
  36195. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36196. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36197. floatIndices.push(matricesIndex >> 24);
  36198. }
  36199. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36200. }
  36201. else {
  36202. delete parsedGeometry.matricesIndices._isExpanded;
  36203. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36204. }
  36205. }
  36206. if (parsedGeometry.matricesIndicesExtra) {
  36207. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36208. var floatIndices = [];
  36209. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36210. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36211. floatIndices.push(matricesIndex & 0x000000FF);
  36212. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36213. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36214. floatIndices.push(matricesIndex >> 24);
  36215. }
  36216. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36217. }
  36218. else {
  36219. delete parsedGeometry.matricesIndices._isExpanded;
  36220. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36221. }
  36222. }
  36223. if (parsedGeometry.matricesWeights) {
  36224. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36225. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36226. }
  36227. if (parsedGeometry.matricesWeightsExtra) {
  36228. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36229. }
  36230. mesh.setIndices(parsedGeometry.indices, null);
  36231. }
  36232. // SubMeshes
  36233. if (parsedGeometry.subMeshes) {
  36234. mesh.subMeshes = [];
  36235. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36236. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36237. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36238. }
  36239. }
  36240. // Flat shading
  36241. if (mesh._shouldGenerateFlatShading) {
  36242. mesh.convertToFlatShadedMesh();
  36243. delete mesh._shouldGenerateFlatShading;
  36244. }
  36245. // Update
  36246. mesh.computeWorldMatrix(true);
  36247. // Octree
  36248. var sceneOctree = scene.selectionOctree;
  36249. if (sceneOctree !== undefined && sceneOctree !== null) {
  36250. sceneOctree.addMesh(mesh);
  36251. }
  36252. };
  36253. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36254. var epsilon = 1e-3;
  36255. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36256. return;
  36257. }
  36258. var noInfluenceBoneIndex = 0.0;
  36259. if (parsedGeometry.skeletonId > -1) {
  36260. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36261. if (!skeleton) {
  36262. return;
  36263. }
  36264. noInfluenceBoneIndex = skeleton.bones.length;
  36265. }
  36266. else {
  36267. return;
  36268. }
  36269. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36270. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36271. var matricesWeights = parsedGeometry.matricesWeights;
  36272. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36273. var influencers = parsedGeometry.numBoneInfluencer;
  36274. var size = matricesWeights.length;
  36275. for (var i = 0; i < size; i += 4) {
  36276. var weight = 0.0;
  36277. var firstZeroWeight = -1;
  36278. for (var j = 0; j < 4; j++) {
  36279. var w = matricesWeights[i + j];
  36280. weight += w;
  36281. if (w < epsilon && firstZeroWeight < 0) {
  36282. firstZeroWeight = j;
  36283. }
  36284. }
  36285. if (matricesWeightsExtra) {
  36286. for (var j = 0; j < 4; j++) {
  36287. var w = matricesWeightsExtra[i + j];
  36288. weight += w;
  36289. if (w < epsilon && firstZeroWeight < 0) {
  36290. firstZeroWeight = j + 4;
  36291. }
  36292. }
  36293. }
  36294. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36295. firstZeroWeight = influencers - 1;
  36296. }
  36297. if (weight > epsilon) {
  36298. var mweight = 1.0 / weight;
  36299. for (var j = 0; j < 4; j++) {
  36300. matricesWeights[i + j] *= mweight;
  36301. }
  36302. if (matricesWeightsExtra) {
  36303. for (var j = 0; j < 4; j++) {
  36304. matricesWeightsExtra[i + j] *= mweight;
  36305. }
  36306. }
  36307. }
  36308. else {
  36309. if (firstZeroWeight >= 4) {
  36310. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36311. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36312. }
  36313. else {
  36314. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36315. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36316. }
  36317. }
  36318. }
  36319. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36320. if (parsedGeometry.matricesWeightsExtra) {
  36321. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36322. }
  36323. };
  36324. /**
  36325. * Create a new geometry from persisted data (Using .babylon file format)
  36326. * @param parsedVertexData defines the persisted data
  36327. * @param scene defines the hosting scene
  36328. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36329. * @returns the new geometry object
  36330. */
  36331. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36332. if (scene.getGeometryByID(parsedVertexData.id)) {
  36333. return null; // null since geometry could be something else than a box...
  36334. }
  36335. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36336. if (BABYLON.Tags) {
  36337. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36338. }
  36339. if (parsedVertexData.delayLoadingFile) {
  36340. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36341. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36342. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36343. geometry._delayInfo = [];
  36344. if (parsedVertexData.hasUVs) {
  36345. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36346. }
  36347. if (parsedVertexData.hasUVs2) {
  36348. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36349. }
  36350. if (parsedVertexData.hasUVs3) {
  36351. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36352. }
  36353. if (parsedVertexData.hasUVs4) {
  36354. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36355. }
  36356. if (parsedVertexData.hasUVs5) {
  36357. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36358. }
  36359. if (parsedVertexData.hasUVs6) {
  36360. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36361. }
  36362. if (parsedVertexData.hasColors) {
  36363. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36364. }
  36365. if (parsedVertexData.hasMatricesIndices) {
  36366. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36367. }
  36368. if (parsedVertexData.hasMatricesWeights) {
  36369. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36370. }
  36371. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36372. }
  36373. else {
  36374. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36375. }
  36376. scene.pushGeometry(geometry, true);
  36377. return geometry;
  36378. };
  36379. return Geometry;
  36380. }());
  36381. BABYLON.Geometry = Geometry;
  36382. // Primitives
  36383. /// Abstract class
  36384. /**
  36385. * Abstract class used to provide common services for all typed geometries
  36386. */
  36387. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36388. __extends(_PrimitiveGeometry, _super);
  36389. /**
  36390. * Creates a new typed geometry
  36391. * @param id defines the unique ID of the geometry
  36392. * @param scene defines the hosting scene
  36393. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36394. * @param mesh defines the hosting mesh (can be null)
  36395. */
  36396. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36397. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36398. if (mesh === void 0) { mesh = null; }
  36399. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36400. _this._canBeRegenerated = _canBeRegenerated;
  36401. _this._beingRegenerated = true;
  36402. _this.regenerate();
  36403. _this._beingRegenerated = false;
  36404. return _this;
  36405. }
  36406. /**
  36407. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36408. * @returns true if the geometry can be regenerated
  36409. */
  36410. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36411. return this._canBeRegenerated;
  36412. };
  36413. /**
  36414. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36415. */
  36416. _PrimitiveGeometry.prototype.regenerate = function () {
  36417. if (!this._canBeRegenerated) {
  36418. return;
  36419. }
  36420. this._beingRegenerated = true;
  36421. this.setAllVerticesData(this._regenerateVertexData(), false);
  36422. this._beingRegenerated = false;
  36423. };
  36424. /**
  36425. * Clone the geometry
  36426. * @param id defines the unique ID of the new geometry
  36427. * @returns the new geometry
  36428. */
  36429. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36430. return _super.prototype.copy.call(this, id);
  36431. };
  36432. // overrides
  36433. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36434. if (!this._beingRegenerated) {
  36435. return;
  36436. }
  36437. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36438. };
  36439. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36440. if (!this._beingRegenerated) {
  36441. return;
  36442. }
  36443. _super.prototype.setVerticesData.call(this, kind, data, false);
  36444. };
  36445. // to override
  36446. /** @ignore */
  36447. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36448. throw new Error("Abstract method");
  36449. };
  36450. _PrimitiveGeometry.prototype.copy = function (id) {
  36451. throw new Error("Must be overriden in sub-classes.");
  36452. };
  36453. _PrimitiveGeometry.prototype.serialize = function () {
  36454. var serializationObject = _super.prototype.serialize.call(this);
  36455. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36456. return serializationObject;
  36457. };
  36458. return _PrimitiveGeometry;
  36459. }(Geometry));
  36460. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36461. /**
  36462. * Creates a ribbon geometry
  36463. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36464. */
  36465. var RibbonGeometry = /** @class */ (function (_super) {
  36466. __extends(RibbonGeometry, _super);
  36467. /**
  36468. * Creates a ribbon geometry
  36469. * @param id defines the unique ID of the geometry
  36470. * @param scene defines the hosting scene
  36471. * @param pathArray defines the array of paths to use
  36472. * @param closeArray defines if the last path and the first path must be joined
  36473. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36474. * @param offset defines the offset between points
  36475. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36476. * @param mesh defines the hosting mesh (can be null)
  36477. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36478. */
  36479. function RibbonGeometry(id, scene,
  36480. /**
  36481. * Defines the array of paths to use
  36482. */
  36483. pathArray,
  36484. /**
  36485. * Defines if the last and first points of each path in your pathArray must be joined
  36486. */
  36487. closeArray,
  36488. /**
  36489. * Defines if the last and first points of each path in your pathArray must be joined
  36490. */
  36491. closePath,
  36492. /**
  36493. * Defines the offset between points
  36494. */
  36495. offset, canBeRegenerated, mesh,
  36496. /**
  36497. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36498. */
  36499. side) {
  36500. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36501. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36502. _this.pathArray = pathArray;
  36503. _this.closeArray = closeArray;
  36504. _this.closePath = closePath;
  36505. _this.offset = offset;
  36506. _this.side = side;
  36507. return _this;
  36508. }
  36509. /** @ignore */
  36510. RibbonGeometry.prototype._regenerateVertexData = function () {
  36511. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36512. };
  36513. RibbonGeometry.prototype.copy = function (id) {
  36514. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36515. };
  36516. return RibbonGeometry;
  36517. }(_PrimitiveGeometry));
  36518. BABYLON.RibbonGeometry = RibbonGeometry;
  36519. /**
  36520. * Creates a box geometry
  36521. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36522. */
  36523. var BoxGeometry = /** @class */ (function (_super) {
  36524. __extends(BoxGeometry, _super);
  36525. /**
  36526. * Creates a box geometry
  36527. * @param id defines the unique ID of the geometry
  36528. * @param scene defines the hosting scene
  36529. * @param size defines the zise of the box (width, height and depth are the same)
  36530. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36531. * @param mesh defines the hosting mesh (can be null)
  36532. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36533. */
  36534. function BoxGeometry(id, scene,
  36535. /**
  36536. * Defines the zise of the box (width, height and depth are the same)
  36537. */
  36538. size, canBeRegenerated, mesh,
  36539. /**
  36540. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36541. */
  36542. side) {
  36543. if (mesh === void 0) { mesh = null; }
  36544. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36545. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36546. _this.size = size;
  36547. _this.side = side;
  36548. return _this;
  36549. }
  36550. BoxGeometry.prototype._regenerateVertexData = function () {
  36551. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36552. };
  36553. BoxGeometry.prototype.copy = function (id) {
  36554. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36555. };
  36556. BoxGeometry.prototype.serialize = function () {
  36557. var serializationObject = _super.prototype.serialize.call(this);
  36558. serializationObject.size = this.size;
  36559. return serializationObject;
  36560. };
  36561. BoxGeometry.Parse = function (parsedBox, scene) {
  36562. if (scene.getGeometryByID(parsedBox.id)) {
  36563. return null; // null since geometry could be something else than a box...
  36564. }
  36565. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36566. if (BABYLON.Tags) {
  36567. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36568. }
  36569. scene.pushGeometry(box, true);
  36570. return box;
  36571. };
  36572. return BoxGeometry;
  36573. }(_PrimitiveGeometry));
  36574. BABYLON.BoxGeometry = BoxGeometry;
  36575. /**
  36576. * Creates a sphere geometry
  36577. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36578. */
  36579. var SphereGeometry = /** @class */ (function (_super) {
  36580. __extends(SphereGeometry, _super);
  36581. /**
  36582. * Create a new sphere geometry
  36583. * @param id defines the unique ID of the geometry
  36584. * @param scene defines the hosting scene
  36585. * @param segments defines the number of segments to use to create the sphere
  36586. * @param diameter defines the diameter of the sphere
  36587. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36588. * @param mesh defines the hosting mesh (can be null)
  36589. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36590. */
  36591. function SphereGeometry(id, scene,
  36592. /**
  36593. * Defines the number of segments to use to create the sphere
  36594. */
  36595. segments,
  36596. /**
  36597. * Defines the diameter of the sphere
  36598. */
  36599. diameter, canBeRegenerated, mesh,
  36600. /**
  36601. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36602. */
  36603. side) {
  36604. if (mesh === void 0) { mesh = null; }
  36605. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36606. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36607. _this.segments = segments;
  36608. _this.diameter = diameter;
  36609. _this.side = side;
  36610. return _this;
  36611. }
  36612. SphereGeometry.prototype._regenerateVertexData = function () {
  36613. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36614. };
  36615. SphereGeometry.prototype.copy = function (id) {
  36616. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36617. };
  36618. SphereGeometry.prototype.serialize = function () {
  36619. var serializationObject = _super.prototype.serialize.call(this);
  36620. serializationObject.segments = this.segments;
  36621. serializationObject.diameter = this.diameter;
  36622. return serializationObject;
  36623. };
  36624. SphereGeometry.Parse = function (parsedSphere, scene) {
  36625. if (scene.getGeometryByID(parsedSphere.id)) {
  36626. return null; // null since geometry could be something else than a sphere...
  36627. }
  36628. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36629. if (BABYLON.Tags) {
  36630. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36631. }
  36632. scene.pushGeometry(sphere, true);
  36633. return sphere;
  36634. };
  36635. return SphereGeometry;
  36636. }(_PrimitiveGeometry));
  36637. BABYLON.SphereGeometry = SphereGeometry;
  36638. /**
  36639. * Creates a disc geometry
  36640. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36641. */
  36642. var DiscGeometry = /** @class */ (function (_super) {
  36643. __extends(DiscGeometry, _super);
  36644. /**
  36645. * Creates a new disc geometry
  36646. * @param id defines the unique ID of the geometry
  36647. * @param scene defines the hosting scene
  36648. * @param radius defines the radius of the disc
  36649. * @param tessellation defines the tesselation factor to apply to the disc
  36650. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36651. * @param mesh defines the hosting mesh (can be null)
  36652. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36653. */
  36654. function DiscGeometry(id, scene,
  36655. /**
  36656. * Defines the radius of the disc
  36657. */
  36658. radius,
  36659. /**
  36660. * Defines the tesselation factor to apply to the disc
  36661. */
  36662. tessellation, canBeRegenerated, mesh,
  36663. /**
  36664. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36665. */
  36666. side) {
  36667. if (mesh === void 0) { mesh = null; }
  36668. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36669. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36670. _this.radius = radius;
  36671. _this.tessellation = tessellation;
  36672. _this.side = side;
  36673. return _this;
  36674. }
  36675. DiscGeometry.prototype._regenerateVertexData = function () {
  36676. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36677. };
  36678. DiscGeometry.prototype.copy = function (id) {
  36679. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36680. };
  36681. return DiscGeometry;
  36682. }(_PrimitiveGeometry));
  36683. BABYLON.DiscGeometry = DiscGeometry;
  36684. /**
  36685. * Creates a new cylinder geometry
  36686. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36687. */
  36688. var CylinderGeometry = /** @class */ (function (_super) {
  36689. __extends(CylinderGeometry, _super);
  36690. /**
  36691. * Creates a new cylinder geometry
  36692. * @param id defines the unique ID of the geometry
  36693. * @param scene defines the hosting scene
  36694. * @param height defines the height of the cylinder
  36695. * @param diameterTop defines the diameter of the cylinder's top cap
  36696. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36697. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36698. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36699. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36700. * @param mesh defines the hosting mesh (can be null)
  36701. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36702. */
  36703. function CylinderGeometry(id, scene,
  36704. /**
  36705. * Defines the height of the cylinder
  36706. */
  36707. height,
  36708. /**
  36709. * Defines the diameter of the cylinder's top cap
  36710. */
  36711. diameterTop,
  36712. /**
  36713. * Defines the diameter of the cylinder's bottom cap
  36714. */
  36715. diameterBottom,
  36716. /**
  36717. * Defines the tessellation factor to apply to the cylinder
  36718. */
  36719. tessellation,
  36720. /**
  36721. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36722. */
  36723. subdivisions, canBeRegenerated, mesh,
  36724. /**
  36725. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36726. */
  36727. side) {
  36728. if (subdivisions === void 0) { subdivisions = 1; }
  36729. if (mesh === void 0) { mesh = null; }
  36730. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36731. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36732. _this.height = height;
  36733. _this.diameterTop = diameterTop;
  36734. _this.diameterBottom = diameterBottom;
  36735. _this.tessellation = tessellation;
  36736. _this.subdivisions = subdivisions;
  36737. _this.side = side;
  36738. return _this;
  36739. }
  36740. CylinderGeometry.prototype._regenerateVertexData = function () {
  36741. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36742. };
  36743. CylinderGeometry.prototype.copy = function (id) {
  36744. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36745. };
  36746. CylinderGeometry.prototype.serialize = function () {
  36747. var serializationObject = _super.prototype.serialize.call(this);
  36748. serializationObject.height = this.height;
  36749. serializationObject.diameterTop = this.diameterTop;
  36750. serializationObject.diameterBottom = this.diameterBottom;
  36751. serializationObject.tessellation = this.tessellation;
  36752. return serializationObject;
  36753. };
  36754. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36755. if (scene.getGeometryByID(parsedCylinder.id)) {
  36756. return null; // null since geometry could be something else than a cylinder...
  36757. }
  36758. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36759. if (BABYLON.Tags) {
  36760. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36761. }
  36762. scene.pushGeometry(cylinder, true);
  36763. return cylinder;
  36764. };
  36765. return CylinderGeometry;
  36766. }(_PrimitiveGeometry));
  36767. BABYLON.CylinderGeometry = CylinderGeometry;
  36768. /**
  36769. * Creates a new torus geometry
  36770. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36771. */
  36772. var TorusGeometry = /** @class */ (function (_super) {
  36773. __extends(TorusGeometry, _super);
  36774. /**
  36775. * Creates a new torus geometry
  36776. * @param id defines the unique ID of the geometry
  36777. * @param scene defines the hosting scene
  36778. * @param diameter defines the diameter of the torus
  36779. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36780. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36781. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36782. * @param mesh defines the hosting mesh (can be null)
  36783. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36784. */
  36785. function TorusGeometry(id, scene,
  36786. /**
  36787. * Defines the diameter of the torus
  36788. */
  36789. diameter,
  36790. /**
  36791. * Defines the thickness of the torus (ie. internal diameter)
  36792. */
  36793. thickness,
  36794. /**
  36795. * Defines the tesselation factor to apply to the torus
  36796. */
  36797. tessellation, canBeRegenerated, mesh,
  36798. /**
  36799. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36800. */
  36801. side) {
  36802. if (mesh === void 0) { mesh = null; }
  36803. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36804. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36805. _this.diameter = diameter;
  36806. _this.thickness = thickness;
  36807. _this.tessellation = tessellation;
  36808. _this.side = side;
  36809. return _this;
  36810. }
  36811. TorusGeometry.prototype._regenerateVertexData = function () {
  36812. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36813. };
  36814. TorusGeometry.prototype.copy = function (id) {
  36815. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36816. };
  36817. TorusGeometry.prototype.serialize = function () {
  36818. var serializationObject = _super.prototype.serialize.call(this);
  36819. serializationObject.diameter = this.diameter;
  36820. serializationObject.thickness = this.thickness;
  36821. serializationObject.tessellation = this.tessellation;
  36822. return serializationObject;
  36823. };
  36824. TorusGeometry.Parse = function (parsedTorus, scene) {
  36825. if (scene.getGeometryByID(parsedTorus.id)) {
  36826. return null; // null since geometry could be something else than a torus...
  36827. }
  36828. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36829. if (BABYLON.Tags) {
  36830. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36831. }
  36832. scene.pushGeometry(torus, true);
  36833. return torus;
  36834. };
  36835. return TorusGeometry;
  36836. }(_PrimitiveGeometry));
  36837. BABYLON.TorusGeometry = TorusGeometry;
  36838. /**
  36839. * Creates a new ground geometry
  36840. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36841. */
  36842. var GroundGeometry = /** @class */ (function (_super) {
  36843. __extends(GroundGeometry, _super);
  36844. /**
  36845. * Creates a new ground geometry
  36846. * @param id defines the unique ID of the geometry
  36847. * @param scene defines the hosting scene
  36848. * @param width defines the width of the ground
  36849. * @param height defines the height of the ground
  36850. * @param subdivisions defines the subdivisions to apply to the ground
  36851. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36852. * @param mesh defines the hosting mesh (can be null)
  36853. */
  36854. function GroundGeometry(id, scene,
  36855. /**
  36856. * Defines the width of the ground
  36857. */
  36858. width,
  36859. /**
  36860. * Defines the height of the ground
  36861. */
  36862. height,
  36863. /**
  36864. * Defines the subdivisions to apply to the ground
  36865. */
  36866. subdivisions, canBeRegenerated, mesh) {
  36867. if (mesh === void 0) { mesh = null; }
  36868. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36869. _this.width = width;
  36870. _this.height = height;
  36871. _this.subdivisions = subdivisions;
  36872. return _this;
  36873. }
  36874. GroundGeometry.prototype._regenerateVertexData = function () {
  36875. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36876. };
  36877. GroundGeometry.prototype.copy = function (id) {
  36878. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36879. };
  36880. GroundGeometry.prototype.serialize = function () {
  36881. var serializationObject = _super.prototype.serialize.call(this);
  36882. serializationObject.width = this.width;
  36883. serializationObject.height = this.height;
  36884. serializationObject.subdivisions = this.subdivisions;
  36885. return serializationObject;
  36886. };
  36887. GroundGeometry.Parse = function (parsedGround, scene) {
  36888. if (scene.getGeometryByID(parsedGround.id)) {
  36889. return null; // null since geometry could be something else than a ground...
  36890. }
  36891. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36892. if (BABYLON.Tags) {
  36893. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36894. }
  36895. scene.pushGeometry(ground, true);
  36896. return ground;
  36897. };
  36898. return GroundGeometry;
  36899. }(_PrimitiveGeometry));
  36900. BABYLON.GroundGeometry = GroundGeometry;
  36901. /**
  36902. * Creates a tiled ground geometry
  36903. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36904. */
  36905. var TiledGroundGeometry = /** @class */ (function (_super) {
  36906. __extends(TiledGroundGeometry, _super);
  36907. /**
  36908. * Creates a tiled ground geometry
  36909. * @param id defines the unique ID of the geometry
  36910. * @param scene defines the hosting scene
  36911. * @param xmin defines the minimum value on X axis
  36912. * @param zmin defines the minimum value on Z axis
  36913. * @param xmax defines the maximum value on X axis
  36914. * @param zmax defines the maximum value on Z axis
  36915. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36916. * @param precision defines the precision to use when computing the tiles
  36917. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36918. * @param mesh defines the hosting mesh (can be null)
  36919. */
  36920. function TiledGroundGeometry(id, scene,
  36921. /**
  36922. * Defines the minimum value on X axis
  36923. */
  36924. xmin,
  36925. /**
  36926. * Defines the minimum value on Z axis
  36927. */
  36928. zmin,
  36929. /**
  36930. * Defines the maximum value on X axis
  36931. */
  36932. xmax,
  36933. /**
  36934. * Defines the maximum value on Z axis
  36935. */
  36936. zmax,
  36937. /**
  36938. * Defines the subdivisions to apply to the ground
  36939. */
  36940. subdivisions,
  36941. /**
  36942. * Defines the precision to use when computing the tiles
  36943. */
  36944. precision, canBeRegenerated, mesh) {
  36945. if (mesh === void 0) { mesh = null; }
  36946. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36947. _this.xmin = xmin;
  36948. _this.zmin = zmin;
  36949. _this.xmax = xmax;
  36950. _this.zmax = zmax;
  36951. _this.subdivisions = subdivisions;
  36952. _this.precision = precision;
  36953. return _this;
  36954. }
  36955. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36956. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36957. };
  36958. TiledGroundGeometry.prototype.copy = function (id) {
  36959. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36960. };
  36961. return TiledGroundGeometry;
  36962. }(_PrimitiveGeometry));
  36963. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36964. /**
  36965. * Creates a plane geometry
  36966. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36967. */
  36968. var PlaneGeometry = /** @class */ (function (_super) {
  36969. __extends(PlaneGeometry, _super);
  36970. /**
  36971. * Creates a plane geometry
  36972. * @param id defines the unique ID of the geometry
  36973. * @param scene defines the hosting scene
  36974. * @param size defines the size of the plane (width === height)
  36975. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36976. * @param mesh defines the hosting mesh (can be null)
  36977. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36978. */
  36979. function PlaneGeometry(id, scene,
  36980. /**
  36981. * Defines the size of the plane (width === height)
  36982. */
  36983. size, canBeRegenerated, mesh,
  36984. /**
  36985. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36986. */
  36987. side) {
  36988. if (mesh === void 0) { mesh = null; }
  36989. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36990. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36991. _this.size = size;
  36992. _this.side = side;
  36993. return _this;
  36994. }
  36995. PlaneGeometry.prototype._regenerateVertexData = function () {
  36996. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36997. };
  36998. PlaneGeometry.prototype.copy = function (id) {
  36999. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37000. };
  37001. PlaneGeometry.prototype.serialize = function () {
  37002. var serializationObject = _super.prototype.serialize.call(this);
  37003. serializationObject.size = this.size;
  37004. return serializationObject;
  37005. };
  37006. PlaneGeometry.Parse = function (parsedPlane, scene) {
  37007. if (scene.getGeometryByID(parsedPlane.id)) {
  37008. return null; // null since geometry could be something else than a ground...
  37009. }
  37010. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37011. if (BABYLON.Tags) {
  37012. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37013. }
  37014. scene.pushGeometry(plane, true);
  37015. return plane;
  37016. };
  37017. return PlaneGeometry;
  37018. }(_PrimitiveGeometry));
  37019. BABYLON.PlaneGeometry = PlaneGeometry;
  37020. /**
  37021. * Creates a torus knot geometry
  37022. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  37023. */
  37024. var TorusKnotGeometry = /** @class */ (function (_super) {
  37025. __extends(TorusKnotGeometry, _super);
  37026. /**
  37027. * Creates a torus knot geometry
  37028. * @param id defines the unique ID of the geometry
  37029. * @param scene defines the hosting scene
  37030. * @param radius defines the radius of the torus knot
  37031. * @param tube defines the thickness of the torus knot tube
  37032. * @param radialSegments defines the number of radial segments
  37033. * @param tubularSegments defines the number of tubular segments
  37034. * @param p defines the first number of windings
  37035. * @param q defines the second number of windings
  37036. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37037. * @param mesh defines the hosting mesh (can be null)
  37038. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37039. */
  37040. function TorusKnotGeometry(id, scene,
  37041. /**
  37042. * Defines the radius of the torus knot
  37043. */
  37044. radius,
  37045. /**
  37046. * Defines the thickness of the torus knot tube
  37047. */
  37048. tube,
  37049. /**
  37050. * Defines the number of radial segments
  37051. */
  37052. radialSegments,
  37053. /**
  37054. * Defines the number of tubular segments
  37055. */
  37056. tubularSegments,
  37057. /**
  37058. * Defines the first number of windings
  37059. */
  37060. p,
  37061. /**
  37062. * Defines the second number of windings
  37063. */
  37064. q, canBeRegenerated, mesh,
  37065. /**
  37066. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37067. */
  37068. side) {
  37069. if (mesh === void 0) { mesh = null; }
  37070. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37071. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37072. _this.radius = radius;
  37073. _this.tube = tube;
  37074. _this.radialSegments = radialSegments;
  37075. _this.tubularSegments = tubularSegments;
  37076. _this.p = p;
  37077. _this.q = q;
  37078. _this.side = side;
  37079. return _this;
  37080. }
  37081. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37082. 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 });
  37083. };
  37084. TorusKnotGeometry.prototype.copy = function (id) {
  37085. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37086. };
  37087. TorusKnotGeometry.prototype.serialize = function () {
  37088. var serializationObject = _super.prototype.serialize.call(this);
  37089. serializationObject.radius = this.radius;
  37090. serializationObject.tube = this.tube;
  37091. serializationObject.radialSegments = this.radialSegments;
  37092. serializationObject.tubularSegments = this.tubularSegments;
  37093. serializationObject.p = this.p;
  37094. serializationObject.q = this.q;
  37095. return serializationObject;
  37096. };
  37097. ;
  37098. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37099. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37100. return null; // null since geometry could be something else than a ground...
  37101. }
  37102. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37103. if (BABYLON.Tags) {
  37104. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37105. }
  37106. scene.pushGeometry(torusKnot, true);
  37107. return torusKnot;
  37108. };
  37109. return TorusKnotGeometry;
  37110. }(_PrimitiveGeometry));
  37111. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37112. //}
  37113. })(BABYLON || (BABYLON = {}));
  37114. //# sourceMappingURL=babylon.geometry.js.map
  37115. "use strict";
  37116. var BABYLON;
  37117. (function (BABYLON) {
  37118. /**
  37119. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37120. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37121. */
  37122. var PostProcessManager = /** @class */ (function () {
  37123. /**
  37124. * Creates a new instance PostProcess
  37125. * @param scene The scene that the post process is associated with.
  37126. */
  37127. function PostProcessManager(scene) {
  37128. this._vertexBuffers = {};
  37129. this._scene = scene;
  37130. }
  37131. PostProcessManager.prototype._prepareBuffers = function () {
  37132. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37133. return;
  37134. }
  37135. // VBO
  37136. var vertices = [];
  37137. vertices.push(1, 1);
  37138. vertices.push(-1, 1);
  37139. vertices.push(-1, -1);
  37140. vertices.push(1, -1);
  37141. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37142. this._buildIndexBuffer();
  37143. };
  37144. PostProcessManager.prototype._buildIndexBuffer = function () {
  37145. // Indices
  37146. var indices = [];
  37147. indices.push(0);
  37148. indices.push(1);
  37149. indices.push(2);
  37150. indices.push(0);
  37151. indices.push(2);
  37152. indices.push(3);
  37153. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37154. };
  37155. /**
  37156. * Rebuilds the vertex buffers of the manager.
  37157. */
  37158. PostProcessManager.prototype._rebuild = function () {
  37159. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37160. if (!vb) {
  37161. return;
  37162. }
  37163. vb._rebuild();
  37164. this._buildIndexBuffer();
  37165. };
  37166. // Methods
  37167. /**
  37168. * Prepares a frame to be run through a post process.
  37169. * @param sourceTexture The input texture to the post procesess. (default: null)
  37170. * @param postProcesses An array of post processes to be run. (default: null)
  37171. * @returns True if the post processes were able to be run.
  37172. */
  37173. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37174. if (sourceTexture === void 0) { sourceTexture = null; }
  37175. if (postProcesses === void 0) { postProcesses = null; }
  37176. var camera = this._scene.activeCamera;
  37177. if (!camera) {
  37178. return false;
  37179. }
  37180. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37181. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37182. return false;
  37183. }
  37184. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37185. return true;
  37186. };
  37187. /**
  37188. * Manually render a set of post processes to a texture.
  37189. * @param postProcesses An array of post processes to be run.
  37190. * @param targetTexture The target texture to render to.
  37191. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37192. */
  37193. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37194. if (targetTexture === void 0) { targetTexture = null; }
  37195. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37196. var engine = this._scene.getEngine();
  37197. for (var index = 0; index < postProcesses.length; index++) {
  37198. if (index < postProcesses.length - 1) {
  37199. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37200. }
  37201. else {
  37202. if (targetTexture) {
  37203. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37204. }
  37205. else {
  37206. engine.restoreDefaultFramebuffer();
  37207. }
  37208. }
  37209. var pp = postProcesses[index];
  37210. var effect = pp.apply();
  37211. if (effect) {
  37212. pp.onBeforeRenderObservable.notifyObservers(effect);
  37213. // VBOs
  37214. this._prepareBuffers();
  37215. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37216. // Draw order
  37217. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37218. pp.onAfterRenderObservable.notifyObservers(effect);
  37219. }
  37220. }
  37221. // Restore depth buffer
  37222. engine.setDepthBuffer(true);
  37223. engine.setDepthWrite(true);
  37224. };
  37225. /**
  37226. * Finalize the result of the output of the postprocesses.
  37227. * @param doNotPresent If true the result will not be displayed to the screen.
  37228. * @param targetTexture The target texture to render to.
  37229. * @param faceIndex The index of the face to bind the target texture to.
  37230. * @param postProcesses The array of post processes to render.
  37231. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37232. */
  37233. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37234. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37235. var camera = this._scene.activeCamera;
  37236. if (!camera) {
  37237. return;
  37238. }
  37239. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37240. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37241. return;
  37242. }
  37243. var engine = this._scene.getEngine();
  37244. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37245. var pp = postProcesses[index];
  37246. if (index < len - 1) {
  37247. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37248. }
  37249. else {
  37250. if (targetTexture) {
  37251. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37252. }
  37253. else {
  37254. engine.restoreDefaultFramebuffer();
  37255. }
  37256. }
  37257. if (doNotPresent) {
  37258. break;
  37259. }
  37260. var effect = pp.apply();
  37261. if (effect) {
  37262. pp.onBeforeRenderObservable.notifyObservers(effect);
  37263. // VBOs
  37264. this._prepareBuffers();
  37265. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37266. // Draw order
  37267. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37268. pp.onAfterRenderObservable.notifyObservers(effect);
  37269. }
  37270. }
  37271. // Restore states
  37272. engine.setDepthBuffer(true);
  37273. engine.setDepthWrite(true);
  37274. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37275. };
  37276. /**
  37277. * Disposes of the post process manager.
  37278. */
  37279. PostProcessManager.prototype.dispose = function () {
  37280. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37281. if (buffer) {
  37282. buffer.dispose();
  37283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37284. }
  37285. if (this._indexBuffer) {
  37286. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37287. this._indexBuffer = null;
  37288. }
  37289. };
  37290. return PostProcessManager;
  37291. }());
  37292. BABYLON.PostProcessManager = PostProcessManager;
  37293. })(BABYLON || (BABYLON = {}));
  37294. //# sourceMappingURL=babylon.postProcessManager.js.map
  37295. "use strict";
  37296. var BABYLON;
  37297. (function (BABYLON) {
  37298. /**
  37299. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37300. */
  37301. var PerformanceMonitor = /** @class */ (function () {
  37302. /**
  37303. * constructor
  37304. * @param frameSampleSize The number of samples required to saturate the sliding window
  37305. */
  37306. function PerformanceMonitor(frameSampleSize) {
  37307. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37308. this._enabled = true;
  37309. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37310. }
  37311. /**
  37312. * Samples current frame
  37313. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37314. */
  37315. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37316. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37317. if (!this._enabled)
  37318. return;
  37319. if (this._lastFrameTimeMs != null) {
  37320. var dt = timeMs - this._lastFrameTimeMs;
  37321. this._rollingFrameTime.add(dt);
  37322. }
  37323. this._lastFrameTimeMs = timeMs;
  37324. };
  37325. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37326. /**
  37327. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37328. * @return Average frame time in milliseconds
  37329. */
  37330. get: function () {
  37331. return this._rollingFrameTime.average;
  37332. },
  37333. enumerable: true,
  37334. configurable: true
  37335. });
  37336. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37337. /**
  37338. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37339. * @return Frame time variance in milliseconds squared
  37340. */
  37341. get: function () {
  37342. return this._rollingFrameTime.variance;
  37343. },
  37344. enumerable: true,
  37345. configurable: true
  37346. });
  37347. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37348. /**
  37349. * Returns the frame time of the most recent frame
  37350. * @return Frame time in milliseconds
  37351. */
  37352. get: function () {
  37353. return this._rollingFrameTime.history(0);
  37354. },
  37355. enumerable: true,
  37356. configurable: true
  37357. });
  37358. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37359. /**
  37360. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37361. * @return Framerate in frames per second
  37362. */
  37363. get: function () {
  37364. return 1000.0 / this._rollingFrameTime.average;
  37365. },
  37366. enumerable: true,
  37367. configurable: true
  37368. });
  37369. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37370. /**
  37371. * Returns the average framerate in frames per second using the most recent frame time
  37372. * @return Framerate in frames per second
  37373. */
  37374. get: function () {
  37375. var history = this._rollingFrameTime.history(0);
  37376. if (history === 0) {
  37377. return 0;
  37378. }
  37379. return 1000.0 / history;
  37380. },
  37381. enumerable: true,
  37382. configurable: true
  37383. });
  37384. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37385. /**
  37386. * Returns true if enough samples have been taken to completely fill the sliding window
  37387. * @return true if saturated
  37388. */
  37389. get: function () {
  37390. return this._rollingFrameTime.isSaturated();
  37391. },
  37392. enumerable: true,
  37393. configurable: true
  37394. });
  37395. /**
  37396. * Enables contributions to the sliding window sample set
  37397. */
  37398. PerformanceMonitor.prototype.enable = function () {
  37399. this._enabled = true;
  37400. };
  37401. /**
  37402. * Disables contributions to the sliding window sample set
  37403. * Samples will not be interpolated over the disabled period
  37404. */
  37405. PerformanceMonitor.prototype.disable = function () {
  37406. this._enabled = false;
  37407. //clear last sample to avoid interpolating over the disabled period when next enabled
  37408. this._lastFrameTimeMs = null;
  37409. };
  37410. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37411. /**
  37412. * Returns true if sampling is enabled
  37413. * @return true if enabled
  37414. */
  37415. get: function () {
  37416. return this._enabled;
  37417. },
  37418. enumerable: true,
  37419. configurable: true
  37420. });
  37421. /**
  37422. * Resets performance monitor
  37423. */
  37424. PerformanceMonitor.prototype.reset = function () {
  37425. //clear last sample to avoid interpolating over the disabled period when next enabled
  37426. this._lastFrameTimeMs = null;
  37427. //wipe record
  37428. this._rollingFrameTime.reset();
  37429. };
  37430. return PerformanceMonitor;
  37431. }());
  37432. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37433. /**
  37434. * RollingAverage
  37435. *
  37436. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37437. */
  37438. var RollingAverage = /** @class */ (function () {
  37439. /**
  37440. * constructor
  37441. * @param length The number of samples required to saturate the sliding window
  37442. */
  37443. function RollingAverage(length) {
  37444. this._samples = new Array(length);
  37445. this.reset();
  37446. }
  37447. /**
  37448. * Adds a sample to the sample set
  37449. * @param v The sample value
  37450. */
  37451. RollingAverage.prototype.add = function (v) {
  37452. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37453. var delta;
  37454. //we need to check if we've already wrapped round
  37455. if (this.isSaturated()) {
  37456. //remove bottom of stack from mean
  37457. var bottomValue = this._samples[this._pos];
  37458. delta = bottomValue - this.average;
  37459. this.average -= delta / (this._sampleCount - 1);
  37460. this._m2 -= delta * (bottomValue - this.average);
  37461. }
  37462. else {
  37463. this._sampleCount++;
  37464. }
  37465. //add new value to mean
  37466. delta = v - this.average;
  37467. this.average += delta / (this._sampleCount);
  37468. this._m2 += delta * (v - this.average);
  37469. //set the new variance
  37470. this.variance = this._m2 / (this._sampleCount - 1);
  37471. this._samples[this._pos] = v;
  37472. this._pos++;
  37473. this._pos %= this._samples.length; //positive wrap around
  37474. };
  37475. /**
  37476. * Returns previously added values or null if outside of history or outside the sliding window domain
  37477. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37478. * @return Value previously recorded with add() or null if outside of range
  37479. */
  37480. RollingAverage.prototype.history = function (i) {
  37481. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37482. return 0;
  37483. }
  37484. var i0 = this._wrapPosition(this._pos - 1.0);
  37485. return this._samples[this._wrapPosition(i0 - i)];
  37486. };
  37487. /**
  37488. * Returns true if enough samples have been taken to completely fill the sliding window
  37489. * @return true if sample-set saturated
  37490. */
  37491. RollingAverage.prototype.isSaturated = function () {
  37492. return this._sampleCount >= this._samples.length;
  37493. };
  37494. /**
  37495. * Resets the rolling average (equivalent to 0 samples taken so far)
  37496. */
  37497. RollingAverage.prototype.reset = function () {
  37498. this.average = 0;
  37499. this.variance = 0;
  37500. this._sampleCount = 0;
  37501. this._pos = 0;
  37502. this._m2 = 0;
  37503. };
  37504. /**
  37505. * Wraps a value around the sample range boundaries
  37506. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37507. * @return Wrapped position in sample range
  37508. */
  37509. RollingAverage.prototype._wrapPosition = function (i) {
  37510. var max = this._samples.length;
  37511. return ((i % max) + max) % max;
  37512. };
  37513. return RollingAverage;
  37514. }());
  37515. BABYLON.RollingAverage = RollingAverage;
  37516. })(BABYLON || (BABYLON = {}));
  37517. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37518. "use strict";
  37519. var BABYLON;
  37520. (function (BABYLON) {
  37521. /**
  37522. * This groups together the common properties used for image processing either in direct forward pass
  37523. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37524. * or not.
  37525. */
  37526. var ImageProcessingConfiguration = /** @class */ (function () {
  37527. function ImageProcessingConfiguration() {
  37528. /**
  37529. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37530. */
  37531. this.colorCurves = new BABYLON.ColorCurves();
  37532. this._colorCurvesEnabled = false;
  37533. this._colorGradingEnabled = false;
  37534. this._colorGradingWithGreenDepth = true;
  37535. this._colorGradingBGR = true;
  37536. this._exposure = 1.0;
  37537. this._toneMappingEnabled = false;
  37538. this._contrast = 1.0;
  37539. /**
  37540. * Vignette stretch size.
  37541. */
  37542. this.vignetteStretch = 0;
  37543. /**
  37544. * Vignette centre X Offset.
  37545. */
  37546. this.vignetteCentreX = 0;
  37547. /**
  37548. * Vignette centre Y Offset.
  37549. */
  37550. this.vignetteCentreY = 0;
  37551. /**
  37552. * Vignette weight or intensity of the vignette effect.
  37553. */
  37554. this.vignetteWeight = 1.5;
  37555. /**
  37556. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37557. * if vignetteEnabled is set to true.
  37558. */
  37559. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37560. /**
  37561. * Camera field of view used by the Vignette effect.
  37562. */
  37563. this.vignetteCameraFov = 0.5;
  37564. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37565. this._vignetteEnabled = false;
  37566. this._applyByPostProcess = false;
  37567. this._isEnabled = true;
  37568. /**
  37569. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37570. */
  37571. this.onUpdateParameters = new BABYLON.Observable();
  37572. }
  37573. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37574. /**
  37575. * Gets wether the color curves effect is enabled.
  37576. */
  37577. get: function () {
  37578. return this._colorCurvesEnabled;
  37579. },
  37580. /**
  37581. * Sets wether the color curves effect is enabled.
  37582. */
  37583. set: function (value) {
  37584. if (this._colorCurvesEnabled === value) {
  37585. return;
  37586. }
  37587. this._colorCurvesEnabled = value;
  37588. this._updateParameters();
  37589. },
  37590. enumerable: true,
  37591. configurable: true
  37592. });
  37593. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37594. /**
  37595. * Gets wether the color grading effect is enabled.
  37596. */
  37597. get: function () {
  37598. return this._colorGradingEnabled;
  37599. },
  37600. /**
  37601. * Sets wether the color grading effect is enabled.
  37602. */
  37603. set: function (value) {
  37604. if (this._colorGradingEnabled === value) {
  37605. return;
  37606. }
  37607. this._colorGradingEnabled = value;
  37608. this._updateParameters();
  37609. },
  37610. enumerable: true,
  37611. configurable: true
  37612. });
  37613. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37614. /**
  37615. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37616. */
  37617. get: function () {
  37618. return this._colorGradingWithGreenDepth;
  37619. },
  37620. /**
  37621. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37622. */
  37623. set: function (value) {
  37624. if (this._colorGradingWithGreenDepth === value) {
  37625. return;
  37626. }
  37627. this._colorGradingWithGreenDepth = value;
  37628. this._updateParameters();
  37629. },
  37630. enumerable: true,
  37631. configurable: true
  37632. });
  37633. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37634. /**
  37635. * Gets wether the color grading texture contains BGR values.
  37636. */
  37637. get: function () {
  37638. return this._colorGradingBGR;
  37639. },
  37640. /**
  37641. * Sets wether the color grading texture contains BGR values.
  37642. */
  37643. set: function (value) {
  37644. if (this._colorGradingBGR === value) {
  37645. return;
  37646. }
  37647. this._colorGradingBGR = value;
  37648. this._updateParameters();
  37649. },
  37650. enumerable: true,
  37651. configurable: true
  37652. });
  37653. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37654. /**
  37655. * Gets the Exposure used in the effect.
  37656. */
  37657. get: function () {
  37658. return this._exposure;
  37659. },
  37660. /**
  37661. * Sets the Exposure used in the effect.
  37662. */
  37663. set: function (value) {
  37664. if (this._exposure === value) {
  37665. return;
  37666. }
  37667. this._exposure = value;
  37668. this._updateParameters();
  37669. },
  37670. enumerable: true,
  37671. configurable: true
  37672. });
  37673. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37674. /**
  37675. * Gets wether the tone mapping effect is enabled.
  37676. */
  37677. get: function () {
  37678. return this._toneMappingEnabled;
  37679. },
  37680. /**
  37681. * Sets wether the tone mapping effect is enabled.
  37682. */
  37683. set: function (value) {
  37684. if (this._toneMappingEnabled === value) {
  37685. return;
  37686. }
  37687. this._toneMappingEnabled = value;
  37688. this._updateParameters();
  37689. },
  37690. enumerable: true,
  37691. configurable: true
  37692. });
  37693. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37694. /**
  37695. * Gets the contrast used in the effect.
  37696. */
  37697. get: function () {
  37698. return this._contrast;
  37699. },
  37700. /**
  37701. * Sets the contrast used in the effect.
  37702. */
  37703. set: function (value) {
  37704. if (this._contrast === value) {
  37705. return;
  37706. }
  37707. this._contrast = value;
  37708. this._updateParameters();
  37709. },
  37710. enumerable: true,
  37711. configurable: true
  37712. });
  37713. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37714. /**
  37715. * Gets the vignette blend mode allowing different kind of effect.
  37716. */
  37717. get: function () {
  37718. return this._vignetteBlendMode;
  37719. },
  37720. /**
  37721. * Sets the vignette blend mode allowing different kind of effect.
  37722. */
  37723. set: function (value) {
  37724. if (this._vignetteBlendMode === value) {
  37725. return;
  37726. }
  37727. this._vignetteBlendMode = value;
  37728. this._updateParameters();
  37729. },
  37730. enumerable: true,
  37731. configurable: true
  37732. });
  37733. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37734. /**
  37735. * Gets wether the vignette effect is enabled.
  37736. */
  37737. get: function () {
  37738. return this._vignetteEnabled;
  37739. },
  37740. /**
  37741. * Sets wether the vignette effect is enabled.
  37742. */
  37743. set: function (value) {
  37744. if (this._vignetteEnabled === value) {
  37745. return;
  37746. }
  37747. this._vignetteEnabled = value;
  37748. this._updateParameters();
  37749. },
  37750. enumerable: true,
  37751. configurable: true
  37752. });
  37753. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37754. /**
  37755. * Gets wether the image processing is applied through a post process or not.
  37756. */
  37757. get: function () {
  37758. return this._applyByPostProcess;
  37759. },
  37760. /**
  37761. * Sets wether the image processing is applied through a post process or not.
  37762. */
  37763. set: function (value) {
  37764. if (this._applyByPostProcess === value) {
  37765. return;
  37766. }
  37767. this._applyByPostProcess = value;
  37768. this._updateParameters();
  37769. },
  37770. enumerable: true,
  37771. configurable: true
  37772. });
  37773. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37774. /**
  37775. * Gets wether the image processing is enabled or not.
  37776. */
  37777. get: function () {
  37778. return this._isEnabled;
  37779. },
  37780. /**
  37781. * Sets wether the image processing is enabled or not.
  37782. */
  37783. set: function (value) {
  37784. if (this._isEnabled === value) {
  37785. return;
  37786. }
  37787. this._isEnabled = value;
  37788. this._updateParameters();
  37789. },
  37790. enumerable: true,
  37791. configurable: true
  37792. });
  37793. /**
  37794. * Method called each time the image processing information changes requires to recompile the effect.
  37795. */
  37796. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37797. this.onUpdateParameters.notifyObservers(this);
  37798. };
  37799. ImageProcessingConfiguration.prototype.getClassName = function () {
  37800. return "ImageProcessingConfiguration";
  37801. };
  37802. /**
  37803. * Prepare the list of uniforms associated with the Image Processing effects.
  37804. * @param uniformsList The list of uniforms used in the effect
  37805. * @param defines the list of defines currently in use
  37806. */
  37807. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37808. if (defines.EXPOSURE) {
  37809. uniforms.push("exposureLinear");
  37810. }
  37811. if (defines.CONTRAST) {
  37812. uniforms.push("contrast");
  37813. }
  37814. if (defines.COLORGRADING) {
  37815. uniforms.push("colorTransformSettings");
  37816. }
  37817. if (defines.VIGNETTE) {
  37818. uniforms.push("vInverseScreenSize");
  37819. uniforms.push("vignetteSettings1");
  37820. uniforms.push("vignetteSettings2");
  37821. }
  37822. if (defines.COLORCURVES) {
  37823. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37824. }
  37825. };
  37826. /**
  37827. * Prepare the list of samplers associated with the Image Processing effects.
  37828. * @param uniformsList The list of uniforms used in the effect
  37829. * @param defines the list of defines currently in use
  37830. */
  37831. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37832. if (defines.COLORGRADING) {
  37833. samplersList.push("txColorTransform");
  37834. }
  37835. };
  37836. /**
  37837. * Prepare the list of defines associated to the shader.
  37838. * @param defines the list of defines to complete
  37839. */
  37840. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37841. if (forPostProcess === void 0) { forPostProcess = false; }
  37842. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37843. defines.VIGNETTE = false;
  37844. defines.TONEMAPPING = false;
  37845. defines.CONTRAST = false;
  37846. defines.EXPOSURE = false;
  37847. defines.COLORCURVES = false;
  37848. defines.COLORGRADING = false;
  37849. defines.COLORGRADING3D = false;
  37850. defines.IMAGEPROCESSING = false;
  37851. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37852. return;
  37853. }
  37854. defines.VIGNETTE = this.vignetteEnabled;
  37855. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37856. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37857. defines.TONEMAPPING = this.toneMappingEnabled;
  37858. defines.CONTRAST = (this.contrast !== 1.0);
  37859. defines.EXPOSURE = (this.exposure !== 1.0);
  37860. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37861. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37862. if (defines.COLORGRADING) {
  37863. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37864. }
  37865. else {
  37866. defines.COLORGRADING3D = false;
  37867. }
  37868. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37869. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37870. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37871. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37872. };
  37873. /**
  37874. * Returns true if all the image processing information are ready.
  37875. */
  37876. ImageProcessingConfiguration.prototype.isReady = function () {
  37877. // Color Grading texure can not be none blocking.
  37878. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37879. };
  37880. /**
  37881. * Binds the image processing to the shader.
  37882. * @param effect The effect to bind to
  37883. */
  37884. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37885. if (aspectRatio === void 0) { aspectRatio = 1; }
  37886. // Color Curves
  37887. if (this._colorCurvesEnabled && this.colorCurves) {
  37888. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37889. }
  37890. // Vignette
  37891. if (this._vignetteEnabled) {
  37892. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37893. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37894. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37895. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37896. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37897. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37898. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37899. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37900. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37901. var vignettePower = -2.0 * this.vignetteWeight;
  37902. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37903. }
  37904. // Exposure
  37905. effect.setFloat("exposureLinear", this.exposure);
  37906. // Contrast
  37907. effect.setFloat("contrast", this.contrast);
  37908. // Color transform settings
  37909. if (this.colorGradingTexture) {
  37910. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37911. var textureSize = this.colorGradingTexture.getSize().height;
  37912. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37913. 0.5 / textureSize, // textureOffset
  37914. textureSize, // textureSize
  37915. this.colorGradingTexture.level // weight
  37916. );
  37917. }
  37918. };
  37919. /**
  37920. * Clones the current image processing instance.
  37921. * @return The cloned image processing
  37922. */
  37923. ImageProcessingConfiguration.prototype.clone = function () {
  37924. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37925. };
  37926. /**
  37927. * Serializes the current image processing instance to a json representation.
  37928. * @return a JSON representation
  37929. */
  37930. ImageProcessingConfiguration.prototype.serialize = function () {
  37931. return BABYLON.SerializationHelper.Serialize(this);
  37932. };
  37933. /**
  37934. * Parses the image processing from a json representation.
  37935. * @param source the JSON source to parse
  37936. * @return The parsed image processing
  37937. */
  37938. ImageProcessingConfiguration.Parse = function (source) {
  37939. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37940. };
  37941. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37942. /**
  37943. * Used to apply the vignette as a mix with the pixel color.
  37944. */
  37945. get: function () {
  37946. return this._VIGNETTEMODE_MULTIPLY;
  37947. },
  37948. enumerable: true,
  37949. configurable: true
  37950. });
  37951. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37952. /**
  37953. * Used to apply the vignette as a replacement of the pixel color.
  37954. */
  37955. get: function () {
  37956. return this._VIGNETTEMODE_OPAQUE;
  37957. },
  37958. enumerable: true,
  37959. configurable: true
  37960. });
  37961. // Static constants associated to the image processing.
  37962. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37963. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37964. __decorate([
  37965. BABYLON.serializeAsColorCurves()
  37966. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37967. __decorate([
  37968. BABYLON.serialize()
  37969. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37970. __decorate([
  37971. BABYLON.serializeAsTexture()
  37972. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37973. __decorate([
  37974. BABYLON.serialize()
  37975. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37976. __decorate([
  37977. BABYLON.serialize()
  37978. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37979. __decorate([
  37980. BABYLON.serialize()
  37981. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37982. __decorate([
  37983. BABYLON.serialize()
  37984. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37985. __decorate([
  37986. BABYLON.serialize()
  37987. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37988. __decorate([
  37989. BABYLON.serialize()
  37990. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37991. __decorate([
  37992. BABYLON.serialize()
  37993. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37994. __decorate([
  37995. BABYLON.serialize()
  37996. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37997. __decorate([
  37998. BABYLON.serialize()
  37999. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38000. __decorate([
  38001. BABYLON.serialize()
  38002. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38003. __decorate([
  38004. BABYLON.serializeAsColor4()
  38005. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38006. __decorate([
  38007. BABYLON.serialize()
  38008. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38009. __decorate([
  38010. BABYLON.serialize()
  38011. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38012. __decorate([
  38013. BABYLON.serialize()
  38014. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38015. __decorate([
  38016. BABYLON.serialize()
  38017. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38018. __decorate([
  38019. BABYLON.serialize()
  38020. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38021. return ImageProcessingConfiguration;
  38022. }());
  38023. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38024. })(BABYLON || (BABYLON = {}));
  38025. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38026. "use strict";
  38027. var BABYLON;
  38028. (function (BABYLON) {
  38029. /**
  38030. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38031. * It can help converting any input color in a desired output one. This can then be used to create effects
  38032. * from sepia, black and white to sixties or futuristic rendering...
  38033. *
  38034. * The only supported format is currently 3dl.
  38035. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38036. */
  38037. var ColorGradingTexture = /** @class */ (function (_super) {
  38038. __extends(ColorGradingTexture, _super);
  38039. /**
  38040. * Instantiates a ColorGradingTexture from the following parameters.
  38041. *
  38042. * @param url The location of the color gradind data (currently only supporting 3dl)
  38043. * @param scene The scene the texture will be used in
  38044. */
  38045. function ColorGradingTexture(url, scene) {
  38046. var _this = _super.call(this, scene) || this;
  38047. if (!url) {
  38048. return _this;
  38049. }
  38050. _this._engine = scene.getEngine();
  38051. _this._textureMatrix = BABYLON.Matrix.Identity();
  38052. _this.name = url;
  38053. _this.url = url;
  38054. _this.hasAlpha = false;
  38055. _this.isCube = false;
  38056. _this.is3D = _this._engine.webGLVersion > 1;
  38057. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38058. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38059. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38060. _this.anisotropicFilteringLevel = 1;
  38061. _this._texture = _this._getFromCache(url, true);
  38062. if (!_this._texture) {
  38063. if (!scene.useDelayedTextureLoading) {
  38064. _this.loadTexture();
  38065. }
  38066. else {
  38067. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38068. }
  38069. }
  38070. return _this;
  38071. }
  38072. /**
  38073. * Returns the texture matrix used in most of the material.
  38074. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38075. */
  38076. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38077. return this._textureMatrix;
  38078. };
  38079. /**
  38080. * Occurs when the file being loaded is a .3dl LUT file.
  38081. */
  38082. ColorGradingTexture.prototype.load3dlTexture = function () {
  38083. var engine = this._engine;
  38084. var texture;
  38085. if (engine.webGLVersion === 1) {
  38086. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38087. }
  38088. else {
  38089. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38090. }
  38091. this._texture = texture;
  38092. var callback = function (text) {
  38093. if (typeof text !== "string") {
  38094. return;
  38095. }
  38096. var data = null;
  38097. var tempData = null;
  38098. var line;
  38099. var lines = text.split('\n');
  38100. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38101. var maxColor = 0;
  38102. for (var i = 0; i < lines.length; i++) {
  38103. line = lines[i];
  38104. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38105. continue;
  38106. if (line.indexOf('#') === 0)
  38107. continue;
  38108. var words = line.split(" ");
  38109. if (size === 0) {
  38110. // Number of space + one
  38111. size = words.length;
  38112. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38113. tempData = new Float32Array(size * size * size * 4);
  38114. continue;
  38115. }
  38116. if (size != 0) {
  38117. var r = Math.max(parseInt(words[0]), 0);
  38118. var g = Math.max(parseInt(words[1]), 0);
  38119. var b = Math.max(parseInt(words[2]), 0);
  38120. maxColor = Math.max(r, maxColor);
  38121. maxColor = Math.max(g, maxColor);
  38122. maxColor = Math.max(b, maxColor);
  38123. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38124. if (tempData) {
  38125. tempData[pixelStorageIndex + 0] = r;
  38126. tempData[pixelStorageIndex + 1] = g;
  38127. tempData[pixelStorageIndex + 2] = b;
  38128. }
  38129. pixelIndexSlice++;
  38130. if (pixelIndexSlice % size == 0) {
  38131. pixelIndexH++;
  38132. pixelIndexSlice = 0;
  38133. if (pixelIndexH % size == 0) {
  38134. pixelIndexW++;
  38135. pixelIndexH = 0;
  38136. }
  38137. }
  38138. }
  38139. }
  38140. if (tempData && data) {
  38141. for (var i = 0; i < tempData.length; i++) {
  38142. if (i > 0 && (i + 1) % 4 === 0) {
  38143. data[i] = 255;
  38144. }
  38145. else {
  38146. var value = tempData[i];
  38147. data[i] = (value / maxColor * 255);
  38148. }
  38149. }
  38150. }
  38151. if (texture.is3D) {
  38152. texture.updateSize(size, size, size);
  38153. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38154. }
  38155. else {
  38156. texture.updateSize(size * size, size);
  38157. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38158. }
  38159. };
  38160. var scene = this.getScene();
  38161. if (scene) {
  38162. scene._loadFile(this.url, callback);
  38163. }
  38164. else {
  38165. this._engine._loadFile(this.url, callback);
  38166. }
  38167. return this._texture;
  38168. };
  38169. /**
  38170. * Starts the loading process of the texture.
  38171. */
  38172. ColorGradingTexture.prototype.loadTexture = function () {
  38173. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38174. this.load3dlTexture();
  38175. }
  38176. };
  38177. /**
  38178. * Clones the color gradind texture.
  38179. */
  38180. ColorGradingTexture.prototype.clone = function () {
  38181. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38182. // Base texture
  38183. newTexture.level = this.level;
  38184. return newTexture;
  38185. };
  38186. /**
  38187. * Called during delayed load for textures.
  38188. */
  38189. ColorGradingTexture.prototype.delayLoad = function () {
  38190. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38191. return;
  38192. }
  38193. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38194. this._texture = this._getFromCache(this.url, true);
  38195. if (!this._texture) {
  38196. this.loadTexture();
  38197. }
  38198. };
  38199. /**
  38200. * Parses a color grading texture serialized by Babylon.
  38201. * @param parsedTexture The texture information being parsedTexture
  38202. * @param scene The scene to load the texture in
  38203. * @param rootUrl The root url of the data assets to load
  38204. * @return A color gradind texture
  38205. */
  38206. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38207. var texture = null;
  38208. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38209. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38210. texture.name = parsedTexture.name;
  38211. texture.level = parsedTexture.level;
  38212. }
  38213. return texture;
  38214. };
  38215. /**
  38216. * Serializes the LUT texture to json format.
  38217. */
  38218. ColorGradingTexture.prototype.serialize = function () {
  38219. if (!this.name) {
  38220. return null;
  38221. }
  38222. var serializationObject = {};
  38223. serializationObject.name = this.name;
  38224. serializationObject.level = this.level;
  38225. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38226. return serializationObject;
  38227. };
  38228. /**
  38229. * Empty line regex stored for GC.
  38230. */
  38231. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38232. return ColorGradingTexture;
  38233. }(BABYLON.BaseTexture));
  38234. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38235. })(BABYLON || (BABYLON = {}));
  38236. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38237. "use strict";
  38238. var BABYLON;
  38239. (function (BABYLON) {
  38240. /**
  38241. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38242. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38243. * 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;
  38244. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38245. */
  38246. var ColorCurves = /** @class */ (function () {
  38247. function ColorCurves() {
  38248. this._dirty = true;
  38249. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38250. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38251. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38252. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38253. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38254. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38255. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38256. this._globalHue = 30;
  38257. this._globalDensity = 0;
  38258. this._globalSaturation = 0;
  38259. this._globalExposure = 0;
  38260. this._highlightsHue = 30;
  38261. this._highlightsDensity = 0;
  38262. this._highlightsSaturation = 0;
  38263. this._highlightsExposure = 0;
  38264. this._midtonesHue = 30;
  38265. this._midtonesDensity = 0;
  38266. this._midtonesSaturation = 0;
  38267. this._midtonesExposure = 0;
  38268. this._shadowsHue = 30;
  38269. this._shadowsDensity = 0;
  38270. this._shadowsSaturation = 0;
  38271. this._shadowsExposure = 0;
  38272. }
  38273. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38274. /**
  38275. * Gets the global Hue value.
  38276. * 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).
  38277. */
  38278. get: function () {
  38279. return this._globalHue;
  38280. },
  38281. /**
  38282. * Sets the global Hue value.
  38283. * 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).
  38284. */
  38285. set: function (value) {
  38286. this._globalHue = value;
  38287. this._dirty = true;
  38288. },
  38289. enumerable: true,
  38290. configurable: true
  38291. });
  38292. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38293. /**
  38294. * Gets the global Density value.
  38295. * 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.
  38296. * Values less than zero provide a filter of opposite hue.
  38297. */
  38298. get: function () {
  38299. return this._globalDensity;
  38300. },
  38301. /**
  38302. * Sets the global Density value.
  38303. * 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.
  38304. * Values less than zero provide a filter of opposite hue.
  38305. */
  38306. set: function (value) {
  38307. this._globalDensity = value;
  38308. this._dirty = true;
  38309. },
  38310. enumerable: true,
  38311. configurable: true
  38312. });
  38313. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38314. /**
  38315. * Gets the global Saturation value.
  38316. * 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.
  38317. */
  38318. get: function () {
  38319. return this._globalSaturation;
  38320. },
  38321. /**
  38322. * Sets the global Saturation value.
  38323. * 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.
  38324. */
  38325. set: function (value) {
  38326. this._globalSaturation = value;
  38327. this._dirty = true;
  38328. },
  38329. enumerable: true,
  38330. configurable: true
  38331. });
  38332. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38333. /**
  38334. * Gets the highlights Hue value.
  38335. * 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).
  38336. */
  38337. get: function () {
  38338. return this._highlightsHue;
  38339. },
  38340. /**
  38341. * Sets the highlights Hue value.
  38342. * 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).
  38343. */
  38344. set: function (value) {
  38345. this._highlightsHue = value;
  38346. this._dirty = true;
  38347. },
  38348. enumerable: true,
  38349. configurable: true
  38350. });
  38351. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38352. /**
  38353. * Gets the highlights Density value.
  38354. * 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.
  38355. * Values less than zero provide a filter of opposite hue.
  38356. */
  38357. get: function () {
  38358. return this._highlightsDensity;
  38359. },
  38360. /**
  38361. * Sets the highlights Density value.
  38362. * 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.
  38363. * Values less than zero provide a filter of opposite hue.
  38364. */
  38365. set: function (value) {
  38366. this._highlightsDensity = value;
  38367. this._dirty = true;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38373. /**
  38374. * Gets the highlights Saturation value.
  38375. * 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.
  38376. */
  38377. get: function () {
  38378. return this._highlightsSaturation;
  38379. },
  38380. /**
  38381. * Sets the highlights Saturation value.
  38382. * 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.
  38383. */
  38384. set: function (value) {
  38385. this._highlightsSaturation = value;
  38386. this._dirty = true;
  38387. },
  38388. enumerable: true,
  38389. configurable: true
  38390. });
  38391. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38392. /**
  38393. * Gets the highlights Exposure value.
  38394. * 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.
  38395. */
  38396. get: function () {
  38397. return this._highlightsExposure;
  38398. },
  38399. /**
  38400. * Sets the highlights Exposure value.
  38401. * 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.
  38402. */
  38403. set: function (value) {
  38404. this._highlightsExposure = value;
  38405. this._dirty = true;
  38406. },
  38407. enumerable: true,
  38408. configurable: true
  38409. });
  38410. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38411. /**
  38412. * Gets the midtones Hue value.
  38413. * 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).
  38414. */
  38415. get: function () {
  38416. return this._midtonesHue;
  38417. },
  38418. /**
  38419. * Sets the midtones Hue value.
  38420. * 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).
  38421. */
  38422. set: function (value) {
  38423. this._midtonesHue = value;
  38424. this._dirty = true;
  38425. },
  38426. enumerable: true,
  38427. configurable: true
  38428. });
  38429. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38430. /**
  38431. * Gets the midtones Density value.
  38432. * 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.
  38433. * Values less than zero provide a filter of opposite hue.
  38434. */
  38435. get: function () {
  38436. return this._midtonesDensity;
  38437. },
  38438. /**
  38439. * Sets the midtones Density value.
  38440. * 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.
  38441. * Values less than zero provide a filter of opposite hue.
  38442. */
  38443. set: function (value) {
  38444. this._midtonesDensity = value;
  38445. this._dirty = true;
  38446. },
  38447. enumerable: true,
  38448. configurable: true
  38449. });
  38450. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38451. /**
  38452. * Gets the midtones Saturation value.
  38453. * 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.
  38454. */
  38455. get: function () {
  38456. return this._midtonesSaturation;
  38457. },
  38458. /**
  38459. * Sets the midtones Saturation value.
  38460. * 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.
  38461. */
  38462. set: function (value) {
  38463. this._midtonesSaturation = value;
  38464. this._dirty = true;
  38465. },
  38466. enumerable: true,
  38467. configurable: true
  38468. });
  38469. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38470. /**
  38471. * Gets the midtones Exposure value.
  38472. * 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.
  38473. */
  38474. get: function () {
  38475. return this._midtonesExposure;
  38476. },
  38477. /**
  38478. * Sets the midtones Exposure value.
  38479. * 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.
  38480. */
  38481. set: function (value) {
  38482. this._midtonesExposure = value;
  38483. this._dirty = true;
  38484. },
  38485. enumerable: true,
  38486. configurable: true
  38487. });
  38488. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38489. /**
  38490. * Gets the shadows Hue value.
  38491. * 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).
  38492. */
  38493. get: function () {
  38494. return this._shadowsHue;
  38495. },
  38496. /**
  38497. * Sets the shadows Hue value.
  38498. * 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).
  38499. */
  38500. set: function (value) {
  38501. this._shadowsHue = value;
  38502. this._dirty = true;
  38503. },
  38504. enumerable: true,
  38505. configurable: true
  38506. });
  38507. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38508. /**
  38509. * Gets the shadows Density value.
  38510. * 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.
  38511. * Values less than zero provide a filter of opposite hue.
  38512. */
  38513. get: function () {
  38514. return this._shadowsDensity;
  38515. },
  38516. /**
  38517. * Sets the shadows Density value.
  38518. * 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.
  38519. * Values less than zero provide a filter of opposite hue.
  38520. */
  38521. set: function (value) {
  38522. this._shadowsDensity = value;
  38523. this._dirty = true;
  38524. },
  38525. enumerable: true,
  38526. configurable: true
  38527. });
  38528. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38529. /**
  38530. * Gets the shadows Saturation value.
  38531. * 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.
  38532. */
  38533. get: function () {
  38534. return this._shadowsSaturation;
  38535. },
  38536. /**
  38537. * Sets the shadows Saturation value.
  38538. * 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.
  38539. */
  38540. set: function (value) {
  38541. this._shadowsSaturation = value;
  38542. this._dirty = true;
  38543. },
  38544. enumerable: true,
  38545. configurable: true
  38546. });
  38547. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38548. /**
  38549. * Gets the shadows Exposure value.
  38550. * 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.
  38551. */
  38552. get: function () {
  38553. return this._shadowsExposure;
  38554. },
  38555. /**
  38556. * Sets the shadows Exposure value.
  38557. * 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.
  38558. */
  38559. set: function (value) {
  38560. this._shadowsExposure = value;
  38561. this._dirty = true;
  38562. },
  38563. enumerable: true,
  38564. configurable: true
  38565. });
  38566. ColorCurves.prototype.getClassName = function () {
  38567. return "ColorCurves";
  38568. };
  38569. /**
  38570. * Binds the color curves to the shader.
  38571. * @param colorCurves The color curve to bind
  38572. * @param effect The effect to bind to
  38573. */
  38574. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38575. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38576. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38577. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38578. if (colorCurves._dirty) {
  38579. colorCurves._dirty = false;
  38580. // Fill in global info.
  38581. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38582. // Compute highlights info.
  38583. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38584. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38585. // Compute midtones info.
  38586. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38587. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38588. // Compute shadows info.
  38589. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38590. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38591. // Compute deltas (neutral is midtones).
  38592. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38593. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38594. }
  38595. if (effect) {
  38596. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38597. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38598. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38599. }
  38600. };
  38601. /**
  38602. * Prepare the list of uniforms associated with the ColorCurves effects.
  38603. * @param uniformsList The list of uniforms used in the effect
  38604. */
  38605. ColorCurves.PrepareUniforms = function (uniformsList) {
  38606. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38607. };
  38608. /**
  38609. * Returns color grading data based on a hue, density, saturation and exposure value.
  38610. * @param filterHue The hue of the color filter.
  38611. * @param filterDensity The density of the color filter.
  38612. * @param saturation The saturation.
  38613. * @param exposure The exposure.
  38614. * @param result The result data container.
  38615. */
  38616. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38617. if (hue == null) {
  38618. return;
  38619. }
  38620. hue = ColorCurves.clamp(hue, 0, 360);
  38621. density = ColorCurves.clamp(density, -100, 100);
  38622. saturation = ColorCurves.clamp(saturation, -100, 100);
  38623. exposure = ColorCurves.clamp(exposure, -100, 100);
  38624. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38625. // so that the maximum filter density is only 50% control. This provides fine control
  38626. // for small values and reasonable range.
  38627. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38628. density *= 0.5;
  38629. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38630. if (density < 0) {
  38631. density *= -1;
  38632. hue = (hue + 180) % 360;
  38633. }
  38634. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38635. result.scaleToRef(2, result);
  38636. result.a = 1 + 0.01 * saturation;
  38637. };
  38638. /**
  38639. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38640. * @param value The input slider value in range [-100,100].
  38641. * @returns Adjusted value.
  38642. */
  38643. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38644. value /= 100;
  38645. var x = Math.abs(value);
  38646. x = Math.pow(x, 2);
  38647. if (value < 0) {
  38648. x *= -1;
  38649. }
  38650. x *= 100;
  38651. return x;
  38652. };
  38653. /**
  38654. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38655. * @param hue The hue (H) input.
  38656. * @param saturation The saturation (S) input.
  38657. * @param brightness The brightness (B) input.
  38658. * @result An RGBA color represented as Vector4.
  38659. */
  38660. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38661. var h = ColorCurves.clamp(hue, 0, 360);
  38662. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38663. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38664. if (s === 0) {
  38665. result.r = v;
  38666. result.g = v;
  38667. result.b = v;
  38668. }
  38669. else {
  38670. // sector 0 to 5
  38671. h /= 60;
  38672. var i = Math.floor(h);
  38673. // fractional part of h
  38674. var f = h - i;
  38675. var p = v * (1 - s);
  38676. var q = v * (1 - s * f);
  38677. var t = v * (1 - s * (1 - f));
  38678. switch (i) {
  38679. case 0:
  38680. result.r = v;
  38681. result.g = t;
  38682. result.b = p;
  38683. break;
  38684. case 1:
  38685. result.r = q;
  38686. result.g = v;
  38687. result.b = p;
  38688. break;
  38689. case 2:
  38690. result.r = p;
  38691. result.g = v;
  38692. result.b = t;
  38693. break;
  38694. case 3:
  38695. result.r = p;
  38696. result.g = q;
  38697. result.b = v;
  38698. break;
  38699. case 4:
  38700. result.r = t;
  38701. result.g = p;
  38702. result.b = v;
  38703. break;
  38704. default:// case 5:
  38705. result.r = v;
  38706. result.g = p;
  38707. result.b = q;
  38708. break;
  38709. }
  38710. }
  38711. result.a = 1;
  38712. };
  38713. /**
  38714. * Returns a value clamped between min and max
  38715. * @param value The value to clamp
  38716. * @param min The minimum of value
  38717. * @param max The maximum of value
  38718. * @returns The clamped value.
  38719. */
  38720. ColorCurves.clamp = function (value, min, max) {
  38721. return Math.min(Math.max(value, min), max);
  38722. };
  38723. /**
  38724. * Clones the current color curve instance.
  38725. * @return The cloned curves
  38726. */
  38727. ColorCurves.prototype.clone = function () {
  38728. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38729. };
  38730. /**
  38731. * Serializes the current color curve instance to a json representation.
  38732. * @return a JSON representation
  38733. */
  38734. ColorCurves.prototype.serialize = function () {
  38735. return BABYLON.SerializationHelper.Serialize(this);
  38736. };
  38737. /**
  38738. * Parses the color curve from a json representation.
  38739. * @param source the JSON source to parse
  38740. * @return The parsed curves
  38741. */
  38742. ColorCurves.Parse = function (source) {
  38743. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38744. };
  38745. __decorate([
  38746. BABYLON.serialize()
  38747. ], ColorCurves.prototype, "_globalHue", void 0);
  38748. __decorate([
  38749. BABYLON.serialize()
  38750. ], ColorCurves.prototype, "_globalDensity", void 0);
  38751. __decorate([
  38752. BABYLON.serialize()
  38753. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38754. __decorate([
  38755. BABYLON.serialize()
  38756. ], ColorCurves.prototype, "_globalExposure", void 0);
  38757. __decorate([
  38758. BABYLON.serialize()
  38759. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38760. __decorate([
  38761. BABYLON.serialize()
  38762. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38763. __decorate([
  38764. BABYLON.serialize()
  38765. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38766. __decorate([
  38767. BABYLON.serialize()
  38768. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38769. __decorate([
  38770. BABYLON.serialize()
  38771. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38772. __decorate([
  38773. BABYLON.serialize()
  38774. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38775. __decorate([
  38776. BABYLON.serialize()
  38777. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38778. __decorate([
  38779. BABYLON.serialize()
  38780. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38781. return ColorCurves;
  38782. }());
  38783. BABYLON.ColorCurves = ColorCurves;
  38784. })(BABYLON || (BABYLON = {}));
  38785. //# sourceMappingURL=babylon.colorCurves.js.map
  38786. "use strict";
  38787. //# sourceMappingURL=babylon.behavior.js.map
  38788. "use strict";
  38789. var BABYLON;
  38790. (function (BABYLON) {
  38791. /**
  38792. * "Static Class" containing the most commonly used helper while dealing with material for
  38793. * rendering purpose.
  38794. *
  38795. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38796. *
  38797. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38798. */
  38799. var MaterialHelper = /** @class */ (function () {
  38800. function MaterialHelper() {
  38801. }
  38802. /**
  38803. * Bind the current view position to an effect.
  38804. * @param effect The effect to be bound
  38805. * @param scene The scene the eyes position is used from
  38806. */
  38807. MaterialHelper.BindEyePosition = function (effect, scene) {
  38808. if (scene._forcedViewPosition) {
  38809. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38810. return;
  38811. }
  38812. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38813. };
  38814. /**
  38815. * Helps preparing the defines values about the UVs in used in the effect.
  38816. * UVs are shared as much as we can accross chanels in the shaders.
  38817. * @param texture The texture we are preparing the UVs for
  38818. * @param defines The defines to update
  38819. * @param key The chanel key "diffuse", "specular"... used in the shader
  38820. */
  38821. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38822. defines._needUVs = true;
  38823. defines[key] = true;
  38824. if (texture.getTextureMatrix().isIdentity(true)) {
  38825. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38826. if (texture.coordinatesIndex === 0) {
  38827. defines["MAINUV1"] = true;
  38828. }
  38829. else {
  38830. defines["MAINUV2"] = true;
  38831. }
  38832. }
  38833. else {
  38834. defines[key + "DIRECTUV"] = 0;
  38835. }
  38836. };
  38837. /**
  38838. * Binds a texture matrix value to its corrsponding uniform
  38839. * @param texture The texture to bind the matrix for
  38840. * @param uniformBuffer The uniform buffer receivin the data
  38841. * @param key The chanel key "diffuse", "specular"... used in the shader
  38842. */
  38843. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38844. var matrix = texture.getTextureMatrix();
  38845. if (!matrix.isIdentity(true)) {
  38846. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38847. }
  38848. };
  38849. /**
  38850. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38851. * @param mesh defines the current mesh
  38852. * @param scene defines the current scene
  38853. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38854. * @param pointsCloud defines if point cloud rendering has to be turned on
  38855. * @param fogEnabled defines if fog has to be turned on
  38856. * @param alphaTest defines if alpha testing has to be turned on
  38857. * @param defines defines the current list of defines
  38858. */
  38859. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38860. if (defines._areMiscDirty) {
  38861. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38862. defines["POINTSIZE"] = pointsCloud;
  38863. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38864. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38865. defines["ALPHATEST"] = alphaTest;
  38866. }
  38867. };
  38868. /**
  38869. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38870. * @param scene defines the current scene
  38871. * @param engine defines the current engine
  38872. * @param defines specifies the list of active defines
  38873. * @param useInstances defines if instances have to be turned on
  38874. * @param useClipPlane defines if clip plane have to be turned on
  38875. */
  38876. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38877. if (useClipPlane === void 0) { useClipPlane = null; }
  38878. var changed = false;
  38879. if (useClipPlane == null) {
  38880. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38881. }
  38882. if (defines["CLIPPLANE"] !== useClipPlane) {
  38883. defines["CLIPPLANE"] = useClipPlane;
  38884. changed = true;
  38885. }
  38886. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38887. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38888. changed = true;
  38889. }
  38890. if (defines["INSTANCES"] !== useInstances) {
  38891. defines["INSTANCES"] = useInstances;
  38892. changed = true;
  38893. }
  38894. if (changed) {
  38895. defines.markAsUnprocessed();
  38896. }
  38897. };
  38898. /**
  38899. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38900. * @param mesh The mesh containing the geometry data we will draw
  38901. * @param defines The defines to update
  38902. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38903. * @param useBones Precise whether bones should be used or not (override mesh info)
  38904. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38905. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38906. * @returns false if defines are considered not dirty and have not been checked
  38907. */
  38908. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38909. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38910. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38911. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38912. return false;
  38913. }
  38914. defines._normals = defines._needNormals;
  38915. defines._uvs = defines._needUVs;
  38916. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38917. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38918. defines["TANGENT"] = true;
  38919. }
  38920. if (defines._needUVs) {
  38921. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38922. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38923. }
  38924. else {
  38925. defines["UV1"] = false;
  38926. defines["UV2"] = false;
  38927. }
  38928. if (useVertexColor) {
  38929. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38930. defines["VERTEXCOLOR"] = hasVertexColors;
  38931. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38932. }
  38933. if (useBones) {
  38934. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38935. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38936. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38937. }
  38938. else {
  38939. defines["NUM_BONE_INFLUENCERS"] = 0;
  38940. defines["BonesPerMesh"] = 0;
  38941. }
  38942. }
  38943. if (useMorphTargets) {
  38944. var manager = mesh.morphTargetManager;
  38945. if (manager) {
  38946. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38947. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38948. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38949. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38950. }
  38951. else {
  38952. defines["MORPHTARGETS_TANGENT"] = false;
  38953. defines["MORPHTARGETS_NORMAL"] = false;
  38954. defines["MORPHTARGETS"] = false;
  38955. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38956. }
  38957. }
  38958. return true;
  38959. };
  38960. /**
  38961. * Prepares the defines related to the light information passed in parameter
  38962. * @param scene The scene we are intending to draw
  38963. * @param mesh The mesh the effect is compiling for
  38964. * @param defines The defines to update
  38965. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38966. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38967. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38968. * @returns true if normals will be required for the rest of the effect
  38969. */
  38970. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38971. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38972. if (disableLighting === void 0) { disableLighting = false; }
  38973. if (!defines._areLightsDirty) {
  38974. return defines._needNormals;
  38975. }
  38976. var lightIndex = 0;
  38977. var needNormals = false;
  38978. var needRebuild = false;
  38979. var lightmapMode = false;
  38980. var shadowEnabled = false;
  38981. var specularEnabled = false;
  38982. if (scene.lightsEnabled && !disableLighting) {
  38983. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38984. var light = _a[_i];
  38985. needNormals = true;
  38986. if (defines["LIGHT" + lightIndex] === undefined) {
  38987. needRebuild = true;
  38988. }
  38989. defines["LIGHT" + lightIndex] = true;
  38990. defines["SPOTLIGHT" + lightIndex] = false;
  38991. defines["HEMILIGHT" + lightIndex] = false;
  38992. defines["POINTLIGHT" + lightIndex] = false;
  38993. defines["DIRLIGHT" + lightIndex] = false;
  38994. var type;
  38995. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38996. type = "SPOTLIGHT" + lightIndex;
  38997. var spotLight = light;
  38998. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38999. }
  39000. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39001. type = "HEMILIGHT" + lightIndex;
  39002. }
  39003. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39004. type = "POINTLIGHT" + lightIndex;
  39005. }
  39006. else {
  39007. type = "DIRLIGHT" + lightIndex;
  39008. }
  39009. defines[type] = true;
  39010. // Specular
  39011. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39012. specularEnabled = true;
  39013. }
  39014. // Shadows
  39015. defines["SHADOW" + lightIndex] = false;
  39016. defines["SHADOWPCF" + lightIndex] = false;
  39017. defines["SHADOWPCSS" + lightIndex] = false;
  39018. defines["SHADOWPOISSON" + lightIndex] = false;
  39019. defines["SHADOWESM" + lightIndex] = false;
  39020. defines["SHADOWCUBE" + lightIndex] = false;
  39021. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39022. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39023. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39024. var shadowGenerator = light.getShadowGenerator();
  39025. if (shadowGenerator) {
  39026. shadowEnabled = true;
  39027. shadowGenerator.prepareDefines(defines, lightIndex);
  39028. }
  39029. }
  39030. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39031. lightmapMode = true;
  39032. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39033. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39034. }
  39035. else {
  39036. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39037. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39038. }
  39039. lightIndex++;
  39040. if (lightIndex === maxSimultaneousLights)
  39041. break;
  39042. }
  39043. }
  39044. defines["SPECULARTERM"] = specularEnabled;
  39045. defines["SHADOWS"] = shadowEnabled;
  39046. // Resetting all other lights if any
  39047. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39048. if (defines["LIGHT" + index] !== undefined) {
  39049. defines["LIGHT" + index] = false;
  39050. defines["HEMILIGHT" + lightIndex] = false;
  39051. defines["POINTLIGHT" + lightIndex] = false;
  39052. defines["DIRLIGHT" + lightIndex] = false;
  39053. defines["SPOTLIGHT" + lightIndex] = false;
  39054. defines["SHADOW" + lightIndex] = false;
  39055. }
  39056. }
  39057. var caps = scene.getEngine().getCaps();
  39058. if (defines["SHADOWFLOAT"] === undefined) {
  39059. needRebuild = true;
  39060. }
  39061. defines["SHADOWFLOAT"] = shadowEnabled &&
  39062. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39063. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39064. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39065. if (needRebuild) {
  39066. defines.rebuild();
  39067. }
  39068. return needNormals;
  39069. };
  39070. /**
  39071. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39072. * that won t be acctive due to defines being turned off.
  39073. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39074. * @param samplersList The samplers list
  39075. * @param defines The defines helping in the list generation
  39076. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39077. */
  39078. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39079. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39080. var uniformsList;
  39081. var uniformBuffersList = null;
  39082. if (uniformsListOrOptions.uniformsNames) {
  39083. var options = uniformsListOrOptions;
  39084. uniformsList = options.uniformsNames;
  39085. uniformBuffersList = options.uniformBuffersNames;
  39086. samplersList = options.samplers;
  39087. defines = options.defines;
  39088. maxSimultaneousLights = options.maxSimultaneousLights;
  39089. }
  39090. else {
  39091. uniformsList = uniformsListOrOptions;
  39092. if (!samplersList) {
  39093. samplersList = [];
  39094. }
  39095. }
  39096. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39097. if (!defines["LIGHT" + lightIndex]) {
  39098. break;
  39099. }
  39100. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39101. if (uniformBuffersList) {
  39102. uniformBuffersList.push("Light" + lightIndex);
  39103. }
  39104. samplersList.push("shadowSampler" + lightIndex);
  39105. samplersList.push("depthSampler" + lightIndex);
  39106. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39107. samplersList.push("projectionLightSampler" + lightIndex);
  39108. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39109. }
  39110. }
  39111. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39112. uniformsList.push("morphTargetInfluences");
  39113. }
  39114. };
  39115. /**
  39116. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39117. * @param defines The defines to update while falling back
  39118. * @param fallbacks The authorized effect fallbacks
  39119. * @param maxSimultaneousLights The maximum number of lights allowed
  39120. * @param rank the current rank of the Effect
  39121. * @returns The newly affected rank
  39122. */
  39123. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39124. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39125. if (rank === void 0) { rank = 0; }
  39126. var lightFallbackRank = 0;
  39127. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39128. if (!defines["LIGHT" + lightIndex]) {
  39129. break;
  39130. }
  39131. if (lightIndex > 0) {
  39132. lightFallbackRank = rank + lightIndex;
  39133. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39134. }
  39135. if (!defines["SHADOWS"]) {
  39136. if (defines["SHADOW" + lightIndex]) {
  39137. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39138. }
  39139. if (defines["SHADOWPCF" + lightIndex]) {
  39140. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39141. }
  39142. if (defines["SHADOWPCSS" + lightIndex]) {
  39143. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39144. }
  39145. if (defines["SHADOWPOISSON" + lightIndex]) {
  39146. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39147. }
  39148. if (defines["SHADOWESM" + lightIndex]) {
  39149. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39150. }
  39151. }
  39152. }
  39153. return lightFallbackRank++;
  39154. };
  39155. /**
  39156. * Prepares the list of attributes required for morph targets according to the effect defines.
  39157. * @param attribs The current list of supported attribs
  39158. * @param mesh The mesh to prepare the morph targets attributes for
  39159. * @param defines The current Defines of the effect
  39160. */
  39161. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39162. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39163. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39164. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39165. var manager = mesh.morphTargetManager;
  39166. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39167. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39168. for (var index = 0; index < influencers; index++) {
  39169. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39170. if (normal) {
  39171. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39172. }
  39173. if (tangent) {
  39174. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39175. }
  39176. if (attribs.length > maxAttributesCount) {
  39177. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39178. }
  39179. }
  39180. }
  39181. };
  39182. /**
  39183. * Prepares the list of attributes required for bones according to the effect defines.
  39184. * @param attribs The current list of supported attribs
  39185. * @param mesh The mesh to prepare the bones attributes for
  39186. * @param defines The current Defines of the effect
  39187. * @param fallbacks The current efffect fallback strategy
  39188. */
  39189. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39190. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39191. fallbacks.addCPUSkinningFallback(0, mesh);
  39192. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39193. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39194. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39195. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39196. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39197. }
  39198. }
  39199. };
  39200. /**
  39201. * Prepares the list of attributes required for instances according to the effect defines.
  39202. * @param attribs The current list of supported attribs
  39203. * @param defines The current Defines of the effect
  39204. */
  39205. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39206. if (defines["INSTANCES"]) {
  39207. attribs.push("world0");
  39208. attribs.push("world1");
  39209. attribs.push("world2");
  39210. attribs.push("world3");
  39211. }
  39212. };
  39213. /**
  39214. * Binds the light shadow information to the effect for the given mesh.
  39215. * @param light The light containing the generator
  39216. * @param scene The scene the lights belongs to
  39217. * @param mesh The mesh we are binding the information to render
  39218. * @param lightIndex The light index in the effect used to render the mesh
  39219. * @param effect The effect we are binding the data to
  39220. */
  39221. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39222. if (light.shadowEnabled && mesh.receiveShadows) {
  39223. var shadowGenerator = light.getShadowGenerator();
  39224. if (shadowGenerator) {
  39225. shadowGenerator.bindShadowLight(lightIndex, effect);
  39226. }
  39227. }
  39228. };
  39229. /**
  39230. * Binds the light information to the effect.
  39231. * @param light The light containing the generator
  39232. * @param effect The effect we are binding the data to
  39233. * @param lightIndex The light index in the effect used to render
  39234. */
  39235. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39236. light.transferToEffect(effect, lightIndex + "");
  39237. };
  39238. /**
  39239. * Binds the lights information from the scene to the effect for the given mesh.
  39240. * @param scene The scene the lights belongs to
  39241. * @param mesh The mesh we are binding the information to render
  39242. * @param effect The effect we are binding the data to
  39243. * @param defines The generated defines for the effect
  39244. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39245. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39246. */
  39247. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39248. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39249. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39250. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39251. for (var i = 0; i < len; i++) {
  39252. var light = mesh._lightSources[i];
  39253. var iAsString = i.toString();
  39254. var scaledIntensity = light.getScaledIntensity();
  39255. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39256. MaterialHelper.BindLightProperties(light, effect, i);
  39257. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39258. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39259. if (defines["SPECULARTERM"]) {
  39260. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39261. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39262. }
  39263. // Shadows
  39264. if (scene.shadowsEnabled) {
  39265. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39266. }
  39267. light._uniformBuffer.update();
  39268. }
  39269. };
  39270. /**
  39271. * Binds the fog information from the scene to the effect for the given mesh.
  39272. * @param scene The scene the lights belongs to
  39273. * @param mesh The mesh we are binding the information to render
  39274. * @param effect The effect we are binding the data to
  39275. */
  39276. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39277. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39278. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39279. effect.setColor3("vFogColor", scene.fogColor);
  39280. }
  39281. };
  39282. /**
  39283. * Binds the bones information from the mesh to the effect.
  39284. * @param mesh The mesh we are binding the information to render
  39285. * @param effect The effect we are binding the data to
  39286. */
  39287. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39288. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39289. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39290. if (matrices && effect) {
  39291. effect.setMatrices("mBones", matrices);
  39292. }
  39293. }
  39294. };
  39295. /**
  39296. * Binds the morph targets information from the mesh to the effect.
  39297. * @param abstractMesh The mesh we are binding the information to render
  39298. * @param effect The effect we are binding the data to
  39299. */
  39300. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39301. var manager = abstractMesh.morphTargetManager;
  39302. if (!abstractMesh || !manager) {
  39303. return;
  39304. }
  39305. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39306. };
  39307. /**
  39308. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39309. * @param defines The generated defines used in the effect
  39310. * @param effect The effect we are binding the data to
  39311. * @param scene The scene we are willing to render with logarithmic scale for
  39312. */
  39313. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39314. if (defines["LOGARITHMICDEPTH"]) {
  39315. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39316. }
  39317. };
  39318. /**
  39319. * Binds the clip plane information from the scene to the effect.
  39320. * @param scene The scene the clip plane information are extracted from
  39321. * @param effect The effect we are binding the data to
  39322. */
  39323. MaterialHelper.BindClipPlane = function (effect, scene) {
  39324. if (scene.clipPlane) {
  39325. var clipPlane = scene.clipPlane;
  39326. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39327. }
  39328. };
  39329. return MaterialHelper;
  39330. }());
  39331. BABYLON.MaterialHelper = MaterialHelper;
  39332. })(BABYLON || (BABYLON = {}));
  39333. //# sourceMappingURL=babylon.materialHelper.js.map
  39334. "use strict";
  39335. var BABYLON;
  39336. (function (BABYLON) {
  39337. var PushMaterial = /** @class */ (function (_super) {
  39338. __extends(PushMaterial, _super);
  39339. function PushMaterial(name, scene) {
  39340. var _this = _super.call(this, name, scene) || this;
  39341. _this._normalMatrix = new BABYLON.Matrix();
  39342. _this.storeEffectOnSubMeshes = true;
  39343. return _this;
  39344. }
  39345. PushMaterial.prototype.getEffect = function () {
  39346. return this._activeEffect;
  39347. };
  39348. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39349. if (!mesh) {
  39350. return false;
  39351. }
  39352. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39353. return true;
  39354. }
  39355. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39356. };
  39357. /**
  39358. * Binds the given world matrix to the active effect
  39359. *
  39360. * @param world the matrix to bind
  39361. */
  39362. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39363. this._activeEffect.setMatrix("world", world);
  39364. };
  39365. /**
  39366. * Binds the given normal matrix to the active effect
  39367. *
  39368. * @param normalMatrix the matrix to bind
  39369. */
  39370. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39371. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39372. };
  39373. PushMaterial.prototype.bind = function (world, mesh) {
  39374. if (!mesh) {
  39375. return;
  39376. }
  39377. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39378. };
  39379. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39380. if (effect === void 0) { effect = null; }
  39381. _super.prototype._afterBind.call(this, mesh);
  39382. this.getScene()._cachedEffect = effect;
  39383. };
  39384. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39385. if (visibility === void 0) { visibility = 1; }
  39386. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39387. };
  39388. return PushMaterial;
  39389. }(BABYLON.Material));
  39390. BABYLON.PushMaterial = PushMaterial;
  39391. })(BABYLON || (BABYLON = {}));
  39392. //# sourceMappingURL=babylon.pushMaterial.js.map
  39393. "use strict";
  39394. var BABYLON;
  39395. (function (BABYLON) {
  39396. /** @ignore */
  39397. var StandardMaterialDefines = /** @class */ (function (_super) {
  39398. __extends(StandardMaterialDefines, _super);
  39399. function StandardMaterialDefines() {
  39400. var _this = _super.call(this) || this;
  39401. _this.MAINUV1 = false;
  39402. _this.MAINUV2 = false;
  39403. _this.DIFFUSE = false;
  39404. _this.DIFFUSEDIRECTUV = 0;
  39405. _this.AMBIENT = false;
  39406. _this.AMBIENTDIRECTUV = 0;
  39407. _this.OPACITY = false;
  39408. _this.OPACITYDIRECTUV = 0;
  39409. _this.OPACITYRGB = false;
  39410. _this.REFLECTION = false;
  39411. _this.EMISSIVE = false;
  39412. _this.EMISSIVEDIRECTUV = 0;
  39413. _this.SPECULAR = false;
  39414. _this.SPECULARDIRECTUV = 0;
  39415. _this.BUMP = false;
  39416. _this.BUMPDIRECTUV = 0;
  39417. _this.PARALLAX = false;
  39418. _this.PARALLAXOCCLUSION = false;
  39419. _this.SPECULAROVERALPHA = false;
  39420. _this.CLIPPLANE = false;
  39421. _this.ALPHATEST = false;
  39422. _this.DEPTHPREPASS = false;
  39423. _this.ALPHAFROMDIFFUSE = false;
  39424. _this.POINTSIZE = false;
  39425. _this.FOG = false;
  39426. _this.SPECULARTERM = false;
  39427. _this.DIFFUSEFRESNEL = false;
  39428. _this.OPACITYFRESNEL = false;
  39429. _this.REFLECTIONFRESNEL = false;
  39430. _this.REFRACTIONFRESNEL = false;
  39431. _this.EMISSIVEFRESNEL = false;
  39432. _this.FRESNEL = false;
  39433. _this.NORMAL = false;
  39434. _this.UV1 = false;
  39435. _this.UV2 = false;
  39436. _this.VERTEXCOLOR = false;
  39437. _this.VERTEXALPHA = false;
  39438. _this.NUM_BONE_INFLUENCERS = 0;
  39439. _this.BonesPerMesh = 0;
  39440. _this.INSTANCES = false;
  39441. _this.GLOSSINESS = false;
  39442. _this.ROUGHNESS = false;
  39443. _this.EMISSIVEASILLUMINATION = false;
  39444. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39445. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39446. _this.LIGHTMAP = false;
  39447. _this.LIGHTMAPDIRECTUV = 0;
  39448. _this.OBJECTSPACE_NORMALMAP = false;
  39449. _this.USELIGHTMAPASSHADOWMAP = false;
  39450. _this.REFLECTIONMAP_3D = false;
  39451. _this.REFLECTIONMAP_SPHERICAL = false;
  39452. _this.REFLECTIONMAP_PLANAR = false;
  39453. _this.REFLECTIONMAP_CUBIC = false;
  39454. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39455. _this.REFLECTIONMAP_PROJECTION = false;
  39456. _this.REFLECTIONMAP_SKYBOX = false;
  39457. _this.REFLECTIONMAP_EXPLICIT = false;
  39458. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39459. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39460. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39461. _this.INVERTCUBICMAP = false;
  39462. _this.LOGARITHMICDEPTH = false;
  39463. _this.REFRACTION = false;
  39464. _this.REFRACTIONMAP_3D = false;
  39465. _this.REFLECTIONOVERALPHA = false;
  39466. _this.TWOSIDEDLIGHTING = false;
  39467. _this.SHADOWFLOAT = false;
  39468. _this.MORPHTARGETS = false;
  39469. _this.MORPHTARGETS_NORMAL = false;
  39470. _this.MORPHTARGETS_TANGENT = false;
  39471. _this.NUM_MORPH_INFLUENCERS = 0;
  39472. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39473. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39474. _this.IMAGEPROCESSING = false;
  39475. _this.VIGNETTE = false;
  39476. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39477. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39478. _this.TONEMAPPING = false;
  39479. _this.CONTRAST = false;
  39480. _this.COLORCURVES = false;
  39481. _this.COLORGRADING = false;
  39482. _this.COLORGRADING3D = false;
  39483. _this.SAMPLER3DGREENDEPTH = false;
  39484. _this.SAMPLER3DBGRMAP = false;
  39485. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39486. _this.EXPOSURE = false;
  39487. _this.rebuild();
  39488. return _this;
  39489. }
  39490. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39491. var modes = [
  39492. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39493. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39494. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39495. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39496. ];
  39497. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39498. var mode = modes_1[_i];
  39499. this[mode] = (mode === modeToEnable);
  39500. }
  39501. };
  39502. return StandardMaterialDefines;
  39503. }(BABYLON.MaterialDefines));
  39504. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39505. var StandardMaterial = /** @class */ (function (_super) {
  39506. __extends(StandardMaterial, _super);
  39507. function StandardMaterial(name, scene) {
  39508. var _this = _super.call(this, name, scene) || this;
  39509. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39510. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39511. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39512. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39513. _this.specularPower = 64;
  39514. _this._useAlphaFromDiffuseTexture = false;
  39515. _this._useEmissiveAsIllumination = false;
  39516. _this._linkEmissiveWithDiffuse = false;
  39517. _this._useSpecularOverAlpha = false;
  39518. _this._useReflectionOverAlpha = false;
  39519. _this._disableLighting = false;
  39520. _this._useObjectSpaceNormalMap = false;
  39521. _this._useParallax = false;
  39522. _this._useParallaxOcclusion = false;
  39523. _this.parallaxScaleBias = 0.05;
  39524. _this._roughness = 0;
  39525. _this.indexOfRefraction = 0.98;
  39526. _this.invertRefractionY = true;
  39527. _this._useLightmapAsShadowmap = false;
  39528. _this._useReflectionFresnelFromSpecular = false;
  39529. _this._useGlossinessFromSpecularMapAlpha = false;
  39530. _this._maxSimultaneousLights = 4;
  39531. /**
  39532. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39533. */
  39534. _this._invertNormalMapX = false;
  39535. /**
  39536. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39537. */
  39538. _this._invertNormalMapY = false;
  39539. /**
  39540. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39541. */
  39542. _this._twoSidedLighting = false;
  39543. _this._renderTargets = new BABYLON.SmartArray(16);
  39544. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39545. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39546. // Setup the default processing configuration to the scene.
  39547. _this._attachImageProcessingConfiguration(null);
  39548. _this.getRenderTargetTextures = function () {
  39549. _this._renderTargets.reset();
  39550. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39551. _this._renderTargets.push(_this._reflectionTexture);
  39552. }
  39553. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39554. _this._renderTargets.push(_this._refractionTexture);
  39555. }
  39556. return _this._renderTargets;
  39557. };
  39558. return _this;
  39559. }
  39560. ;
  39561. ;
  39562. ;
  39563. ;
  39564. ;
  39565. ;
  39566. ;
  39567. ;
  39568. ;
  39569. ;
  39570. ;
  39571. ;
  39572. ;
  39573. ;
  39574. ;
  39575. ;
  39576. ;
  39577. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39578. /**
  39579. * Gets the image processing configuration used either in this material.
  39580. */
  39581. get: function () {
  39582. return this._imageProcessingConfiguration;
  39583. },
  39584. /**
  39585. * Sets the Default image processing configuration used either in the this material.
  39586. *
  39587. * If sets to null, the scene one is in use.
  39588. */
  39589. set: function (value) {
  39590. this._attachImageProcessingConfiguration(value);
  39591. // Ensure the effect will be rebuilt.
  39592. this._markAllSubMeshesAsTexturesDirty();
  39593. },
  39594. enumerable: true,
  39595. configurable: true
  39596. });
  39597. /**
  39598. * Attaches a new image processing configuration to the Standard Material.
  39599. * @param configuration
  39600. */
  39601. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39602. var _this = this;
  39603. if (configuration === this._imageProcessingConfiguration) {
  39604. return;
  39605. }
  39606. // Detaches observer.
  39607. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39608. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39609. }
  39610. // Pick the scene configuration if needed.
  39611. if (!configuration) {
  39612. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39613. }
  39614. else {
  39615. this._imageProcessingConfiguration = configuration;
  39616. }
  39617. // Attaches observer.
  39618. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39619. _this._markAllSubMeshesAsImageProcessingDirty();
  39620. });
  39621. };
  39622. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39623. /**
  39624. * Gets wether the color curves effect is enabled.
  39625. */
  39626. get: function () {
  39627. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39628. },
  39629. /**
  39630. * Sets wether the color curves effect is enabled.
  39631. */
  39632. set: function (value) {
  39633. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39634. },
  39635. enumerable: true,
  39636. configurable: true
  39637. });
  39638. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39639. /**
  39640. * Gets wether the color grading effect is enabled.
  39641. */
  39642. get: function () {
  39643. return this.imageProcessingConfiguration.colorGradingEnabled;
  39644. },
  39645. /**
  39646. * Gets wether the color grading effect is enabled.
  39647. */
  39648. set: function (value) {
  39649. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39650. },
  39651. enumerable: true,
  39652. configurable: true
  39653. });
  39654. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39655. /**
  39656. * Gets wether tonemapping is enabled or not.
  39657. */
  39658. get: function () {
  39659. return this._imageProcessingConfiguration.toneMappingEnabled;
  39660. },
  39661. /**
  39662. * Sets wether tonemapping is enabled or not
  39663. */
  39664. set: function (value) {
  39665. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39666. },
  39667. enumerable: true,
  39668. configurable: true
  39669. });
  39670. ;
  39671. ;
  39672. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39673. /**
  39674. * The camera exposure used on this material.
  39675. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39676. * This corresponds to a photographic exposure.
  39677. */
  39678. get: function () {
  39679. return this._imageProcessingConfiguration.exposure;
  39680. },
  39681. /**
  39682. * The camera exposure used on this material.
  39683. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39684. * This corresponds to a photographic exposure.
  39685. */
  39686. set: function (value) {
  39687. this._imageProcessingConfiguration.exposure = value;
  39688. },
  39689. enumerable: true,
  39690. configurable: true
  39691. });
  39692. ;
  39693. ;
  39694. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39695. /**
  39696. * Gets The camera contrast used on this material.
  39697. */
  39698. get: function () {
  39699. return this._imageProcessingConfiguration.contrast;
  39700. },
  39701. /**
  39702. * Sets The camera contrast used on this material.
  39703. */
  39704. set: function (value) {
  39705. this._imageProcessingConfiguration.contrast = value;
  39706. },
  39707. enumerable: true,
  39708. configurable: true
  39709. });
  39710. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39711. /**
  39712. * Gets the Color Grading 2D Lookup Texture.
  39713. */
  39714. get: function () {
  39715. return this._imageProcessingConfiguration.colorGradingTexture;
  39716. },
  39717. /**
  39718. * Sets the Color Grading 2D Lookup Texture.
  39719. */
  39720. set: function (value) {
  39721. this._imageProcessingConfiguration.colorGradingTexture = value;
  39722. },
  39723. enumerable: true,
  39724. configurable: true
  39725. });
  39726. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39727. /**
  39728. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39729. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39730. * 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;
  39731. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39732. */
  39733. get: function () {
  39734. return this._imageProcessingConfiguration.colorCurves;
  39735. },
  39736. /**
  39737. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39738. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39739. * 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;
  39740. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39741. */
  39742. set: function (value) {
  39743. this._imageProcessingConfiguration.colorCurves = value;
  39744. },
  39745. enumerable: true,
  39746. configurable: true
  39747. });
  39748. StandardMaterial.prototype.getClassName = function () {
  39749. return "StandardMaterial";
  39750. };
  39751. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39752. get: function () {
  39753. return this._useLogarithmicDepth;
  39754. },
  39755. set: function (value) {
  39756. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39757. this._markAllSubMeshesAsMiscDirty();
  39758. },
  39759. enumerable: true,
  39760. configurable: true
  39761. });
  39762. StandardMaterial.prototype.needAlphaBlending = function () {
  39763. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39764. };
  39765. StandardMaterial.prototype.needAlphaTesting = function () {
  39766. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39767. };
  39768. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39769. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39770. };
  39771. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39772. return this._diffuseTexture;
  39773. };
  39774. /**
  39775. * Child classes can use it to update shaders
  39776. */
  39777. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39778. if (useInstances === void 0) { useInstances = false; }
  39779. if (subMesh.effect && this.isFrozen) {
  39780. if (this._wasPreviouslyReady && subMesh.effect) {
  39781. return true;
  39782. }
  39783. }
  39784. if (!subMesh._materialDefines) {
  39785. subMesh._materialDefines = new StandardMaterialDefines();
  39786. }
  39787. var scene = this.getScene();
  39788. var defines = subMesh._materialDefines;
  39789. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39790. if (defines._renderId === scene.getRenderId()) {
  39791. return true;
  39792. }
  39793. }
  39794. var engine = scene.getEngine();
  39795. // Lights
  39796. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39797. // Textures
  39798. if (defines._areTexturesDirty) {
  39799. defines._needUVs = false;
  39800. defines.MAINUV1 = false;
  39801. defines.MAINUV2 = false;
  39802. if (scene.texturesEnabled) {
  39803. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39804. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39805. return false;
  39806. }
  39807. else {
  39808. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39809. }
  39810. }
  39811. else {
  39812. defines.DIFFUSE = false;
  39813. }
  39814. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39815. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39816. return false;
  39817. }
  39818. else {
  39819. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39820. }
  39821. }
  39822. else {
  39823. defines.AMBIENT = false;
  39824. }
  39825. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39826. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39827. return false;
  39828. }
  39829. else {
  39830. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39831. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39832. }
  39833. }
  39834. else {
  39835. defines.OPACITY = false;
  39836. }
  39837. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39838. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39839. return false;
  39840. }
  39841. else {
  39842. defines._needNormals = true;
  39843. defines.REFLECTION = true;
  39844. defines.ROUGHNESS = (this._roughness > 0);
  39845. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39846. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39847. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39848. switch (this._reflectionTexture.coordinatesMode) {
  39849. case BABYLON.Texture.CUBIC_MODE:
  39850. case BABYLON.Texture.INVCUBIC_MODE:
  39851. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39852. break;
  39853. case BABYLON.Texture.EXPLICIT_MODE:
  39854. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39855. break;
  39856. case BABYLON.Texture.PLANAR_MODE:
  39857. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39858. break;
  39859. case BABYLON.Texture.PROJECTION_MODE:
  39860. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39861. break;
  39862. case BABYLON.Texture.SKYBOX_MODE:
  39863. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39864. break;
  39865. case BABYLON.Texture.SPHERICAL_MODE:
  39866. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39867. break;
  39868. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39869. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39870. break;
  39871. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39872. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39873. break;
  39874. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39875. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39876. break;
  39877. }
  39878. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39879. }
  39880. }
  39881. else {
  39882. defines.REFLECTION = false;
  39883. }
  39884. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39885. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39886. return false;
  39887. }
  39888. else {
  39889. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39890. }
  39891. }
  39892. else {
  39893. defines.EMISSIVE = false;
  39894. }
  39895. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39896. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39897. return false;
  39898. }
  39899. else {
  39900. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39901. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39902. }
  39903. }
  39904. else {
  39905. defines.LIGHTMAP = false;
  39906. }
  39907. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39908. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39909. return false;
  39910. }
  39911. else {
  39912. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39913. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39914. }
  39915. }
  39916. else {
  39917. defines.SPECULAR = false;
  39918. }
  39919. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39920. // Bump texure can not be not blocking.
  39921. if (!this._bumpTexture.isReady()) {
  39922. return false;
  39923. }
  39924. else {
  39925. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39926. defines.PARALLAX = this._useParallax;
  39927. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39928. }
  39929. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39930. }
  39931. else {
  39932. defines.BUMP = false;
  39933. }
  39934. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39935. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39936. return false;
  39937. }
  39938. else {
  39939. defines._needUVs = true;
  39940. defines.REFRACTION = true;
  39941. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39942. }
  39943. }
  39944. else {
  39945. defines.REFRACTION = false;
  39946. }
  39947. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39948. }
  39949. else {
  39950. defines.DIFFUSE = false;
  39951. defines.AMBIENT = false;
  39952. defines.OPACITY = false;
  39953. defines.REFLECTION = false;
  39954. defines.EMISSIVE = false;
  39955. defines.LIGHTMAP = false;
  39956. defines.BUMP = false;
  39957. defines.REFRACTION = false;
  39958. }
  39959. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39960. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39961. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39962. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39963. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39964. }
  39965. if (defines._areImageProcessingDirty) {
  39966. if (!this._imageProcessingConfiguration.isReady()) {
  39967. return false;
  39968. }
  39969. this._imageProcessingConfiguration.prepareDefines(defines);
  39970. }
  39971. if (defines._areFresnelDirty) {
  39972. if (StandardMaterial.FresnelEnabled) {
  39973. // Fresnel
  39974. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39975. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39976. this._reflectionFresnelParameters) {
  39977. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39978. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39979. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39980. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39981. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39982. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39983. defines._needNormals = true;
  39984. defines.FRESNEL = true;
  39985. }
  39986. }
  39987. else {
  39988. defines.FRESNEL = false;
  39989. }
  39990. }
  39991. // Misc.
  39992. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39993. // Attribs
  39994. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39995. // Values that need to be evaluated on every frame
  39996. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39997. // Get correct effect
  39998. if (defines.isDirty) {
  39999. defines.markAsProcessed();
  40000. scene.resetCachedMaterial();
  40001. // Fallbacks
  40002. var fallbacks = new BABYLON.EffectFallbacks();
  40003. if (defines.REFLECTION) {
  40004. fallbacks.addFallback(0, "REFLECTION");
  40005. }
  40006. if (defines.SPECULAR) {
  40007. fallbacks.addFallback(0, "SPECULAR");
  40008. }
  40009. if (defines.BUMP) {
  40010. fallbacks.addFallback(0, "BUMP");
  40011. }
  40012. if (defines.PARALLAX) {
  40013. fallbacks.addFallback(1, "PARALLAX");
  40014. }
  40015. if (defines.PARALLAXOCCLUSION) {
  40016. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40017. }
  40018. if (defines.SPECULAROVERALPHA) {
  40019. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40020. }
  40021. if (defines.FOG) {
  40022. fallbacks.addFallback(1, "FOG");
  40023. }
  40024. if (defines.POINTSIZE) {
  40025. fallbacks.addFallback(0, "POINTSIZE");
  40026. }
  40027. if (defines.LOGARITHMICDEPTH) {
  40028. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40029. }
  40030. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40031. if (defines.SPECULARTERM) {
  40032. fallbacks.addFallback(0, "SPECULARTERM");
  40033. }
  40034. if (defines.DIFFUSEFRESNEL) {
  40035. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40036. }
  40037. if (defines.OPACITYFRESNEL) {
  40038. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40039. }
  40040. if (defines.REFLECTIONFRESNEL) {
  40041. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40042. }
  40043. if (defines.EMISSIVEFRESNEL) {
  40044. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40045. }
  40046. if (defines.FRESNEL) {
  40047. fallbacks.addFallback(4, "FRESNEL");
  40048. }
  40049. //Attributes
  40050. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40051. if (defines.NORMAL) {
  40052. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40053. }
  40054. if (defines.UV1) {
  40055. attribs.push(BABYLON.VertexBuffer.UVKind);
  40056. }
  40057. if (defines.UV2) {
  40058. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40059. }
  40060. if (defines.VERTEXCOLOR) {
  40061. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40062. }
  40063. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40064. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40065. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40066. var shaderName = "default";
  40067. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40068. "vFogInfos", "vFogColor", "pointSize",
  40069. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40070. "mBones",
  40071. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40072. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40073. "vReflectionPosition", "vReflectionSize",
  40074. "logarithmicDepthConstant", "vTangentSpaceParams"
  40075. ];
  40076. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40077. var uniformBuffers = ["Material", "Scene"];
  40078. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40079. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40080. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40081. uniformsNames: uniforms,
  40082. uniformBuffersNames: uniformBuffers,
  40083. samplers: samplers,
  40084. defines: defines,
  40085. maxSimultaneousLights: this._maxSimultaneousLights
  40086. });
  40087. if (this.customShaderNameResolve) {
  40088. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40089. }
  40090. var join = defines.toString();
  40091. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40092. attributes: attribs,
  40093. uniformsNames: uniforms,
  40094. uniformBuffersNames: uniformBuffers,
  40095. samplers: samplers,
  40096. defines: join,
  40097. fallbacks: fallbacks,
  40098. onCompiled: this.onCompiled,
  40099. onError: this.onError,
  40100. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40101. }, engine), defines);
  40102. this.buildUniformLayout();
  40103. }
  40104. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40105. return false;
  40106. }
  40107. defines._renderId = scene.getRenderId();
  40108. this._wasPreviouslyReady = true;
  40109. return true;
  40110. };
  40111. StandardMaterial.prototype.buildUniformLayout = function () {
  40112. // Order is important !
  40113. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40114. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40115. this._uniformBuffer.addUniform("opacityParts", 4);
  40116. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40117. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40118. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40119. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40120. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40121. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40122. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40123. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40124. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40125. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40126. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40127. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40128. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40129. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40130. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40131. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40132. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40133. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40134. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40135. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40136. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40137. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40138. this._uniformBuffer.addUniform("specularMatrix", 16);
  40139. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40140. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40141. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40142. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40143. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40144. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40145. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40146. this._uniformBuffer.addUniform("pointSize", 1);
  40147. this._uniformBuffer.create();
  40148. };
  40149. StandardMaterial.prototype.unbind = function () {
  40150. if (this._activeEffect) {
  40151. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40152. this._activeEffect.setTexture("reflection2DSampler", null);
  40153. }
  40154. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40155. this._activeEffect.setTexture("refraction2DSampler", null);
  40156. }
  40157. }
  40158. _super.prototype.unbind.call(this);
  40159. };
  40160. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40161. var scene = this.getScene();
  40162. var defines = subMesh._materialDefines;
  40163. if (!defines) {
  40164. return;
  40165. }
  40166. var effect = subMesh.effect;
  40167. if (!effect) {
  40168. return;
  40169. }
  40170. this._activeEffect = effect;
  40171. // Matrices
  40172. this.bindOnlyWorldMatrix(world);
  40173. // Normal Matrix
  40174. if (defines.OBJECTSPACE_NORMALMAP) {
  40175. world.toNormalMatrix(this._normalMatrix);
  40176. this.bindOnlyNormalMatrix(this._normalMatrix);
  40177. }
  40178. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40179. // Bones
  40180. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40181. if (mustRebind) {
  40182. this._uniformBuffer.bindToEffect(effect, "Material");
  40183. this.bindViewProjection(effect);
  40184. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40185. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40186. // Fresnel
  40187. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40188. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40189. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40190. }
  40191. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40192. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40193. }
  40194. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40195. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40196. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40197. }
  40198. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40199. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40200. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40201. }
  40202. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40203. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40204. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40205. }
  40206. }
  40207. // Textures
  40208. if (scene.texturesEnabled) {
  40209. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40210. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40211. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40212. }
  40213. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40214. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40215. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40216. }
  40217. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40218. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40219. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40220. }
  40221. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40222. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40223. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40224. if (this._reflectionTexture.boundingBoxSize) {
  40225. var cubeTexture = this._reflectionTexture;
  40226. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40227. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40228. }
  40229. }
  40230. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40231. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40232. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40233. }
  40234. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40235. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40236. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40237. }
  40238. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40239. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40240. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40241. }
  40242. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40243. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40244. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40245. if (scene._mirroredCameraPosition) {
  40246. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40247. }
  40248. else {
  40249. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40250. }
  40251. }
  40252. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40253. var depth = 1.0;
  40254. if (!this._refractionTexture.isCube) {
  40255. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40256. if (this._refractionTexture.depth) {
  40257. depth = this._refractionTexture.depth;
  40258. }
  40259. }
  40260. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40261. }
  40262. }
  40263. // Point size
  40264. if (this.pointsCloud) {
  40265. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40266. }
  40267. if (defines.SPECULARTERM) {
  40268. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40269. }
  40270. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40271. // Diffuse
  40272. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40273. }
  40274. // Textures
  40275. if (scene.texturesEnabled) {
  40276. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40277. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40278. }
  40279. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40280. effect.setTexture("ambientSampler", this._ambientTexture);
  40281. }
  40282. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40283. effect.setTexture("opacitySampler", this._opacityTexture);
  40284. }
  40285. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40286. if (this._reflectionTexture.isCube) {
  40287. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40288. }
  40289. else {
  40290. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40291. }
  40292. }
  40293. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40294. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40295. }
  40296. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40297. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40298. }
  40299. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40300. effect.setTexture("specularSampler", this._specularTexture);
  40301. }
  40302. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40303. effect.setTexture("bumpSampler", this._bumpTexture);
  40304. }
  40305. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40306. var depth = 1.0;
  40307. if (this._refractionTexture.isCube) {
  40308. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40309. }
  40310. else {
  40311. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40312. }
  40313. }
  40314. }
  40315. // Clip plane
  40316. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40317. // Colors
  40318. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40319. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40320. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40321. }
  40322. if (mustRebind || !this.isFrozen) {
  40323. // Lights
  40324. if (scene.lightsEnabled && !this._disableLighting) {
  40325. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40326. }
  40327. // View
  40328. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40329. this.bindView(effect);
  40330. }
  40331. // Fog
  40332. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40333. // Morph targets
  40334. if (defines.NUM_MORPH_INFLUENCERS) {
  40335. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40336. }
  40337. // Log. depth
  40338. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40339. // image processing
  40340. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40341. this._imageProcessingConfiguration.bind(this._activeEffect);
  40342. }
  40343. }
  40344. this._uniformBuffer.update();
  40345. this._afterBind(mesh, this._activeEffect);
  40346. };
  40347. StandardMaterial.prototype.getAnimatables = function () {
  40348. var results = [];
  40349. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40350. results.push(this._diffuseTexture);
  40351. }
  40352. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40353. results.push(this._ambientTexture);
  40354. }
  40355. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40356. results.push(this._opacityTexture);
  40357. }
  40358. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40359. results.push(this._reflectionTexture);
  40360. }
  40361. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40362. results.push(this._emissiveTexture);
  40363. }
  40364. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40365. results.push(this._specularTexture);
  40366. }
  40367. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40368. results.push(this._bumpTexture);
  40369. }
  40370. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40371. results.push(this._lightmapTexture);
  40372. }
  40373. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40374. results.push(this._refractionTexture);
  40375. }
  40376. return results;
  40377. };
  40378. StandardMaterial.prototype.getActiveTextures = function () {
  40379. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40380. if (this._diffuseTexture) {
  40381. activeTextures.push(this._diffuseTexture);
  40382. }
  40383. if (this._ambientTexture) {
  40384. activeTextures.push(this._ambientTexture);
  40385. }
  40386. if (this._opacityTexture) {
  40387. activeTextures.push(this._opacityTexture);
  40388. }
  40389. if (this._reflectionTexture) {
  40390. activeTextures.push(this._reflectionTexture);
  40391. }
  40392. if (this._emissiveTexture) {
  40393. activeTextures.push(this._emissiveTexture);
  40394. }
  40395. if (this._specularTexture) {
  40396. activeTextures.push(this._specularTexture);
  40397. }
  40398. if (this._bumpTexture) {
  40399. activeTextures.push(this._bumpTexture);
  40400. }
  40401. if (this._lightmapTexture) {
  40402. activeTextures.push(this._lightmapTexture);
  40403. }
  40404. if (this._refractionTexture) {
  40405. activeTextures.push(this._refractionTexture);
  40406. }
  40407. return activeTextures;
  40408. };
  40409. StandardMaterial.prototype.hasTexture = function (texture) {
  40410. if (_super.prototype.hasTexture.call(this, texture)) {
  40411. return true;
  40412. }
  40413. if (this._diffuseTexture === texture) {
  40414. return true;
  40415. }
  40416. if (this._ambientTexture === texture) {
  40417. return true;
  40418. }
  40419. if (this._opacityTexture === texture) {
  40420. return true;
  40421. }
  40422. if (this._reflectionTexture === texture) {
  40423. return true;
  40424. }
  40425. if (this._emissiveTexture === texture) {
  40426. return true;
  40427. }
  40428. if (this._specularTexture === texture) {
  40429. return true;
  40430. }
  40431. if (this._bumpTexture === texture) {
  40432. return true;
  40433. }
  40434. if (this._lightmapTexture === texture) {
  40435. return true;
  40436. }
  40437. if (this._refractionTexture === texture) {
  40438. return true;
  40439. }
  40440. return false;
  40441. };
  40442. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40443. if (forceDisposeTextures) {
  40444. if (this._diffuseTexture) {
  40445. this._diffuseTexture.dispose();
  40446. }
  40447. if (this._ambientTexture) {
  40448. this._ambientTexture.dispose();
  40449. }
  40450. if (this._opacityTexture) {
  40451. this._opacityTexture.dispose();
  40452. }
  40453. if (this._reflectionTexture) {
  40454. this._reflectionTexture.dispose();
  40455. }
  40456. if (this._emissiveTexture) {
  40457. this._emissiveTexture.dispose();
  40458. }
  40459. if (this._specularTexture) {
  40460. this._specularTexture.dispose();
  40461. }
  40462. if (this._bumpTexture) {
  40463. this._bumpTexture.dispose();
  40464. }
  40465. if (this._lightmapTexture) {
  40466. this._lightmapTexture.dispose();
  40467. }
  40468. if (this._refractionTexture) {
  40469. this._refractionTexture.dispose();
  40470. }
  40471. }
  40472. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40473. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40474. }
  40475. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40476. };
  40477. StandardMaterial.prototype.clone = function (name) {
  40478. var _this = this;
  40479. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40480. result.name = name;
  40481. result.id = name;
  40482. return result;
  40483. };
  40484. StandardMaterial.prototype.serialize = function () {
  40485. return BABYLON.SerializationHelper.Serialize(this);
  40486. };
  40487. // Statics
  40488. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40489. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40490. };
  40491. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40492. get: function () {
  40493. return StandardMaterial._DiffuseTextureEnabled;
  40494. },
  40495. set: function (value) {
  40496. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40497. return;
  40498. }
  40499. StandardMaterial._DiffuseTextureEnabled = value;
  40500. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40501. },
  40502. enumerable: true,
  40503. configurable: true
  40504. });
  40505. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40506. get: function () {
  40507. return StandardMaterial._AmbientTextureEnabled;
  40508. },
  40509. set: function (value) {
  40510. if (StandardMaterial._AmbientTextureEnabled === value) {
  40511. return;
  40512. }
  40513. StandardMaterial._AmbientTextureEnabled = value;
  40514. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40515. },
  40516. enumerable: true,
  40517. configurable: true
  40518. });
  40519. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40520. get: function () {
  40521. return StandardMaterial._OpacityTextureEnabled;
  40522. },
  40523. set: function (value) {
  40524. if (StandardMaterial._OpacityTextureEnabled === value) {
  40525. return;
  40526. }
  40527. StandardMaterial._OpacityTextureEnabled = value;
  40528. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40529. },
  40530. enumerable: true,
  40531. configurable: true
  40532. });
  40533. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40534. get: function () {
  40535. return StandardMaterial._ReflectionTextureEnabled;
  40536. },
  40537. set: function (value) {
  40538. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40539. return;
  40540. }
  40541. StandardMaterial._ReflectionTextureEnabled = value;
  40542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40543. },
  40544. enumerable: true,
  40545. configurable: true
  40546. });
  40547. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40548. get: function () {
  40549. return StandardMaterial._EmissiveTextureEnabled;
  40550. },
  40551. set: function (value) {
  40552. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40553. return;
  40554. }
  40555. StandardMaterial._EmissiveTextureEnabled = value;
  40556. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40562. get: function () {
  40563. return StandardMaterial._SpecularTextureEnabled;
  40564. },
  40565. set: function (value) {
  40566. if (StandardMaterial._SpecularTextureEnabled === value) {
  40567. return;
  40568. }
  40569. StandardMaterial._SpecularTextureEnabled = value;
  40570. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40571. },
  40572. enumerable: true,
  40573. configurable: true
  40574. });
  40575. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40576. get: function () {
  40577. return StandardMaterial._BumpTextureEnabled;
  40578. },
  40579. set: function (value) {
  40580. if (StandardMaterial._BumpTextureEnabled === value) {
  40581. return;
  40582. }
  40583. StandardMaterial._BumpTextureEnabled = value;
  40584. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40585. },
  40586. enumerable: true,
  40587. configurable: true
  40588. });
  40589. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40590. get: function () {
  40591. return StandardMaterial._LightmapTextureEnabled;
  40592. },
  40593. set: function (value) {
  40594. if (StandardMaterial._LightmapTextureEnabled === value) {
  40595. return;
  40596. }
  40597. StandardMaterial._LightmapTextureEnabled = value;
  40598. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40599. },
  40600. enumerable: true,
  40601. configurable: true
  40602. });
  40603. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40604. get: function () {
  40605. return StandardMaterial._RefractionTextureEnabled;
  40606. },
  40607. set: function (value) {
  40608. if (StandardMaterial._RefractionTextureEnabled === value) {
  40609. return;
  40610. }
  40611. StandardMaterial._RefractionTextureEnabled = value;
  40612. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40613. },
  40614. enumerable: true,
  40615. configurable: true
  40616. });
  40617. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40618. get: function () {
  40619. return StandardMaterial._ColorGradingTextureEnabled;
  40620. },
  40621. set: function (value) {
  40622. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40623. return;
  40624. }
  40625. StandardMaterial._ColorGradingTextureEnabled = value;
  40626. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40627. },
  40628. enumerable: true,
  40629. configurable: true
  40630. });
  40631. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40632. get: function () {
  40633. return StandardMaterial._FresnelEnabled;
  40634. },
  40635. set: function (value) {
  40636. if (StandardMaterial._FresnelEnabled === value) {
  40637. return;
  40638. }
  40639. StandardMaterial._FresnelEnabled = value;
  40640. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. // Flags used to enable or disable a type of texture for all Standard Materials
  40646. StandardMaterial._DiffuseTextureEnabled = true;
  40647. StandardMaterial._AmbientTextureEnabled = true;
  40648. StandardMaterial._OpacityTextureEnabled = true;
  40649. StandardMaterial._ReflectionTextureEnabled = true;
  40650. StandardMaterial._EmissiveTextureEnabled = true;
  40651. StandardMaterial._SpecularTextureEnabled = true;
  40652. StandardMaterial._BumpTextureEnabled = true;
  40653. StandardMaterial._LightmapTextureEnabled = true;
  40654. StandardMaterial._RefractionTextureEnabled = true;
  40655. StandardMaterial._ColorGradingTextureEnabled = true;
  40656. StandardMaterial._FresnelEnabled = true;
  40657. __decorate([
  40658. BABYLON.serializeAsTexture("diffuseTexture")
  40659. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40660. __decorate([
  40661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40662. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40663. __decorate([
  40664. BABYLON.serializeAsTexture("ambientTexture")
  40665. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40666. __decorate([
  40667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40668. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40669. __decorate([
  40670. BABYLON.serializeAsTexture("opacityTexture")
  40671. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40672. __decorate([
  40673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40674. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40675. __decorate([
  40676. BABYLON.serializeAsTexture("reflectionTexture")
  40677. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40678. __decorate([
  40679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40680. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40681. __decorate([
  40682. BABYLON.serializeAsTexture("emissiveTexture")
  40683. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40684. __decorate([
  40685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40686. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40687. __decorate([
  40688. BABYLON.serializeAsTexture("specularTexture")
  40689. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40690. __decorate([
  40691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40692. ], StandardMaterial.prototype, "specularTexture", void 0);
  40693. __decorate([
  40694. BABYLON.serializeAsTexture("bumpTexture")
  40695. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40696. __decorate([
  40697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40698. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40699. __decorate([
  40700. BABYLON.serializeAsTexture("lightmapTexture")
  40701. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40702. __decorate([
  40703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40704. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40705. __decorate([
  40706. BABYLON.serializeAsTexture("refractionTexture")
  40707. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40708. __decorate([
  40709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40710. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40711. __decorate([
  40712. BABYLON.serializeAsColor3("ambient")
  40713. ], StandardMaterial.prototype, "ambientColor", void 0);
  40714. __decorate([
  40715. BABYLON.serializeAsColor3("diffuse")
  40716. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40717. __decorate([
  40718. BABYLON.serializeAsColor3("specular")
  40719. ], StandardMaterial.prototype, "specularColor", void 0);
  40720. __decorate([
  40721. BABYLON.serializeAsColor3("emissive")
  40722. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40723. __decorate([
  40724. BABYLON.serialize()
  40725. ], StandardMaterial.prototype, "specularPower", void 0);
  40726. __decorate([
  40727. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40728. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40729. __decorate([
  40730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40731. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40732. __decorate([
  40733. BABYLON.serialize("useEmissiveAsIllumination")
  40734. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40735. __decorate([
  40736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40737. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40738. __decorate([
  40739. BABYLON.serialize("linkEmissiveWithDiffuse")
  40740. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40741. __decorate([
  40742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40743. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40744. __decorate([
  40745. BABYLON.serialize("useSpecularOverAlpha")
  40746. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40747. __decorate([
  40748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40749. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40750. __decorate([
  40751. BABYLON.serialize("useReflectionOverAlpha")
  40752. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40753. __decorate([
  40754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40755. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40756. __decorate([
  40757. BABYLON.serialize("disableLighting")
  40758. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40759. __decorate([
  40760. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40761. ], StandardMaterial.prototype, "disableLighting", void 0);
  40762. __decorate([
  40763. BABYLON.serialize("useObjectSpaceNormalMap")
  40764. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40765. __decorate([
  40766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40767. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40768. __decorate([
  40769. BABYLON.serialize("useParallax")
  40770. ], StandardMaterial.prototype, "_useParallax", void 0);
  40771. __decorate([
  40772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40773. ], StandardMaterial.prototype, "useParallax", void 0);
  40774. __decorate([
  40775. BABYLON.serialize("useParallaxOcclusion")
  40776. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40777. __decorate([
  40778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40779. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40780. __decorate([
  40781. BABYLON.serialize()
  40782. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40783. __decorate([
  40784. BABYLON.serialize("roughness")
  40785. ], StandardMaterial.prototype, "_roughness", void 0);
  40786. __decorate([
  40787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40788. ], StandardMaterial.prototype, "roughness", void 0);
  40789. __decorate([
  40790. BABYLON.serialize()
  40791. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40792. __decorate([
  40793. BABYLON.serialize()
  40794. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40795. __decorate([
  40796. BABYLON.serialize("useLightmapAsShadowmap")
  40797. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40798. __decorate([
  40799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40800. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40801. __decorate([
  40802. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40803. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40804. __decorate([
  40805. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40806. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40807. __decorate([
  40808. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40809. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40810. __decorate([
  40811. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40812. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40813. __decorate([
  40814. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40815. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40816. __decorate([
  40817. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40818. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40819. __decorate([
  40820. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40821. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40822. __decorate([
  40823. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40824. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40825. __decorate([
  40826. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40827. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40828. __decorate([
  40829. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40830. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40831. __decorate([
  40832. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40833. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40834. __decorate([
  40835. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40836. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40837. __decorate([
  40838. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40839. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40840. __decorate([
  40841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40842. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40843. __decorate([
  40844. BABYLON.serialize("maxSimultaneousLights")
  40845. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40846. __decorate([
  40847. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40848. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40849. __decorate([
  40850. BABYLON.serialize("invertNormalMapX")
  40851. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40852. __decorate([
  40853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40854. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40855. __decorate([
  40856. BABYLON.serialize("invertNormalMapY")
  40857. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40858. __decorate([
  40859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40860. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40861. __decorate([
  40862. BABYLON.serialize("twoSidedLighting")
  40863. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40864. __decorate([
  40865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40866. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40867. __decorate([
  40868. BABYLON.serialize()
  40869. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40870. return StandardMaterial;
  40871. }(BABYLON.PushMaterial));
  40872. BABYLON.StandardMaterial = StandardMaterial;
  40873. })(BABYLON || (BABYLON = {}));
  40874. //# sourceMappingURL=babylon.standardMaterial.js.map
  40875. "use strict";
  40876. var BABYLON;
  40877. (function (BABYLON) {
  40878. /**
  40879. * Manages the defines for the PBR Material.
  40880. */
  40881. var PBRMaterialDefines = /** @class */ (function (_super) {
  40882. __extends(PBRMaterialDefines, _super);
  40883. /**
  40884. * Initializes the PBR Material defines.
  40885. */
  40886. function PBRMaterialDefines() {
  40887. var _this = _super.call(this) || this;
  40888. _this.PBR = true;
  40889. _this.MAINUV1 = false;
  40890. _this.MAINUV2 = false;
  40891. _this.UV1 = false;
  40892. _this.UV2 = false;
  40893. _this.ALBEDO = false;
  40894. _this.ALBEDODIRECTUV = 0;
  40895. _this.VERTEXCOLOR = false;
  40896. _this.AMBIENT = false;
  40897. _this.AMBIENTDIRECTUV = 0;
  40898. _this.AMBIENTINGRAYSCALE = false;
  40899. _this.OPACITY = false;
  40900. _this.VERTEXALPHA = false;
  40901. _this.OPACITYDIRECTUV = 0;
  40902. _this.OPACITYRGB = false;
  40903. _this.ALPHATEST = false;
  40904. _this.DEPTHPREPASS = false;
  40905. _this.ALPHABLEND = false;
  40906. _this.ALPHAFROMALBEDO = false;
  40907. _this.ALPHATESTVALUE = "0.5";
  40908. _this.SPECULAROVERALPHA = false;
  40909. _this.RADIANCEOVERALPHA = false;
  40910. _this.ALPHAFRESNEL = false;
  40911. _this.LINEARALPHAFRESNEL = false;
  40912. _this.PREMULTIPLYALPHA = false;
  40913. _this.EMISSIVE = false;
  40914. _this.EMISSIVEDIRECTUV = 0;
  40915. _this.REFLECTIVITY = false;
  40916. _this.REFLECTIVITYDIRECTUV = 0;
  40917. _this.SPECULARTERM = false;
  40918. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40919. _this.MICROSURFACEAUTOMATIC = false;
  40920. _this.LODBASEDMICROSFURACE = false;
  40921. _this.MICROSURFACEMAP = false;
  40922. _this.MICROSURFACEMAPDIRECTUV = 0;
  40923. _this.METALLICWORKFLOW = false;
  40924. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40925. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40926. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40927. _this.AOSTOREINMETALMAPRED = false;
  40928. _this.ENVIRONMENTBRDF = false;
  40929. _this.NORMAL = false;
  40930. _this.TANGENT = false;
  40931. _this.BUMP = false;
  40932. _this.BUMPDIRECTUV = 0;
  40933. _this.OBJECTSPACE_NORMALMAP = false;
  40934. _this.PARALLAX = false;
  40935. _this.PARALLAXOCCLUSION = false;
  40936. _this.NORMALXYSCALE = true;
  40937. _this.LIGHTMAP = false;
  40938. _this.LIGHTMAPDIRECTUV = 0;
  40939. _this.USELIGHTMAPASSHADOWMAP = false;
  40940. _this.GAMMALIGHTMAP = false;
  40941. _this.REFLECTION = false;
  40942. _this.REFLECTIONMAP_3D = false;
  40943. _this.REFLECTIONMAP_SPHERICAL = false;
  40944. _this.REFLECTIONMAP_PLANAR = false;
  40945. _this.REFLECTIONMAP_CUBIC = false;
  40946. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40947. _this.REFLECTIONMAP_PROJECTION = false;
  40948. _this.REFLECTIONMAP_SKYBOX = false;
  40949. _this.REFLECTIONMAP_EXPLICIT = false;
  40950. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40951. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40952. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40953. _this.INVERTCUBICMAP = false;
  40954. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40955. _this.USESPHERICALINVERTEX = false;
  40956. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40957. _this.LODINREFLECTIONALPHA = false;
  40958. _this.GAMMAREFLECTION = false;
  40959. _this.RADIANCEOCCLUSION = false;
  40960. _this.HORIZONOCCLUSION = false;
  40961. _this.REFRACTION = false;
  40962. _this.REFRACTIONMAP_3D = false;
  40963. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40964. _this.LODINREFRACTIONALPHA = false;
  40965. _this.GAMMAREFRACTION = false;
  40966. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40967. _this.INSTANCES = false;
  40968. _this.NUM_BONE_INFLUENCERS = 0;
  40969. _this.BonesPerMesh = 0;
  40970. _this.NONUNIFORMSCALING = false;
  40971. _this.MORPHTARGETS = false;
  40972. _this.MORPHTARGETS_NORMAL = false;
  40973. _this.MORPHTARGETS_TANGENT = false;
  40974. _this.NUM_MORPH_INFLUENCERS = 0;
  40975. _this.IMAGEPROCESSING = false;
  40976. _this.VIGNETTE = false;
  40977. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40978. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40979. _this.TONEMAPPING = false;
  40980. _this.CONTRAST = false;
  40981. _this.COLORCURVES = false;
  40982. _this.COLORGRADING = false;
  40983. _this.COLORGRADING3D = false;
  40984. _this.SAMPLER3DGREENDEPTH = false;
  40985. _this.SAMPLER3DBGRMAP = false;
  40986. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40987. _this.EXPOSURE = false;
  40988. _this.USEPHYSICALLIGHTFALLOFF = false;
  40989. _this.TWOSIDEDLIGHTING = false;
  40990. _this.SHADOWFLOAT = false;
  40991. _this.CLIPPLANE = false;
  40992. _this.POINTSIZE = false;
  40993. _this.FOG = false;
  40994. _this.LOGARITHMICDEPTH = false;
  40995. _this.FORCENORMALFORWARD = false;
  40996. _this.UNLIT = false;
  40997. _this.rebuild();
  40998. return _this;
  40999. }
  41000. /**
  41001. * Resets the PBR Material defines.
  41002. */
  41003. PBRMaterialDefines.prototype.reset = function () {
  41004. _super.prototype.reset.call(this);
  41005. this.ALPHATESTVALUE = "0.5";
  41006. this.PBR = true;
  41007. };
  41008. return PBRMaterialDefines;
  41009. }(BABYLON.MaterialDefines));
  41010. /**
  41011. * The Physically based material base class of BJS.
  41012. *
  41013. * This offers the main features of a standard PBR material.
  41014. * For more information, please refer to the documentation :
  41015. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41016. */
  41017. var PBRBaseMaterial = /** @class */ (function (_super) {
  41018. __extends(PBRBaseMaterial, _super);
  41019. /**
  41020. * Instantiates a new PBRMaterial instance.
  41021. *
  41022. * @param name The material name
  41023. * @param scene The scene the material will be use in.
  41024. */
  41025. function PBRBaseMaterial(name, scene) {
  41026. var _this = _super.call(this, name, scene) || this;
  41027. /**
  41028. * Intensity of the direct lights e.g. the four lights available in your scene.
  41029. * This impacts both the direct diffuse and specular highlights.
  41030. */
  41031. _this._directIntensity = 1.0;
  41032. /**
  41033. * Intensity of the emissive part of the material.
  41034. * This helps controlling the emissive effect without modifying the emissive color.
  41035. */
  41036. _this._emissiveIntensity = 1.0;
  41037. /**
  41038. * Intensity of the environment e.g. how much the environment will light the object
  41039. * either through harmonics for rough material or through the refelction for shiny ones.
  41040. */
  41041. _this._environmentIntensity = 1.0;
  41042. /**
  41043. * This is a special control allowing the reduction of the specular highlights coming from the
  41044. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41045. */
  41046. _this._specularIntensity = 1.0;
  41047. /**
  41048. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41049. */
  41050. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41051. /**
  41052. * Debug Control allowing disabling the bump map on this material.
  41053. */
  41054. _this._disableBumpMap = false;
  41055. /**
  41056. * AKA Occlusion Texture Intensity in other nomenclature.
  41057. */
  41058. _this._ambientTextureStrength = 1.0;
  41059. /**
  41060. * The color of a material in ambient lighting.
  41061. */
  41062. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41063. /**
  41064. * AKA Diffuse Color in other nomenclature.
  41065. */
  41066. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41067. /**
  41068. * AKA Specular Color in other nomenclature.
  41069. */
  41070. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41071. /**
  41072. * The color applied when light is reflected from a material.
  41073. */
  41074. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41075. /**
  41076. * The color applied when light is emitted from a material.
  41077. */
  41078. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41079. /**
  41080. * AKA Glossiness in other nomenclature.
  41081. */
  41082. _this._microSurface = 0.9;
  41083. /**
  41084. * source material index of refraction (IOR)' / 'destination material IOR.
  41085. */
  41086. _this._indexOfRefraction = 0.66;
  41087. /**
  41088. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41089. */
  41090. _this._invertRefractionY = false;
  41091. /**
  41092. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41093. * Materials half opaque for instance using refraction could benefit from this control.
  41094. */
  41095. _this._linkRefractionWithTransparency = false;
  41096. /**
  41097. * Specifies that the material will use the light map as a show map.
  41098. */
  41099. _this._useLightmapAsShadowmap = false;
  41100. /**
  41101. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41102. * makes the reflect vector face the model (under horizon).
  41103. */
  41104. _this._useHorizonOcclusion = true;
  41105. /**
  41106. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41107. * too much the area relying on ambient texture to define their ambient occlusion.
  41108. */
  41109. _this._useRadianceOcclusion = true;
  41110. /**
  41111. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41112. */
  41113. _this._useAlphaFromAlbedoTexture = false;
  41114. /**
  41115. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41116. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41117. */
  41118. _this._useSpecularOverAlpha = true;
  41119. /**
  41120. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41121. */
  41122. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41123. /**
  41124. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41125. */
  41126. _this._useRoughnessFromMetallicTextureAlpha = true;
  41127. /**
  41128. * Specifies if the metallic texture contains the roughness information in its green channel.
  41129. */
  41130. _this._useRoughnessFromMetallicTextureGreen = false;
  41131. /**
  41132. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41133. */
  41134. _this._useMetallnessFromMetallicTextureBlue = false;
  41135. /**
  41136. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41137. */
  41138. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41139. /**
  41140. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41141. */
  41142. _this._useAmbientInGrayScale = false;
  41143. /**
  41144. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41145. * The material will try to infer what glossiness each pixel should be.
  41146. */
  41147. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41148. /**
  41149. * BJS is using an harcoded light falloff based on a manually sets up range.
  41150. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41151. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41152. */
  41153. _this._usePhysicalLightFalloff = true;
  41154. /**
  41155. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41156. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41157. */
  41158. _this._useRadianceOverAlpha = true;
  41159. /**
  41160. * Allows using an object space normal map (instead of tangent space).
  41161. */
  41162. _this._useObjectSpaceNormalMap = false;
  41163. /**
  41164. * Allows using the bump map in parallax mode.
  41165. */
  41166. _this._useParallax = false;
  41167. /**
  41168. * Allows using the bump map in parallax occlusion mode.
  41169. */
  41170. _this._useParallaxOcclusion = false;
  41171. /**
  41172. * Controls the scale bias of the parallax mode.
  41173. */
  41174. _this._parallaxScaleBias = 0.05;
  41175. /**
  41176. * If sets to true, disables all the lights affecting the material.
  41177. */
  41178. _this._disableLighting = false;
  41179. /**
  41180. * Number of Simultaneous lights allowed on the material.
  41181. */
  41182. _this._maxSimultaneousLights = 4;
  41183. /**
  41184. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41185. */
  41186. _this._invertNormalMapX = false;
  41187. /**
  41188. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41189. */
  41190. _this._invertNormalMapY = false;
  41191. /**
  41192. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41193. */
  41194. _this._twoSidedLighting = false;
  41195. /**
  41196. * Defines the alpha limits in alpha test mode.
  41197. */
  41198. _this._alphaCutOff = 0.4;
  41199. /**
  41200. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41201. */
  41202. _this._forceAlphaTest = false;
  41203. /**
  41204. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41205. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41206. */
  41207. _this._useAlphaFresnel = false;
  41208. /**
  41209. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41210. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41211. */
  41212. _this._useLinearAlphaFresnel = false;
  41213. /**
  41214. * The transparency mode of the material.
  41215. */
  41216. _this._transparencyMode = null;
  41217. /**
  41218. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41219. * from cos thetav and roughness:
  41220. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41221. */
  41222. _this._environmentBRDFTexture = null;
  41223. /**
  41224. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41225. */
  41226. _this._forceIrradianceInFragment = false;
  41227. /**
  41228. * Force normal to face away from face.
  41229. */
  41230. _this._forceNormalForward = false;
  41231. /**
  41232. * Stores the available render targets.
  41233. */
  41234. _this._renderTargets = new BABYLON.SmartArray(16);
  41235. /**
  41236. * Sets the global ambient color for the material used in lighting calculations.
  41237. */
  41238. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41239. /**
  41240. * If set to true, no lighting calculations will be applied.
  41241. */
  41242. _this._unlit = false;
  41243. // Setup the default processing configuration to the scene.
  41244. _this._attachImageProcessingConfiguration(null);
  41245. _this.getRenderTargetTextures = function () {
  41246. _this._renderTargets.reset();
  41247. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41248. _this._renderTargets.push(_this._reflectionTexture);
  41249. }
  41250. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41251. _this._renderTargets.push(_this._refractionTexture);
  41252. }
  41253. return _this._renderTargets;
  41254. };
  41255. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41256. return _this;
  41257. }
  41258. /**
  41259. * Attaches a new image processing configuration to the PBR Material.
  41260. * @param configuration
  41261. */
  41262. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41263. var _this = this;
  41264. if (configuration === this._imageProcessingConfiguration) {
  41265. return;
  41266. }
  41267. // Detaches observer.
  41268. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41269. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41270. }
  41271. // Pick the scene configuration if needed.
  41272. if (!configuration) {
  41273. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41274. }
  41275. else {
  41276. this._imageProcessingConfiguration = configuration;
  41277. }
  41278. // Attaches observer.
  41279. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41280. _this._markAllSubMeshesAsImageProcessingDirty();
  41281. });
  41282. };
  41283. /**
  41284. * Gets the name of the material class.
  41285. */
  41286. PBRBaseMaterial.prototype.getClassName = function () {
  41287. return "PBRBaseMaterial";
  41288. };
  41289. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41290. /**
  41291. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41292. */
  41293. get: function () {
  41294. return this._useLogarithmicDepth;
  41295. },
  41296. /**
  41297. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41298. */
  41299. set: function (value) {
  41300. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41301. },
  41302. enumerable: true,
  41303. configurable: true
  41304. });
  41305. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41306. /**
  41307. * Gets the current transparency mode.
  41308. */
  41309. get: function () {
  41310. return this._transparencyMode;
  41311. },
  41312. /**
  41313. * Sets the transparency mode of the material.
  41314. */
  41315. set: function (value) {
  41316. if (this._transparencyMode === value) {
  41317. return;
  41318. }
  41319. this._transparencyMode = value;
  41320. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41321. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41322. },
  41323. enumerable: true,
  41324. configurable: true
  41325. });
  41326. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41327. /**
  41328. * Returns true if alpha blending should be disabled.
  41329. */
  41330. get: function () {
  41331. return (this._linkRefractionWithTransparency ||
  41332. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41333. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41334. },
  41335. enumerable: true,
  41336. configurable: true
  41337. });
  41338. /**
  41339. * Specifies whether or not this material should be rendered in alpha blend mode.
  41340. */
  41341. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41342. if (this._disableAlphaBlending) {
  41343. return false;
  41344. }
  41345. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41346. };
  41347. /**
  41348. * Specifies if the mesh will require alpha blending.
  41349. * @param mesh - BJS mesh.
  41350. */
  41351. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41352. if (this._disableAlphaBlending) {
  41353. return false;
  41354. }
  41355. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41356. };
  41357. /**
  41358. * Specifies whether or not this material should be rendered in alpha test mode.
  41359. */
  41360. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41361. if (this._forceAlphaTest) {
  41362. return true;
  41363. }
  41364. if (this._linkRefractionWithTransparency) {
  41365. return false;
  41366. }
  41367. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41368. };
  41369. /**
  41370. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41371. */
  41372. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41373. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41374. };
  41375. /**
  41376. * Gets the texture used for the alpha test.
  41377. */
  41378. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41379. return this._albedoTexture;
  41380. };
  41381. /**
  41382. * Specifies that the submesh is ready to be used.
  41383. * @param mesh - BJS mesh.
  41384. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41385. * @param useInstances - Specifies that instances should be used.
  41386. * @returns - boolean indicating that the submesh is ready or not.
  41387. */
  41388. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41389. if (subMesh.effect && this.isFrozen) {
  41390. if (this._wasPreviouslyReady) {
  41391. return true;
  41392. }
  41393. }
  41394. if (!subMesh._materialDefines) {
  41395. subMesh._materialDefines = new PBRMaterialDefines();
  41396. }
  41397. var defines = subMesh._materialDefines;
  41398. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41399. if (defines._renderId === this.getScene().getRenderId()) {
  41400. return true;
  41401. }
  41402. }
  41403. var scene = this.getScene();
  41404. var engine = scene.getEngine();
  41405. if (defines._areTexturesDirty) {
  41406. if (scene.texturesEnabled) {
  41407. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41408. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41409. return false;
  41410. }
  41411. }
  41412. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41413. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41414. return false;
  41415. }
  41416. }
  41417. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41418. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41419. return false;
  41420. }
  41421. }
  41422. var reflectionTexture = this._getReflectionTexture();
  41423. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41424. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41425. return false;
  41426. }
  41427. }
  41428. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41429. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41430. return false;
  41431. }
  41432. }
  41433. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41434. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41435. return false;
  41436. }
  41437. }
  41438. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41439. if (this._metallicTexture) {
  41440. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41441. return false;
  41442. }
  41443. }
  41444. else if (this._reflectivityTexture) {
  41445. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41446. return false;
  41447. }
  41448. }
  41449. if (this._microSurfaceTexture) {
  41450. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41451. return false;
  41452. }
  41453. }
  41454. }
  41455. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41456. // Bump texture cannot be not blocking.
  41457. if (!this._bumpTexture.isReady()) {
  41458. return false;
  41459. }
  41460. }
  41461. var refractionTexture = this._getRefractionTexture();
  41462. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41463. if (!refractionTexture.isReadyOrNotBlocking()) {
  41464. return false;
  41465. }
  41466. }
  41467. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41468. // This is blocking.
  41469. if (!this._environmentBRDFTexture.isReady()) {
  41470. return false;
  41471. }
  41472. }
  41473. }
  41474. }
  41475. if (defines._areImageProcessingDirty) {
  41476. if (!this._imageProcessingConfiguration.isReady()) {
  41477. return false;
  41478. }
  41479. }
  41480. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41481. mesh.createNormals(true);
  41482. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41483. }
  41484. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41485. if (effect) {
  41486. scene.resetCachedMaterial();
  41487. subMesh.setEffect(effect, defines);
  41488. this.buildUniformLayout();
  41489. }
  41490. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41491. return false;
  41492. }
  41493. defines._renderId = scene.getRenderId();
  41494. this._wasPreviouslyReady = true;
  41495. return true;
  41496. };
  41497. /**
  41498. * Specifies if the material uses metallic roughness workflow.
  41499. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41500. */
  41501. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41502. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41503. return true;
  41504. }
  41505. return false;
  41506. };
  41507. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41508. if (onCompiled === void 0) { onCompiled = null; }
  41509. if (onError === void 0) { onError = null; }
  41510. if (useInstances === void 0) { useInstances = null; }
  41511. if (useClipPlane === void 0) { useClipPlane = null; }
  41512. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41513. if (!defines.isDirty) {
  41514. return null;
  41515. }
  41516. defines.markAsProcessed();
  41517. var scene = this.getScene();
  41518. var engine = scene.getEngine();
  41519. // Fallbacks
  41520. var fallbacks = new BABYLON.EffectFallbacks();
  41521. var fallbackRank = 0;
  41522. if (defines.USESPHERICALINVERTEX) {
  41523. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41524. }
  41525. if (defines.FOG) {
  41526. fallbacks.addFallback(fallbackRank, "FOG");
  41527. }
  41528. if (defines.POINTSIZE) {
  41529. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41530. }
  41531. if (defines.LOGARITHMICDEPTH) {
  41532. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41533. }
  41534. if (defines.PARALLAX) {
  41535. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41536. }
  41537. if (defines.PARALLAXOCCLUSION) {
  41538. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41539. }
  41540. if (defines.ENVIRONMENTBRDF) {
  41541. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41542. }
  41543. if (defines.TANGENT) {
  41544. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41545. }
  41546. if (defines.BUMP) {
  41547. fallbacks.addFallback(fallbackRank++, "BUMP");
  41548. }
  41549. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41550. if (defines.SPECULARTERM) {
  41551. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41552. }
  41553. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41554. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41555. }
  41556. if (defines.LIGHTMAP) {
  41557. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41558. }
  41559. if (defines.NORMAL) {
  41560. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41561. }
  41562. if (defines.AMBIENT) {
  41563. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41564. }
  41565. if (defines.EMISSIVE) {
  41566. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41567. }
  41568. if (defines.VERTEXCOLOR) {
  41569. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41570. }
  41571. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41572. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41573. }
  41574. if (defines.MORPHTARGETS) {
  41575. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41576. }
  41577. //Attributes
  41578. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41579. if (defines.NORMAL) {
  41580. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41581. }
  41582. if (defines.TANGENT) {
  41583. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41584. }
  41585. if (defines.UV1) {
  41586. attribs.push(BABYLON.VertexBuffer.UVKind);
  41587. }
  41588. if (defines.UV2) {
  41589. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41590. }
  41591. if (defines.VERTEXCOLOR) {
  41592. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41593. }
  41594. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41595. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41596. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41597. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41598. "vFogInfos", "vFogColor", "pointSize",
  41599. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41600. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41601. "mBones",
  41602. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41603. "vLightingIntensity",
  41604. "logarithmicDepthConstant",
  41605. "vSphericalX", "vSphericalY", "vSphericalZ",
  41606. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41607. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41608. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41609. "vTangentSpaceParams"
  41610. ];
  41611. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41612. "bumpSampler", "lightmapSampler", "opacitySampler",
  41613. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41614. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41615. "microSurfaceSampler", "environmentBrdfSampler"];
  41616. var uniformBuffers = ["Material", "Scene"];
  41617. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41618. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41619. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41620. uniformsNames: uniforms,
  41621. uniformBuffersNames: uniformBuffers,
  41622. samplers: samplers,
  41623. defines: defines,
  41624. maxSimultaneousLights: this._maxSimultaneousLights
  41625. });
  41626. var join = defines.toString();
  41627. return engine.createEffect("pbr", {
  41628. attributes: attribs,
  41629. uniformsNames: uniforms,
  41630. uniformBuffersNames: uniformBuffers,
  41631. samplers: samplers,
  41632. defines: join,
  41633. fallbacks: fallbacks,
  41634. onCompiled: onCompiled,
  41635. onError: onError,
  41636. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41637. }, engine);
  41638. };
  41639. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41640. if (useInstances === void 0) { useInstances = null; }
  41641. if (useClipPlane === void 0) { useClipPlane = null; }
  41642. var scene = this.getScene();
  41643. var engine = scene.getEngine();
  41644. // Lights
  41645. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41646. defines._needNormals = true;
  41647. // Textures
  41648. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41649. if (defines._areTexturesDirty) {
  41650. defines._needUVs = false;
  41651. if (scene.texturesEnabled) {
  41652. if (scene.getEngine().getCaps().textureLOD) {
  41653. defines.LODBASEDMICROSFURACE = true;
  41654. }
  41655. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41656. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41657. }
  41658. else {
  41659. defines.ALBEDO = false;
  41660. }
  41661. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41662. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41663. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41664. }
  41665. else {
  41666. defines.AMBIENT = false;
  41667. }
  41668. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41669. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41670. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41671. }
  41672. else {
  41673. defines.OPACITY = false;
  41674. }
  41675. var reflectionTexture = this._getReflectionTexture();
  41676. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41677. defines.REFLECTION = true;
  41678. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41679. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41680. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41681. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41682. defines.INVERTCUBICMAP = true;
  41683. }
  41684. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41685. switch (reflectionTexture.coordinatesMode) {
  41686. case BABYLON.Texture.CUBIC_MODE:
  41687. case BABYLON.Texture.INVCUBIC_MODE:
  41688. defines.REFLECTIONMAP_CUBIC = true;
  41689. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41690. break;
  41691. case BABYLON.Texture.EXPLICIT_MODE:
  41692. defines.REFLECTIONMAP_EXPLICIT = true;
  41693. break;
  41694. case BABYLON.Texture.PLANAR_MODE:
  41695. defines.REFLECTIONMAP_PLANAR = true;
  41696. break;
  41697. case BABYLON.Texture.PROJECTION_MODE:
  41698. defines.REFLECTIONMAP_PROJECTION = true;
  41699. break;
  41700. case BABYLON.Texture.SKYBOX_MODE:
  41701. defines.REFLECTIONMAP_SKYBOX = true;
  41702. break;
  41703. case BABYLON.Texture.SPHERICAL_MODE:
  41704. defines.REFLECTIONMAP_SPHERICAL = true;
  41705. break;
  41706. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41707. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41708. break;
  41709. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41710. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41711. break;
  41712. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41713. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41714. break;
  41715. }
  41716. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41717. if (reflectionTexture.sphericalPolynomial) {
  41718. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41719. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41720. defines.USESPHERICALINVERTEX = false;
  41721. }
  41722. else {
  41723. defines.USESPHERICALINVERTEX = true;
  41724. }
  41725. }
  41726. }
  41727. }
  41728. else {
  41729. defines.REFLECTION = false;
  41730. defines.REFLECTIONMAP_3D = false;
  41731. defines.REFLECTIONMAP_SPHERICAL = false;
  41732. defines.REFLECTIONMAP_PLANAR = false;
  41733. defines.REFLECTIONMAP_CUBIC = false;
  41734. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41735. defines.REFLECTIONMAP_PROJECTION = false;
  41736. defines.REFLECTIONMAP_SKYBOX = false;
  41737. defines.REFLECTIONMAP_EXPLICIT = false;
  41738. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41739. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41740. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41741. defines.INVERTCUBICMAP = false;
  41742. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41743. defines.USESPHERICALINVERTEX = false;
  41744. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41745. defines.LODINREFLECTIONALPHA = false;
  41746. defines.GAMMAREFLECTION = false;
  41747. }
  41748. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41749. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41750. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41751. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41752. }
  41753. else {
  41754. defines.LIGHTMAP = false;
  41755. }
  41756. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41757. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41758. }
  41759. else {
  41760. defines.EMISSIVE = false;
  41761. }
  41762. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41763. if (this._metallicTexture) {
  41764. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41765. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41766. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41767. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41768. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41769. }
  41770. else if (this._reflectivityTexture) {
  41771. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41772. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41773. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41774. }
  41775. else {
  41776. defines.REFLECTIVITY = false;
  41777. }
  41778. if (this._microSurfaceTexture) {
  41779. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41780. }
  41781. else {
  41782. defines.MICROSURFACEMAP = false;
  41783. }
  41784. }
  41785. else {
  41786. defines.REFLECTIVITY = false;
  41787. defines.MICROSURFACEMAP = false;
  41788. }
  41789. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41790. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41791. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41792. defines.PARALLAX = true;
  41793. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41794. }
  41795. else {
  41796. defines.PARALLAX = false;
  41797. }
  41798. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41799. }
  41800. else {
  41801. defines.BUMP = false;
  41802. }
  41803. var refractionTexture = this._getRefractionTexture();
  41804. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41805. defines.REFRACTION = true;
  41806. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41807. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41808. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41809. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41810. if (this._linkRefractionWithTransparency) {
  41811. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41812. }
  41813. }
  41814. else {
  41815. defines.REFRACTION = false;
  41816. }
  41817. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41818. defines.ENVIRONMENTBRDF = true;
  41819. }
  41820. else {
  41821. defines.ENVIRONMENTBRDF = false;
  41822. }
  41823. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41824. defines.ALPHAFROMALBEDO = true;
  41825. }
  41826. else {
  41827. defines.ALPHAFROMALBEDO = false;
  41828. }
  41829. }
  41830. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41831. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41832. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41833. if (!this.backFaceCulling && this._twoSidedLighting) {
  41834. defines.TWOSIDEDLIGHTING = true;
  41835. }
  41836. else {
  41837. defines.TWOSIDEDLIGHTING = false;
  41838. }
  41839. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41840. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41841. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41842. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41843. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41844. }
  41845. if (defines._areImageProcessingDirty) {
  41846. this._imageProcessingConfiguration.prepareDefines(defines);
  41847. }
  41848. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41849. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41850. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41851. // Misc.
  41852. if (defines._areMiscDirty) {
  41853. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41854. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41855. }
  41856. // Values that need to be evaluated on every frame
  41857. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41858. // Attribs
  41859. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41860. };
  41861. /**
  41862. * Force shader compilation
  41863. */
  41864. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41865. var _this = this;
  41866. var localOptions = __assign({ clipPlane: false }, options);
  41867. var defines = new PBRMaterialDefines();
  41868. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41869. if (effect.isReady()) {
  41870. if (onCompiled) {
  41871. onCompiled(this);
  41872. }
  41873. }
  41874. else {
  41875. effect.onCompileObservable.add(function () {
  41876. if (onCompiled) {
  41877. onCompiled(_this);
  41878. }
  41879. });
  41880. }
  41881. };
  41882. /**
  41883. * Initializes the uniform buffer layout for the shader.
  41884. */
  41885. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41886. // Order is important !
  41887. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41888. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41889. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41890. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41891. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41892. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41893. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41894. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41895. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41896. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41897. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41898. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41899. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41900. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41901. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41902. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41903. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41904. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41905. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41906. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41907. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41908. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41909. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41910. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41911. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41912. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41913. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41914. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41915. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41916. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41917. this._uniformBuffer.addUniform("pointSize", 1);
  41918. this._uniformBuffer.create();
  41919. };
  41920. /**
  41921. * Unbinds the textures.
  41922. */
  41923. PBRBaseMaterial.prototype.unbind = function () {
  41924. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41925. this._uniformBuffer.setTexture("reflectionSampler", null);
  41926. }
  41927. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41928. this._uniformBuffer.setTexture("refractionSampler", null);
  41929. }
  41930. _super.prototype.unbind.call(this);
  41931. };
  41932. /**
  41933. * Binds the submesh data.
  41934. * @param world - The world matrix.
  41935. * @param mesh - The BJS mesh.
  41936. * @param subMesh - A submesh of the BJS mesh.
  41937. */
  41938. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41939. var scene = this.getScene();
  41940. var defines = subMesh._materialDefines;
  41941. if (!defines) {
  41942. return;
  41943. }
  41944. var effect = subMesh.effect;
  41945. if (!effect) {
  41946. return;
  41947. }
  41948. this._activeEffect = effect;
  41949. // Matrices
  41950. this.bindOnlyWorldMatrix(world);
  41951. // Normal Matrix
  41952. if (defines.OBJECTSPACE_NORMALMAP) {
  41953. world.toNormalMatrix(this._normalMatrix);
  41954. this.bindOnlyNormalMatrix(this._normalMatrix);
  41955. }
  41956. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41957. // Bones
  41958. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41959. var reflectionTexture = null;
  41960. if (mustRebind) {
  41961. this._uniformBuffer.bindToEffect(effect, "Material");
  41962. this.bindViewProjection(effect);
  41963. reflectionTexture = this._getReflectionTexture();
  41964. var refractionTexture = this._getRefractionTexture();
  41965. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41966. // Texture uniforms
  41967. if (scene.texturesEnabled) {
  41968. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41969. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41970. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41971. }
  41972. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41973. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41974. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41975. }
  41976. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41977. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41978. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41979. }
  41980. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41981. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41982. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41983. if (reflectionTexture.boundingBoxSize) {
  41984. var cubeTexture = reflectionTexture;
  41985. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41986. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41987. }
  41988. var polynomials = reflectionTexture.sphericalPolynomial;
  41989. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41990. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41991. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41992. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41993. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41994. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41995. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41996. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41997. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41998. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41999. }
  42000. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42001. }
  42002. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42003. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42004. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42005. }
  42006. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42007. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42008. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42009. }
  42010. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42011. if (this._metallicTexture) {
  42012. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42013. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42014. }
  42015. else if (this._reflectivityTexture) {
  42016. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42017. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42018. }
  42019. if (this._microSurfaceTexture) {
  42020. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42021. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42022. }
  42023. }
  42024. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42025. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42026. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42027. if (scene._mirroredCameraPosition) {
  42028. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42029. }
  42030. else {
  42031. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42032. }
  42033. }
  42034. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42035. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42036. var depth = 1.0;
  42037. if (!refractionTexture.isCube) {
  42038. if (refractionTexture.depth) {
  42039. depth = refractionTexture.depth;
  42040. }
  42041. }
  42042. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42043. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42044. }
  42045. }
  42046. // Point size
  42047. if (this.pointsCloud) {
  42048. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42049. }
  42050. // Colors
  42051. if (defines.METALLICWORKFLOW) {
  42052. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42053. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42054. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42055. }
  42056. else {
  42057. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42058. }
  42059. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42060. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42061. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42062. // Misc
  42063. this._lightingInfos.x = this._directIntensity;
  42064. this._lightingInfos.y = this._emissiveIntensity;
  42065. this._lightingInfos.z = this._environmentIntensity;
  42066. this._lightingInfos.w = this._specularIntensity;
  42067. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42068. }
  42069. // Textures
  42070. if (scene.texturesEnabled) {
  42071. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42072. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42073. }
  42074. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42075. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42076. }
  42077. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42078. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42079. }
  42080. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42081. if (defines.LODBASEDMICROSFURACE) {
  42082. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42083. }
  42084. else {
  42085. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42086. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42087. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42088. }
  42089. }
  42090. if (defines.ENVIRONMENTBRDF) {
  42091. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42092. }
  42093. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42094. if (defines.LODBASEDMICROSFURACE) {
  42095. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42096. }
  42097. else {
  42098. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42099. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42100. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42101. }
  42102. }
  42103. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42104. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42105. }
  42106. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42107. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42108. }
  42109. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42110. if (this._metallicTexture) {
  42111. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42112. }
  42113. else if (this._reflectivityTexture) {
  42114. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42115. }
  42116. if (this._microSurfaceTexture) {
  42117. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42118. }
  42119. }
  42120. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42121. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42122. }
  42123. }
  42124. // Clip plane
  42125. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42126. // Colors
  42127. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42128. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42129. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42130. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42131. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42132. }
  42133. if (mustRebind || !this.isFrozen) {
  42134. // Lights
  42135. if (scene.lightsEnabled && !this._disableLighting) {
  42136. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42137. }
  42138. // View
  42139. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42140. this.bindView(effect);
  42141. }
  42142. // Fog
  42143. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42144. // Morph targets
  42145. if (defines.NUM_MORPH_INFLUENCERS) {
  42146. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42147. }
  42148. // image processing
  42149. this._imageProcessingConfiguration.bind(this._activeEffect);
  42150. // Log. depth
  42151. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42152. }
  42153. this._uniformBuffer.update();
  42154. this._afterBind(mesh);
  42155. };
  42156. /**
  42157. * Returns the animatable textures.
  42158. * @returns - Array of animatable textures.
  42159. */
  42160. PBRBaseMaterial.prototype.getAnimatables = function () {
  42161. var results = [];
  42162. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42163. results.push(this._albedoTexture);
  42164. }
  42165. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42166. results.push(this._ambientTexture);
  42167. }
  42168. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42169. results.push(this._opacityTexture);
  42170. }
  42171. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42172. results.push(this._reflectionTexture);
  42173. }
  42174. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42175. results.push(this._emissiveTexture);
  42176. }
  42177. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42178. results.push(this._metallicTexture);
  42179. }
  42180. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42181. results.push(this._reflectivityTexture);
  42182. }
  42183. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42184. results.push(this._bumpTexture);
  42185. }
  42186. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42187. results.push(this._lightmapTexture);
  42188. }
  42189. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42190. results.push(this._refractionTexture);
  42191. }
  42192. return results;
  42193. };
  42194. /**
  42195. * Returns the texture used for reflections.
  42196. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42197. */
  42198. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42199. if (this._reflectionTexture) {
  42200. return this._reflectionTexture;
  42201. }
  42202. return this.getScene().environmentTexture;
  42203. };
  42204. /**
  42205. * Returns the texture used for refraction or null if none is used.
  42206. * @returns - Refection texture if present. If no refraction texture and refraction
  42207. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42208. */
  42209. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42210. if (this._refractionTexture) {
  42211. return this._refractionTexture;
  42212. }
  42213. if (this._linkRefractionWithTransparency) {
  42214. return this.getScene().environmentTexture;
  42215. }
  42216. return null;
  42217. };
  42218. /**
  42219. * Disposes the resources of the material.
  42220. * @param forceDisposeEffect - Forces the disposal of effects.
  42221. * @param forceDisposeTextures - Forces the disposal of all textures.
  42222. */
  42223. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42224. if (forceDisposeTextures) {
  42225. if (this._albedoTexture) {
  42226. this._albedoTexture.dispose();
  42227. }
  42228. if (this._ambientTexture) {
  42229. this._ambientTexture.dispose();
  42230. }
  42231. if (this._opacityTexture) {
  42232. this._opacityTexture.dispose();
  42233. }
  42234. if (this._reflectionTexture) {
  42235. this._reflectionTexture.dispose();
  42236. }
  42237. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42238. this._environmentBRDFTexture.dispose();
  42239. }
  42240. if (this._emissiveTexture) {
  42241. this._emissiveTexture.dispose();
  42242. }
  42243. if (this._metallicTexture) {
  42244. this._metallicTexture.dispose();
  42245. }
  42246. if (this._reflectivityTexture) {
  42247. this._reflectivityTexture.dispose();
  42248. }
  42249. if (this._bumpTexture) {
  42250. this._bumpTexture.dispose();
  42251. }
  42252. if (this._lightmapTexture) {
  42253. this._lightmapTexture.dispose();
  42254. }
  42255. if (this._refractionTexture) {
  42256. this._refractionTexture.dispose();
  42257. }
  42258. }
  42259. this._renderTargets.dispose();
  42260. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42261. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42262. }
  42263. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42264. };
  42265. /**
  42266. * Stores the reflectivity values based on metallic roughness workflow.
  42267. */
  42268. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42269. __decorate([
  42270. BABYLON.serializeAsImageProcessingConfiguration()
  42271. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42272. __decorate([
  42273. BABYLON.serialize()
  42274. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42275. __decorate([
  42276. BABYLON.serialize()
  42277. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42278. return PBRBaseMaterial;
  42279. }(BABYLON.PushMaterial));
  42280. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42281. })(BABYLON || (BABYLON = {}));
  42282. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42283. "use strict";
  42284. var BABYLON;
  42285. (function (BABYLON) {
  42286. /**
  42287. * The Physically based simple base material of BJS.
  42288. *
  42289. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42290. * It is used as the base class for both the specGloss and metalRough conventions.
  42291. */
  42292. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42293. __extends(PBRBaseSimpleMaterial, _super);
  42294. /**
  42295. * Instantiates a new PBRMaterial instance.
  42296. *
  42297. * @param name The material name
  42298. * @param scene The scene the material will be use in.
  42299. */
  42300. function PBRBaseSimpleMaterial(name, scene) {
  42301. var _this = _super.call(this, name, scene) || this;
  42302. /**
  42303. * Number of Simultaneous lights allowed on the material.
  42304. */
  42305. _this.maxSimultaneousLights = 4;
  42306. /**
  42307. * If sets to true, disables all the lights affecting the material.
  42308. */
  42309. _this.disableLighting = false;
  42310. /**
  42311. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42312. */
  42313. _this.invertNormalMapX = false;
  42314. /**
  42315. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42316. */
  42317. _this.invertNormalMapY = false;
  42318. /**
  42319. * Emissivie color used to self-illuminate the model.
  42320. */
  42321. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42322. /**
  42323. * Occlusion Channel Strenght.
  42324. */
  42325. _this.occlusionStrength = 1.0;
  42326. _this.useLightmapAsShadowmap = false;
  42327. _this._useAlphaFromAlbedoTexture = true;
  42328. _this._useAmbientInGrayScale = true;
  42329. return _this;
  42330. }
  42331. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42332. /**
  42333. * Gets the current double sided mode.
  42334. */
  42335. get: function () {
  42336. return this._twoSidedLighting;
  42337. },
  42338. /**
  42339. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42340. */
  42341. set: function (value) {
  42342. if (this._twoSidedLighting === value) {
  42343. return;
  42344. }
  42345. this._twoSidedLighting = value;
  42346. this.backFaceCulling = !value;
  42347. this._markAllSubMeshesAsTexturesDirty();
  42348. },
  42349. enumerable: true,
  42350. configurable: true
  42351. });
  42352. /**
  42353. * Return the active textures of the material.
  42354. */
  42355. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42356. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42357. if (this.environmentTexture) {
  42358. activeTextures.push(this.environmentTexture);
  42359. }
  42360. if (this.normalTexture) {
  42361. activeTextures.push(this.normalTexture);
  42362. }
  42363. if (this.emissiveTexture) {
  42364. activeTextures.push(this.emissiveTexture);
  42365. }
  42366. if (this.occlusionTexture) {
  42367. activeTextures.push(this.occlusionTexture);
  42368. }
  42369. if (this.lightmapTexture) {
  42370. activeTextures.push(this.lightmapTexture);
  42371. }
  42372. return activeTextures;
  42373. };
  42374. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42375. if (_super.prototype.hasTexture.call(this, texture)) {
  42376. return true;
  42377. }
  42378. if (this.lightmapTexture === texture) {
  42379. return true;
  42380. }
  42381. return false;
  42382. };
  42383. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42384. return "PBRBaseSimpleMaterial";
  42385. };
  42386. __decorate([
  42387. BABYLON.serialize(),
  42388. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42389. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42390. __decorate([
  42391. BABYLON.serialize(),
  42392. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42393. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42394. __decorate([
  42395. BABYLON.serializeAsTexture(),
  42396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42397. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42398. __decorate([
  42399. BABYLON.serialize(),
  42400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42401. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42402. __decorate([
  42403. BABYLON.serialize(),
  42404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42405. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42406. __decorate([
  42407. BABYLON.serializeAsTexture(),
  42408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42409. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42410. __decorate([
  42411. BABYLON.serializeAsColor3("emissive"),
  42412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42413. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42414. __decorate([
  42415. BABYLON.serializeAsTexture(),
  42416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42417. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42418. __decorate([
  42419. BABYLON.serialize(),
  42420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42421. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42422. __decorate([
  42423. BABYLON.serializeAsTexture(),
  42424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42425. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42426. __decorate([
  42427. BABYLON.serialize(),
  42428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42429. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42430. __decorate([
  42431. BABYLON.serialize()
  42432. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42433. __decorate([
  42434. BABYLON.serializeAsTexture(),
  42435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42436. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42437. __decorate([
  42438. BABYLON.serialize(),
  42439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42440. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42441. return PBRBaseSimpleMaterial;
  42442. }(BABYLON.PBRBaseMaterial));
  42443. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42444. })(BABYLON || (BABYLON = {}));
  42445. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42446. "use strict";
  42447. var BABYLON;
  42448. (function (BABYLON) {
  42449. /**
  42450. * The Physically based material of BJS.
  42451. *
  42452. * This offers the main features of a standard PBR material.
  42453. * For more information, please refer to the documentation :
  42454. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42455. */
  42456. var PBRMaterial = /** @class */ (function (_super) {
  42457. __extends(PBRMaterial, _super);
  42458. /**
  42459. * Instantiates a new PBRMaterial instance.
  42460. *
  42461. * @param name The material name
  42462. * @param scene The scene the material will be use in.
  42463. */
  42464. function PBRMaterial(name, scene) {
  42465. var _this = _super.call(this, name, scene) || this;
  42466. /**
  42467. * Intensity of the direct lights e.g. the four lights available in your scene.
  42468. * This impacts both the direct diffuse and specular highlights.
  42469. */
  42470. _this.directIntensity = 1.0;
  42471. /**
  42472. * Intensity of the emissive part of the material.
  42473. * This helps controlling the emissive effect without modifying the emissive color.
  42474. */
  42475. _this.emissiveIntensity = 1.0;
  42476. /**
  42477. * Intensity of the environment e.g. how much the environment will light the object
  42478. * either through harmonics for rough material or through the refelction for shiny ones.
  42479. */
  42480. _this.environmentIntensity = 1.0;
  42481. /**
  42482. * This is a special control allowing the reduction of the specular highlights coming from the
  42483. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42484. */
  42485. _this.specularIntensity = 1.0;
  42486. /**
  42487. * Debug Control allowing disabling the bump map on this material.
  42488. */
  42489. _this.disableBumpMap = false;
  42490. /**
  42491. * AKA Occlusion Texture Intensity in other nomenclature.
  42492. */
  42493. _this.ambientTextureStrength = 1.0;
  42494. /**
  42495. * The color of a material in ambient lighting.
  42496. */
  42497. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42498. /**
  42499. * AKA Diffuse Color in other nomenclature.
  42500. */
  42501. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42502. /**
  42503. * AKA Specular Color in other nomenclature.
  42504. */
  42505. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42506. /**
  42507. * The color reflected from the material.
  42508. */
  42509. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42510. /**
  42511. * The color emitted from the material.
  42512. */
  42513. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42514. /**
  42515. * AKA Glossiness in other nomenclature.
  42516. */
  42517. _this.microSurface = 1.0;
  42518. /**
  42519. * source material index of refraction (IOR)' / 'destination material IOR.
  42520. */
  42521. _this.indexOfRefraction = 0.66;
  42522. /**
  42523. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42524. */
  42525. _this.invertRefractionY = false;
  42526. /**
  42527. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42528. * Materials half opaque for instance using refraction could benefit from this control.
  42529. */
  42530. _this.linkRefractionWithTransparency = false;
  42531. _this.useLightmapAsShadowmap = false;
  42532. /**
  42533. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42534. */
  42535. _this.useAlphaFromAlbedoTexture = false;
  42536. /**
  42537. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42538. */
  42539. _this.forceAlphaTest = false;
  42540. /**
  42541. * Defines the alpha limits in alpha test mode.
  42542. */
  42543. _this.alphaCutOff = 0.4;
  42544. /**
  42545. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42546. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42547. */
  42548. _this.useSpecularOverAlpha = true;
  42549. /**
  42550. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42551. */
  42552. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42553. /**
  42554. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42555. */
  42556. _this.useRoughnessFromMetallicTextureAlpha = true;
  42557. /**
  42558. * Specifies if the metallic texture contains the roughness information in its green channel.
  42559. */
  42560. _this.useRoughnessFromMetallicTextureGreen = false;
  42561. /**
  42562. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42563. */
  42564. _this.useMetallnessFromMetallicTextureBlue = false;
  42565. /**
  42566. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42567. */
  42568. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42569. /**
  42570. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42571. */
  42572. _this.useAmbientInGrayScale = false;
  42573. /**
  42574. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42575. * The material will try to infer what glossiness each pixel should be.
  42576. */
  42577. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42578. /**
  42579. * BJS is using an harcoded light falloff based on a manually sets up range.
  42580. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42581. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42582. */
  42583. _this.usePhysicalLightFalloff = true;
  42584. /**
  42585. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42586. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42587. */
  42588. _this.useRadianceOverAlpha = true;
  42589. /**
  42590. * Allows using an object space normal map (instead of tangent space).
  42591. */
  42592. _this.useObjectSpaceNormalMap = false;
  42593. /**
  42594. * Allows using the bump map in parallax mode.
  42595. */
  42596. _this.useParallax = false;
  42597. /**
  42598. * Allows using the bump map in parallax occlusion mode.
  42599. */
  42600. _this.useParallaxOcclusion = false;
  42601. /**
  42602. * Controls the scale bias of the parallax mode.
  42603. */
  42604. _this.parallaxScaleBias = 0.05;
  42605. /**
  42606. * If sets to true, disables all the lights affecting the material.
  42607. */
  42608. _this.disableLighting = false;
  42609. /**
  42610. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42611. */
  42612. _this.forceIrradianceInFragment = false;
  42613. /**
  42614. * Number of Simultaneous lights allowed on the material.
  42615. */
  42616. _this.maxSimultaneousLights = 4;
  42617. /**
  42618. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42619. */
  42620. _this.invertNormalMapX = false;
  42621. /**
  42622. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42623. */
  42624. _this.invertNormalMapY = false;
  42625. /**
  42626. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42627. */
  42628. _this.twoSidedLighting = false;
  42629. /**
  42630. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42631. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42632. */
  42633. _this.useAlphaFresnel = false;
  42634. /**
  42635. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42636. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42637. */
  42638. _this.useLinearAlphaFresnel = false;
  42639. /**
  42640. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42641. * And/Or occlude the blended part.
  42642. */
  42643. _this.environmentBRDFTexture = null;
  42644. /**
  42645. * Force normal to face away from face.
  42646. */
  42647. _this.forceNormalForward = false;
  42648. /**
  42649. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42650. * makes the reflect vector face the model (under horizon).
  42651. */
  42652. _this.useHorizonOcclusion = true;
  42653. /**
  42654. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42655. * too much the area relying on ambient texture to define their ambient occlusion.
  42656. */
  42657. _this.useRadianceOcclusion = true;
  42658. /**
  42659. * If set to true, no lighting calculations will be applied.
  42660. */
  42661. _this.unlit = false;
  42662. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42663. return _this;
  42664. }
  42665. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42666. /**
  42667. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42668. */
  42669. get: function () {
  42670. return this._PBRMATERIAL_OPAQUE;
  42671. },
  42672. enumerable: true,
  42673. configurable: true
  42674. });
  42675. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42676. /**
  42677. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42678. */
  42679. get: function () {
  42680. return this._PBRMATERIAL_ALPHATEST;
  42681. },
  42682. enumerable: true,
  42683. configurable: true
  42684. });
  42685. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42686. /**
  42687. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42688. */
  42689. get: function () {
  42690. return this._PBRMATERIAL_ALPHABLEND;
  42691. },
  42692. enumerable: true,
  42693. configurable: true
  42694. });
  42695. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42696. /**
  42697. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42698. * They are also discarded below the alpha cutoff threshold to improve performances.
  42699. */
  42700. get: function () {
  42701. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42702. },
  42703. enumerable: true,
  42704. configurable: true
  42705. });
  42706. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42707. /**
  42708. * Gets the image processing configuration used either in this material.
  42709. */
  42710. get: function () {
  42711. return this._imageProcessingConfiguration;
  42712. },
  42713. /**
  42714. * Sets the Default image processing configuration used either in the this material.
  42715. *
  42716. * If sets to null, the scene one is in use.
  42717. */
  42718. set: function (value) {
  42719. this._attachImageProcessingConfiguration(value);
  42720. // Ensure the effect will be rebuilt.
  42721. this._markAllSubMeshesAsTexturesDirty();
  42722. },
  42723. enumerable: true,
  42724. configurable: true
  42725. });
  42726. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42727. /**
  42728. * Gets wether the color curves effect is enabled.
  42729. */
  42730. get: function () {
  42731. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42732. },
  42733. /**
  42734. * Sets wether the color curves effect is enabled.
  42735. */
  42736. set: function (value) {
  42737. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42738. },
  42739. enumerable: true,
  42740. configurable: true
  42741. });
  42742. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42743. /**
  42744. * Gets wether the color grading effect is enabled.
  42745. */
  42746. get: function () {
  42747. return this.imageProcessingConfiguration.colorGradingEnabled;
  42748. },
  42749. /**
  42750. * Gets wether the color grading effect is enabled.
  42751. */
  42752. set: function (value) {
  42753. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42754. },
  42755. enumerable: true,
  42756. configurable: true
  42757. });
  42758. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42759. /**
  42760. * Gets wether tonemapping is enabled or not.
  42761. */
  42762. get: function () {
  42763. return this._imageProcessingConfiguration.toneMappingEnabled;
  42764. },
  42765. /**
  42766. * Sets wether tonemapping is enabled or not
  42767. */
  42768. set: function (value) {
  42769. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42770. },
  42771. enumerable: true,
  42772. configurable: true
  42773. });
  42774. ;
  42775. ;
  42776. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42777. /**
  42778. * The camera exposure used on this material.
  42779. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42780. * This corresponds to a photographic exposure.
  42781. */
  42782. get: function () {
  42783. return this._imageProcessingConfiguration.exposure;
  42784. },
  42785. /**
  42786. * The camera exposure used on this material.
  42787. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42788. * This corresponds to a photographic exposure.
  42789. */
  42790. set: function (value) {
  42791. this._imageProcessingConfiguration.exposure = value;
  42792. },
  42793. enumerable: true,
  42794. configurable: true
  42795. });
  42796. ;
  42797. ;
  42798. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42799. /**
  42800. * Gets The camera contrast used on this material.
  42801. */
  42802. get: function () {
  42803. return this._imageProcessingConfiguration.contrast;
  42804. },
  42805. /**
  42806. * Sets The camera contrast used on this material.
  42807. */
  42808. set: function (value) {
  42809. this._imageProcessingConfiguration.contrast = value;
  42810. },
  42811. enumerable: true,
  42812. configurable: true
  42813. });
  42814. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42815. /**
  42816. * Gets the Color Grading 2D Lookup Texture.
  42817. */
  42818. get: function () {
  42819. return this._imageProcessingConfiguration.colorGradingTexture;
  42820. },
  42821. /**
  42822. * Sets the Color Grading 2D Lookup Texture.
  42823. */
  42824. set: function (value) {
  42825. this._imageProcessingConfiguration.colorGradingTexture = value;
  42826. },
  42827. enumerable: true,
  42828. configurable: true
  42829. });
  42830. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42831. /**
  42832. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42833. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42834. * 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;
  42835. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42836. */
  42837. get: function () {
  42838. return this._imageProcessingConfiguration.colorCurves;
  42839. },
  42840. /**
  42841. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42842. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42843. * 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;
  42844. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42845. */
  42846. set: function (value) {
  42847. this._imageProcessingConfiguration.colorCurves = value;
  42848. },
  42849. enumerable: true,
  42850. configurable: true
  42851. });
  42852. /**
  42853. * Returns the name of this material class.
  42854. */
  42855. PBRMaterial.prototype.getClassName = function () {
  42856. return "PBRMaterial";
  42857. };
  42858. /**
  42859. * Returns an array of the actively used textures.
  42860. * @returns - Array of BaseTextures
  42861. */
  42862. PBRMaterial.prototype.getActiveTextures = function () {
  42863. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42864. if (this._albedoTexture) {
  42865. activeTextures.push(this._albedoTexture);
  42866. }
  42867. if (this._ambientTexture) {
  42868. activeTextures.push(this._ambientTexture);
  42869. }
  42870. if (this._opacityTexture) {
  42871. activeTextures.push(this._opacityTexture);
  42872. }
  42873. if (this._reflectionTexture) {
  42874. activeTextures.push(this._reflectionTexture);
  42875. }
  42876. if (this._emissiveTexture) {
  42877. activeTextures.push(this._emissiveTexture);
  42878. }
  42879. if (this._reflectivityTexture) {
  42880. activeTextures.push(this._reflectivityTexture);
  42881. }
  42882. if (this._metallicTexture) {
  42883. activeTextures.push(this._metallicTexture);
  42884. }
  42885. if (this._microSurfaceTexture) {
  42886. activeTextures.push(this._microSurfaceTexture);
  42887. }
  42888. if (this._bumpTexture) {
  42889. activeTextures.push(this._bumpTexture);
  42890. }
  42891. if (this._lightmapTexture) {
  42892. activeTextures.push(this._lightmapTexture);
  42893. }
  42894. if (this._refractionTexture) {
  42895. activeTextures.push(this._refractionTexture);
  42896. }
  42897. return activeTextures;
  42898. };
  42899. /**
  42900. * Checks to see if a texture is used in the material.
  42901. * @param texture - Base texture to use.
  42902. * @returns - Boolean specifying if a texture is used in the material.
  42903. */
  42904. PBRMaterial.prototype.hasTexture = function (texture) {
  42905. if (_super.prototype.hasTexture.call(this, texture)) {
  42906. return true;
  42907. }
  42908. if (this._albedoTexture === texture) {
  42909. return true;
  42910. }
  42911. if (this._ambientTexture === texture) {
  42912. return true;
  42913. }
  42914. if (this._opacityTexture === texture) {
  42915. return true;
  42916. }
  42917. if (this._reflectionTexture === texture) {
  42918. return true;
  42919. }
  42920. if (this._reflectivityTexture === texture) {
  42921. return true;
  42922. }
  42923. if (this._metallicTexture === texture) {
  42924. return true;
  42925. }
  42926. if (this._microSurfaceTexture === texture) {
  42927. return true;
  42928. }
  42929. if (this._bumpTexture === texture) {
  42930. return true;
  42931. }
  42932. if (this._lightmapTexture === texture) {
  42933. return true;
  42934. }
  42935. if (this._refractionTexture === texture) {
  42936. return true;
  42937. }
  42938. return false;
  42939. };
  42940. /**
  42941. * Makes a duplicate of the current material.
  42942. * @param name - name to use for the new material.
  42943. */
  42944. PBRMaterial.prototype.clone = function (name) {
  42945. var _this = this;
  42946. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42947. clone.id = name;
  42948. clone.name = name;
  42949. return clone;
  42950. };
  42951. /**
  42952. * Serializes this PBR Material.
  42953. * @returns - An object with the serialized material.
  42954. */
  42955. PBRMaterial.prototype.serialize = function () {
  42956. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42957. serializationObject.customType = "BABYLON.PBRMaterial";
  42958. return serializationObject;
  42959. };
  42960. // Statics
  42961. /**
  42962. * Parses a PBR Material from a serialized object.
  42963. * @param source - Serialized object.
  42964. * @param scene - BJS scene instance.
  42965. * @param rootUrl - url for the scene object
  42966. * @returns - PBRMaterial
  42967. */
  42968. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42969. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42970. };
  42971. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42972. /**
  42973. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42974. */
  42975. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42976. /**
  42977. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42978. */
  42979. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42980. /**
  42981. * 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.
  42982. * They are also discarded below the alpha cutoff threshold to improve performances.
  42983. */
  42984. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42985. __decorate([
  42986. BABYLON.serialize(),
  42987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42988. ], PBRMaterial.prototype, "directIntensity", void 0);
  42989. __decorate([
  42990. BABYLON.serialize(),
  42991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42992. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42993. __decorate([
  42994. BABYLON.serialize(),
  42995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42996. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42997. __decorate([
  42998. BABYLON.serialize(),
  42999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43000. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43001. __decorate([
  43002. BABYLON.serialize(),
  43003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43004. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43005. __decorate([
  43006. BABYLON.serializeAsTexture(),
  43007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43008. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43009. __decorate([
  43010. BABYLON.serializeAsTexture(),
  43011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43012. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43013. __decorate([
  43014. BABYLON.serialize(),
  43015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43016. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43017. __decorate([
  43018. BABYLON.serializeAsTexture(),
  43019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43020. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43021. __decorate([
  43022. BABYLON.serializeAsTexture(),
  43023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43024. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43025. __decorate([
  43026. BABYLON.serializeAsTexture(),
  43027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43028. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43029. __decorate([
  43030. BABYLON.serializeAsTexture(),
  43031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43032. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43033. __decorate([
  43034. BABYLON.serializeAsTexture(),
  43035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43036. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43037. __decorate([
  43038. BABYLON.serialize(),
  43039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43040. ], PBRMaterial.prototype, "metallic", void 0);
  43041. __decorate([
  43042. BABYLON.serialize(),
  43043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43044. ], PBRMaterial.prototype, "roughness", void 0);
  43045. __decorate([
  43046. BABYLON.serializeAsTexture(),
  43047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43048. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43049. __decorate([
  43050. BABYLON.serializeAsTexture(),
  43051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43052. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43053. __decorate([
  43054. BABYLON.serializeAsTexture(),
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43056. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43057. __decorate([
  43058. BABYLON.serializeAsTexture(),
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43060. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43061. __decorate([
  43062. BABYLON.serializeAsColor3("ambient"),
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43064. ], PBRMaterial.prototype, "ambientColor", void 0);
  43065. __decorate([
  43066. BABYLON.serializeAsColor3("albedo"),
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43068. ], PBRMaterial.prototype, "albedoColor", void 0);
  43069. __decorate([
  43070. BABYLON.serializeAsColor3("reflectivity"),
  43071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43072. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43073. __decorate([
  43074. BABYLON.serializeAsColor3("reflection"),
  43075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43076. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43077. __decorate([
  43078. BABYLON.serializeAsColor3("emissive"),
  43079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43080. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43081. __decorate([
  43082. BABYLON.serialize(),
  43083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43084. ], PBRMaterial.prototype, "microSurface", void 0);
  43085. __decorate([
  43086. BABYLON.serialize(),
  43087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43088. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43089. __decorate([
  43090. BABYLON.serialize(),
  43091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43092. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43093. __decorate([
  43094. BABYLON.serialize(),
  43095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43096. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43097. __decorate([
  43098. BABYLON.serialize(),
  43099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43100. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43101. __decorate([
  43102. BABYLON.serialize(),
  43103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43104. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43105. __decorate([
  43106. BABYLON.serialize(),
  43107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43108. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43109. __decorate([
  43110. BABYLON.serialize(),
  43111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43112. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43113. __decorate([
  43114. BABYLON.serialize(),
  43115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43116. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43117. __decorate([
  43118. BABYLON.serialize(),
  43119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43120. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43121. __decorate([
  43122. BABYLON.serialize(),
  43123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43124. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43125. __decorate([
  43126. BABYLON.serialize(),
  43127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43128. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43129. __decorate([
  43130. BABYLON.serialize(),
  43131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43132. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43133. __decorate([
  43134. BABYLON.serialize(),
  43135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43136. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43137. __decorate([
  43138. BABYLON.serialize(),
  43139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43140. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43141. __decorate([
  43142. BABYLON.serialize(),
  43143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43144. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43145. __decorate([
  43146. BABYLON.serialize(),
  43147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43148. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43149. __decorate([
  43150. BABYLON.serialize(),
  43151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43152. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43153. __decorate([
  43154. BABYLON.serialize(),
  43155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43156. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43157. __decorate([
  43158. BABYLON.serialize(),
  43159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43160. ], PBRMaterial.prototype, "useParallax", void 0);
  43161. __decorate([
  43162. BABYLON.serialize(),
  43163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43164. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43165. __decorate([
  43166. BABYLON.serialize(),
  43167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43168. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43169. __decorate([
  43170. BABYLON.serialize(),
  43171. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43172. ], PBRMaterial.prototype, "disableLighting", void 0);
  43173. __decorate([
  43174. BABYLON.serialize(),
  43175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43176. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43177. __decorate([
  43178. BABYLON.serialize(),
  43179. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43180. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43181. __decorate([
  43182. BABYLON.serialize(),
  43183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43184. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43185. __decorate([
  43186. BABYLON.serialize(),
  43187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43188. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43189. __decorate([
  43190. BABYLON.serialize(),
  43191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43192. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43193. __decorate([
  43194. BABYLON.serialize(),
  43195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43196. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43197. __decorate([
  43198. BABYLON.serialize(),
  43199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43200. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43201. __decorate([
  43202. BABYLON.serializeAsTexture(),
  43203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43204. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43205. __decorate([
  43206. BABYLON.serialize(),
  43207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43208. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43209. __decorate([
  43210. BABYLON.serialize(),
  43211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43212. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43213. __decorate([
  43214. BABYLON.serialize(),
  43215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43216. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43217. __decorate([
  43218. BABYLON.serialize(),
  43219. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43220. ], PBRMaterial.prototype, "unlit", void 0);
  43221. return PBRMaterial;
  43222. }(BABYLON.PBRBaseMaterial));
  43223. BABYLON.PBRMaterial = PBRMaterial;
  43224. })(BABYLON || (BABYLON = {}));
  43225. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43226. "use strict";
  43227. var BABYLON;
  43228. (function (BABYLON) {
  43229. /**
  43230. * The PBR material of BJS following the metal roughness convention.
  43231. *
  43232. * This fits to the PBR convention in the GLTF definition:
  43233. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43234. */
  43235. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43236. __extends(PBRMetallicRoughnessMaterial, _super);
  43237. /**
  43238. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43239. *
  43240. * @param name The material name
  43241. * @param scene The scene the material will be use in.
  43242. */
  43243. function PBRMetallicRoughnessMaterial(name, scene) {
  43244. var _this = _super.call(this, name, scene) || this;
  43245. _this._useRoughnessFromMetallicTextureAlpha = false;
  43246. _this._useRoughnessFromMetallicTextureGreen = true;
  43247. _this._useMetallnessFromMetallicTextureBlue = true;
  43248. _this.metallic = 1.0;
  43249. _this.roughness = 1.0;
  43250. return _this;
  43251. }
  43252. /**
  43253. * Return the currrent class name of the material.
  43254. */
  43255. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43256. return "PBRMetallicRoughnessMaterial";
  43257. };
  43258. /**
  43259. * Return the active textures of the material.
  43260. */
  43261. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43262. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43263. if (this.baseTexture) {
  43264. activeTextures.push(this.baseTexture);
  43265. }
  43266. if (this.metallicRoughnessTexture) {
  43267. activeTextures.push(this.metallicRoughnessTexture);
  43268. }
  43269. return activeTextures;
  43270. };
  43271. /**
  43272. * Checks to see if a texture is used in the material.
  43273. * @param texture - Base texture to use.
  43274. * @returns - Boolean specifying if a texture is used in the material.
  43275. */
  43276. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43277. if (_super.prototype.hasTexture.call(this, texture)) {
  43278. return true;
  43279. }
  43280. if (this.baseTexture === texture) {
  43281. return true;
  43282. }
  43283. if (this.metallicRoughnessTexture === texture) {
  43284. return true;
  43285. }
  43286. return false;
  43287. };
  43288. /**
  43289. * Makes a duplicate of the current material.
  43290. * @param name - name to use for the new material.
  43291. */
  43292. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43293. var _this = this;
  43294. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43295. clone.id = name;
  43296. clone.name = name;
  43297. return clone;
  43298. };
  43299. /**
  43300. * Serialize the material to a parsable JSON object.
  43301. */
  43302. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43303. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43304. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43305. return serializationObject;
  43306. };
  43307. /**
  43308. * Parses a JSON object correponding to the serialize function.
  43309. */
  43310. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43311. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43312. };
  43313. __decorate([
  43314. BABYLON.serializeAsColor3(),
  43315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43316. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43317. __decorate([
  43318. BABYLON.serializeAsTexture(),
  43319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43320. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43321. __decorate([
  43322. BABYLON.serialize(),
  43323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43324. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43325. __decorate([
  43326. BABYLON.serialize(),
  43327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43328. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43329. __decorate([
  43330. BABYLON.serializeAsTexture(),
  43331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43332. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43333. return PBRMetallicRoughnessMaterial;
  43334. }(BABYLON.PBRBaseSimpleMaterial));
  43335. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43336. })(BABYLON || (BABYLON = {}));
  43337. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43338. "use strict";
  43339. var BABYLON;
  43340. (function (BABYLON) {
  43341. /**
  43342. * The PBR material of BJS following the specular glossiness convention.
  43343. *
  43344. * This fits to the PBR convention in the GLTF definition:
  43345. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43346. */
  43347. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43348. __extends(PBRSpecularGlossinessMaterial, _super);
  43349. /**
  43350. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43351. *
  43352. * @param name The material name
  43353. * @param scene The scene the material will be use in.
  43354. */
  43355. function PBRSpecularGlossinessMaterial(name, scene) {
  43356. var _this = _super.call(this, name, scene) || this;
  43357. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43358. return _this;
  43359. }
  43360. /**
  43361. * Return the currrent class name of the material.
  43362. */
  43363. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43364. return "PBRSpecularGlossinessMaterial";
  43365. };
  43366. /**
  43367. * Return the active textures of the material.
  43368. */
  43369. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43370. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43371. if (this.diffuseTexture) {
  43372. activeTextures.push(this.diffuseTexture);
  43373. }
  43374. if (this.specularGlossinessTexture) {
  43375. activeTextures.push(this.specularGlossinessTexture);
  43376. }
  43377. return activeTextures;
  43378. };
  43379. /**
  43380. * Checks to see if a texture is used in the material.
  43381. * @param texture - Base texture to use.
  43382. * @returns - Boolean specifying if a texture is used in the material.
  43383. */
  43384. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43385. if (_super.prototype.hasTexture.call(this, texture)) {
  43386. return true;
  43387. }
  43388. if (this.diffuseTexture === texture) {
  43389. return true;
  43390. }
  43391. if (this.specularGlossinessTexture === texture) {
  43392. return true;
  43393. }
  43394. return false;
  43395. };
  43396. /**
  43397. * Makes a duplicate of the current material.
  43398. * @param name - name to use for the new material.
  43399. */
  43400. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43401. var _this = this;
  43402. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43403. clone.id = name;
  43404. clone.name = name;
  43405. return clone;
  43406. };
  43407. /**
  43408. * Serialize the material to a parsable JSON object.
  43409. */
  43410. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43411. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43412. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43413. return serializationObject;
  43414. };
  43415. /**
  43416. * Parses a JSON object correponding to the serialize function.
  43417. */
  43418. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43419. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43420. };
  43421. __decorate([
  43422. BABYLON.serializeAsColor3("diffuse"),
  43423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43424. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43425. __decorate([
  43426. BABYLON.serializeAsTexture(),
  43427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43428. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43429. __decorate([
  43430. BABYLON.serializeAsColor3("specular"),
  43431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43432. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43433. __decorate([
  43434. BABYLON.serialize(),
  43435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43436. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43437. __decorate([
  43438. BABYLON.serializeAsTexture(),
  43439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43440. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43441. return PBRSpecularGlossinessMaterial;
  43442. }(BABYLON.PBRBaseSimpleMaterial));
  43443. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43444. })(BABYLON || (BABYLON = {}));
  43445. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43446. "use strict";
  43447. var BABYLON;
  43448. (function (BABYLON) {
  43449. BABYLON.CameraInputTypes = {};
  43450. var CameraInputsManager = /** @class */ (function () {
  43451. function CameraInputsManager(camera) {
  43452. this.attached = {};
  43453. this.camera = camera;
  43454. this.checkInputs = function () { };
  43455. }
  43456. /**
  43457. * Add an input method to a camera.
  43458. * builtin inputs example: camera.inputs.addGamepad();
  43459. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43460. * @param input camera input method
  43461. */
  43462. CameraInputsManager.prototype.add = function (input) {
  43463. var type = input.getSimpleName();
  43464. if (this.attached[type]) {
  43465. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43466. return;
  43467. }
  43468. this.attached[type] = input;
  43469. input.camera = this.camera;
  43470. //for checkInputs, we are dynamically creating a function
  43471. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43472. if (input.checkInputs) {
  43473. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43474. }
  43475. if (this.attachedElement) {
  43476. input.attachControl(this.attachedElement);
  43477. }
  43478. };
  43479. /**
  43480. * Remove a specific input method from a camera
  43481. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43482. * @param inputToRemove camera input method
  43483. */
  43484. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43485. for (var cam in this.attached) {
  43486. var input = this.attached[cam];
  43487. if (input === inputToRemove) {
  43488. input.detachControl(this.attachedElement);
  43489. input.camera = null;
  43490. delete this.attached[cam];
  43491. this.rebuildInputCheck();
  43492. }
  43493. }
  43494. };
  43495. CameraInputsManager.prototype.removeByType = function (inputType) {
  43496. for (var cam in this.attached) {
  43497. var input = this.attached[cam];
  43498. if (input.getClassName() === inputType) {
  43499. input.detachControl(this.attachedElement);
  43500. input.camera = null;
  43501. delete this.attached[cam];
  43502. this.rebuildInputCheck();
  43503. }
  43504. }
  43505. };
  43506. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43507. var current = this.checkInputs;
  43508. return function () {
  43509. current();
  43510. fn();
  43511. };
  43512. };
  43513. CameraInputsManager.prototype.attachInput = function (input) {
  43514. if (this.attachedElement) {
  43515. input.attachControl(this.attachedElement, this.noPreventDefault);
  43516. }
  43517. };
  43518. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43519. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43520. if (this.attachedElement) {
  43521. return;
  43522. }
  43523. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43524. this.attachedElement = element;
  43525. this.noPreventDefault = noPreventDefault;
  43526. for (var cam in this.attached) {
  43527. this.attached[cam].attachControl(element, noPreventDefault);
  43528. }
  43529. };
  43530. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43531. if (disconnect === void 0) { disconnect = false; }
  43532. if (this.attachedElement !== element) {
  43533. return;
  43534. }
  43535. for (var cam in this.attached) {
  43536. this.attached[cam].detachControl(element);
  43537. if (disconnect) {
  43538. this.attached[cam].camera = null;
  43539. }
  43540. }
  43541. this.attachedElement = null;
  43542. };
  43543. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43544. this.checkInputs = function () { };
  43545. for (var cam in this.attached) {
  43546. var input = this.attached[cam];
  43547. if (input.checkInputs) {
  43548. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43549. }
  43550. }
  43551. };
  43552. /**
  43553. * Remove all attached input methods from a camera
  43554. */
  43555. CameraInputsManager.prototype.clear = function () {
  43556. if (this.attachedElement) {
  43557. this.detachElement(this.attachedElement, true);
  43558. }
  43559. this.attached = {};
  43560. this.attachedElement = null;
  43561. this.checkInputs = function () { };
  43562. };
  43563. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43564. var inputs = {};
  43565. for (var cam in this.attached) {
  43566. var input = this.attached[cam];
  43567. var res = BABYLON.SerializationHelper.Serialize(input);
  43568. inputs[input.getClassName()] = res;
  43569. }
  43570. serializedCamera.inputsmgr = inputs;
  43571. };
  43572. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43573. var parsedInputs = parsedCamera.inputsmgr;
  43574. if (parsedInputs) {
  43575. this.clear();
  43576. for (var n in parsedInputs) {
  43577. var construct = BABYLON.CameraInputTypes[n];
  43578. if (construct) {
  43579. var parsedinput = parsedInputs[n];
  43580. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43581. this.add(input);
  43582. }
  43583. }
  43584. }
  43585. else {
  43586. //2016-03-08 this part is for managing backward compatibility
  43587. for (var n in this.attached) {
  43588. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43589. if (construct) {
  43590. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43591. this.remove(this.attached[n]);
  43592. this.add(input);
  43593. }
  43594. }
  43595. }
  43596. };
  43597. return CameraInputsManager;
  43598. }());
  43599. BABYLON.CameraInputsManager = CameraInputsManager;
  43600. })(BABYLON || (BABYLON = {}));
  43601. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43602. "use strict";
  43603. var BABYLON;
  43604. (function (BABYLON) {
  43605. var TargetCamera = /** @class */ (function (_super) {
  43606. __extends(TargetCamera, _super);
  43607. function TargetCamera(name, position, scene) {
  43608. var _this = _super.call(this, name, position, scene) || this;
  43609. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43610. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43611. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43612. _this.speed = 2.0;
  43613. _this.noRotationConstraint = false;
  43614. _this.lockedTarget = null;
  43615. _this._currentTarget = BABYLON.Vector3.Zero();
  43616. _this._viewMatrix = BABYLON.Matrix.Zero();
  43617. _this._camMatrix = BABYLON.Matrix.Zero();
  43618. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43619. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43620. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43621. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43622. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43623. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43624. _this._tempMatrix = BABYLON.Matrix.Zero();
  43625. return _this;
  43626. }
  43627. TargetCamera.prototype.getFrontPosition = function (distance) {
  43628. this.getWorldMatrix();
  43629. var direction = this.getTarget().subtract(this.position);
  43630. direction.normalize();
  43631. direction.scaleInPlace(distance);
  43632. return this.globalPosition.add(direction);
  43633. };
  43634. TargetCamera.prototype._getLockedTargetPosition = function () {
  43635. if (!this.lockedTarget) {
  43636. return null;
  43637. }
  43638. if (this.lockedTarget.absolutePosition) {
  43639. this.lockedTarget.computeWorldMatrix();
  43640. }
  43641. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43642. };
  43643. TargetCamera.prototype.storeState = function () {
  43644. this._storedPosition = this.position.clone();
  43645. this._storedRotation = this.rotation.clone();
  43646. if (this.rotationQuaternion) {
  43647. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43648. }
  43649. return _super.prototype.storeState.call(this);
  43650. };
  43651. /**
  43652. * Restored camera state. You must call storeState() first
  43653. */
  43654. TargetCamera.prototype._restoreStateValues = function () {
  43655. if (!_super.prototype._restoreStateValues.call(this)) {
  43656. return false;
  43657. }
  43658. this.position = this._storedPosition.clone();
  43659. this.rotation = this._storedRotation.clone();
  43660. if (this.rotationQuaternion) {
  43661. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43662. }
  43663. this.cameraDirection.copyFromFloats(0, 0, 0);
  43664. this.cameraRotation.copyFromFloats(0, 0);
  43665. return true;
  43666. };
  43667. // Cache
  43668. TargetCamera.prototype._initCache = function () {
  43669. _super.prototype._initCache.call(this);
  43670. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43671. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43672. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43673. };
  43674. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43675. if (!ignoreParentClass) {
  43676. _super.prototype._updateCache.call(this);
  43677. }
  43678. var lockedTargetPosition = this._getLockedTargetPosition();
  43679. if (!lockedTargetPosition) {
  43680. this._cache.lockedTarget = null;
  43681. }
  43682. else {
  43683. if (!this._cache.lockedTarget) {
  43684. this._cache.lockedTarget = lockedTargetPosition.clone();
  43685. }
  43686. else {
  43687. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43688. }
  43689. }
  43690. this._cache.rotation.copyFrom(this.rotation);
  43691. if (this.rotationQuaternion)
  43692. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43693. };
  43694. // Synchronized
  43695. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43696. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43697. return false;
  43698. }
  43699. var lockedTargetPosition = this._getLockedTargetPosition();
  43700. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43701. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43702. };
  43703. // Methods
  43704. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43705. var engine = this.getEngine();
  43706. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43707. };
  43708. // Target
  43709. TargetCamera.prototype.setTarget = function (target) {
  43710. this.upVector.normalize();
  43711. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43712. this._camMatrix.invert();
  43713. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43714. var vDir = target.subtract(this.position);
  43715. if (vDir.x >= 0.0) {
  43716. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43717. }
  43718. else {
  43719. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43720. }
  43721. this.rotation.z = 0;
  43722. if (isNaN(this.rotation.x)) {
  43723. this.rotation.x = 0;
  43724. }
  43725. if (isNaN(this.rotation.y)) {
  43726. this.rotation.y = 0;
  43727. }
  43728. if (isNaN(this.rotation.z)) {
  43729. this.rotation.z = 0;
  43730. }
  43731. if (this.rotationQuaternion) {
  43732. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43733. }
  43734. };
  43735. /**
  43736. * Return the current target position of the camera. This value is expressed in local space.
  43737. */
  43738. TargetCamera.prototype.getTarget = function () {
  43739. return this._currentTarget;
  43740. };
  43741. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43742. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43743. };
  43744. TargetCamera.prototype._updatePosition = function () {
  43745. if (this.parent) {
  43746. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43747. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43748. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43749. return;
  43750. }
  43751. this.position.addInPlace(this.cameraDirection);
  43752. };
  43753. TargetCamera.prototype._checkInputs = function () {
  43754. var needToMove = this._decideIfNeedsToMove();
  43755. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43756. // Move
  43757. if (needToMove) {
  43758. this._updatePosition();
  43759. }
  43760. // Rotate
  43761. if (needToRotate) {
  43762. this.rotation.x += this.cameraRotation.x;
  43763. this.rotation.y += this.cameraRotation.y;
  43764. //rotate, if quaternion is set and rotation was used
  43765. if (this.rotationQuaternion) {
  43766. var len = this.rotation.lengthSquared();
  43767. if (len) {
  43768. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43769. }
  43770. }
  43771. if (!this.noRotationConstraint) {
  43772. var limit = (Math.PI / 2) * 0.95;
  43773. if (this.rotation.x > limit)
  43774. this.rotation.x = limit;
  43775. if (this.rotation.x < -limit)
  43776. this.rotation.x = -limit;
  43777. }
  43778. }
  43779. // Inertia
  43780. if (needToMove) {
  43781. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43782. this.cameraDirection.x = 0;
  43783. }
  43784. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43785. this.cameraDirection.y = 0;
  43786. }
  43787. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43788. this.cameraDirection.z = 0;
  43789. }
  43790. this.cameraDirection.scaleInPlace(this.inertia);
  43791. }
  43792. if (needToRotate) {
  43793. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43794. this.cameraRotation.x = 0;
  43795. }
  43796. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43797. this.cameraRotation.y = 0;
  43798. }
  43799. this.cameraRotation.scaleInPlace(this.inertia);
  43800. }
  43801. _super.prototype._checkInputs.call(this);
  43802. };
  43803. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43804. if (this.rotationQuaternion) {
  43805. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43806. }
  43807. else {
  43808. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43809. }
  43810. //update the up vector!
  43811. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43812. };
  43813. TargetCamera.prototype._getViewMatrix = function () {
  43814. if (this.lockedTarget) {
  43815. this.setTarget(this._getLockedTargetPosition());
  43816. }
  43817. // Compute
  43818. this._updateCameraRotationMatrix();
  43819. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43820. // Computing target and final matrix
  43821. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43822. if (this.getScene().useRightHandedSystem) {
  43823. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43824. }
  43825. else {
  43826. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43827. }
  43828. return this._viewMatrix;
  43829. };
  43830. /**
  43831. * @override
  43832. * Override Camera.createRigCamera
  43833. */
  43834. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43835. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43836. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43837. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43838. if (!this.rotationQuaternion) {
  43839. this.rotationQuaternion = new BABYLON.Quaternion();
  43840. }
  43841. rigCamera._cameraRigParams = {};
  43842. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43843. }
  43844. return rigCamera;
  43845. }
  43846. return null;
  43847. };
  43848. /**
  43849. * @override
  43850. * Override Camera._updateRigCameras
  43851. */
  43852. TargetCamera.prototype._updateRigCameras = function () {
  43853. var camLeft = this._rigCameras[0];
  43854. var camRight = this._rigCameras[1];
  43855. switch (this.cameraRigMode) {
  43856. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43857. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43858. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43859. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43860. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43861. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43862. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43863. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43864. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43865. camLeft.setTarget(this.getTarget());
  43866. camRight.setTarget(this.getTarget());
  43867. break;
  43868. case BABYLON.Camera.RIG_MODE_VR:
  43869. if (camLeft.rotationQuaternion) {
  43870. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43871. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43872. }
  43873. else {
  43874. camLeft.rotation.copyFrom(this.rotation);
  43875. camRight.rotation.copyFrom(this.rotation);
  43876. }
  43877. camLeft.position.copyFrom(this.position);
  43878. camRight.position.copyFrom(this.position);
  43879. break;
  43880. }
  43881. _super.prototype._updateRigCameras.call(this);
  43882. };
  43883. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43884. if (!this._rigCamTransformMatrix) {
  43885. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43886. }
  43887. var target = this.getTarget();
  43888. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43889. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43890. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43891. };
  43892. TargetCamera.prototype.getClassName = function () {
  43893. return "TargetCamera";
  43894. };
  43895. __decorate([
  43896. BABYLON.serializeAsVector3()
  43897. ], TargetCamera.prototype, "rotation", void 0);
  43898. __decorate([
  43899. BABYLON.serialize()
  43900. ], TargetCamera.prototype, "speed", void 0);
  43901. __decorate([
  43902. BABYLON.serializeAsMeshReference("lockedTargetId")
  43903. ], TargetCamera.prototype, "lockedTarget", void 0);
  43904. return TargetCamera;
  43905. }(BABYLON.Camera));
  43906. BABYLON.TargetCamera = TargetCamera;
  43907. })(BABYLON || (BABYLON = {}));
  43908. //# sourceMappingURL=babylon.targetCamera.js.map
  43909. "use strict";
  43910. var BABYLON;
  43911. (function (BABYLON) {
  43912. var FreeCameraMouseInput = /** @class */ (function () {
  43913. function FreeCameraMouseInput(touchEnabled) {
  43914. if (touchEnabled === void 0) { touchEnabled = true; }
  43915. this.touchEnabled = touchEnabled;
  43916. this.buttons = [0, 1, 2];
  43917. this.angularSensibility = 2000.0;
  43918. this.previousPosition = null;
  43919. }
  43920. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43921. var _this = this;
  43922. var engine = this.camera.getEngine();
  43923. if (!this._pointerInput) {
  43924. this._pointerInput = function (p, s) {
  43925. var evt = p.event;
  43926. if (engine.isInVRExclusivePointerMode) {
  43927. return;
  43928. }
  43929. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43930. return;
  43931. }
  43932. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43933. return;
  43934. }
  43935. var srcElement = (evt.srcElement || evt.target);
  43936. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43937. try {
  43938. srcElement.setPointerCapture(evt.pointerId);
  43939. }
  43940. catch (e) {
  43941. //Nothing to do with the error. Execution will continue.
  43942. }
  43943. _this.previousPosition = {
  43944. x: evt.clientX,
  43945. y: evt.clientY
  43946. };
  43947. if (!noPreventDefault) {
  43948. evt.preventDefault();
  43949. element.focus();
  43950. }
  43951. }
  43952. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43953. try {
  43954. srcElement.releasePointerCapture(evt.pointerId);
  43955. }
  43956. catch (e) {
  43957. //Nothing to do with the error.
  43958. }
  43959. _this.previousPosition = null;
  43960. if (!noPreventDefault) {
  43961. evt.preventDefault();
  43962. }
  43963. }
  43964. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43965. if (!_this.previousPosition || engine.isPointerLock) {
  43966. return;
  43967. }
  43968. var offsetX = evt.clientX - _this.previousPosition.x;
  43969. var offsetY = evt.clientY - _this.previousPosition.y;
  43970. if (_this.camera.getScene().useRightHandedSystem) {
  43971. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43972. }
  43973. else {
  43974. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43975. }
  43976. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43977. _this.previousPosition = {
  43978. x: evt.clientX,
  43979. y: evt.clientY
  43980. };
  43981. if (!noPreventDefault) {
  43982. evt.preventDefault();
  43983. }
  43984. }
  43985. };
  43986. }
  43987. this._onMouseMove = function (evt) {
  43988. if (!engine.isPointerLock) {
  43989. return;
  43990. }
  43991. if (engine.isInVRExclusivePointerMode) {
  43992. return;
  43993. }
  43994. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43995. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43996. if (_this.camera.getScene().useRightHandedSystem) {
  43997. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43998. }
  43999. else {
  44000. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44001. }
  44002. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44003. _this.previousPosition = null;
  44004. if (!noPreventDefault) {
  44005. evt.preventDefault();
  44006. }
  44007. };
  44008. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44009. element.addEventListener("mousemove", this._onMouseMove, false);
  44010. };
  44011. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44012. if (this._observer && element) {
  44013. this.camera.getScene().onPointerObservable.remove(this._observer);
  44014. if (this._onMouseMove) {
  44015. element.removeEventListener("mousemove", this._onMouseMove);
  44016. }
  44017. this._observer = null;
  44018. this._onMouseMove = null;
  44019. this.previousPosition = null;
  44020. }
  44021. };
  44022. FreeCameraMouseInput.prototype.getClassName = function () {
  44023. return "FreeCameraMouseInput";
  44024. };
  44025. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44026. return "mouse";
  44027. };
  44028. __decorate([
  44029. BABYLON.serialize()
  44030. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44031. __decorate([
  44032. BABYLON.serialize()
  44033. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44034. return FreeCameraMouseInput;
  44035. }());
  44036. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44037. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44038. })(BABYLON || (BABYLON = {}));
  44039. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44040. "use strict";
  44041. var BABYLON;
  44042. (function (BABYLON) {
  44043. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44044. function FreeCameraKeyboardMoveInput() {
  44045. this._keys = new Array();
  44046. this.keysUp = [38];
  44047. this.keysDown = [40];
  44048. this.keysLeft = [37];
  44049. this.keysRight = [39];
  44050. }
  44051. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44052. var _this = this;
  44053. if (this._onCanvasBlurObserver) {
  44054. return;
  44055. }
  44056. this._scene = this.camera.getScene();
  44057. this._engine = this._scene.getEngine();
  44058. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44059. _this._keys = [];
  44060. });
  44061. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44062. var evt = info.event;
  44063. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44064. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44065. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44066. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44067. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44068. var index = _this._keys.indexOf(evt.keyCode);
  44069. if (index === -1) {
  44070. _this._keys.push(evt.keyCode);
  44071. }
  44072. if (!noPreventDefault) {
  44073. evt.preventDefault();
  44074. }
  44075. }
  44076. }
  44077. else {
  44078. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44079. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44080. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44081. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44082. var index = _this._keys.indexOf(evt.keyCode);
  44083. if (index >= 0) {
  44084. _this._keys.splice(index, 1);
  44085. }
  44086. if (!noPreventDefault) {
  44087. evt.preventDefault();
  44088. }
  44089. }
  44090. }
  44091. });
  44092. };
  44093. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44094. if (this._scene) {
  44095. if (this._onKeyboardObserver) {
  44096. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44097. }
  44098. if (this._onCanvasBlurObserver) {
  44099. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44100. }
  44101. this._onKeyboardObserver = null;
  44102. this._onCanvasBlurObserver = null;
  44103. }
  44104. this._keys = [];
  44105. };
  44106. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44107. if (this._onKeyboardObserver) {
  44108. var camera = this.camera;
  44109. // Keyboard
  44110. for (var index = 0; index < this._keys.length; index++) {
  44111. var keyCode = this._keys[index];
  44112. var speed = camera._computeLocalCameraSpeed();
  44113. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44114. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44115. }
  44116. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44117. camera._localDirection.copyFromFloats(0, 0, speed);
  44118. }
  44119. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44120. camera._localDirection.copyFromFloats(speed, 0, 0);
  44121. }
  44122. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44123. camera._localDirection.copyFromFloats(0, 0, -speed);
  44124. }
  44125. if (camera.getScene().useRightHandedSystem) {
  44126. camera._localDirection.z *= -1;
  44127. }
  44128. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44129. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44130. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44131. }
  44132. }
  44133. };
  44134. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44135. return "FreeCameraKeyboardMoveInput";
  44136. };
  44137. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44138. this._keys = [];
  44139. };
  44140. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44141. return "keyboard";
  44142. };
  44143. __decorate([
  44144. BABYLON.serialize()
  44145. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44146. __decorate([
  44147. BABYLON.serialize()
  44148. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44149. __decorate([
  44150. BABYLON.serialize()
  44151. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44152. __decorate([
  44153. BABYLON.serialize()
  44154. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44155. return FreeCameraKeyboardMoveInput;
  44156. }());
  44157. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44158. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44159. })(BABYLON || (BABYLON = {}));
  44160. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44161. "use strict";
  44162. var BABYLON;
  44163. (function (BABYLON) {
  44164. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44165. __extends(FreeCameraInputsManager, _super);
  44166. function FreeCameraInputsManager(camera) {
  44167. return _super.call(this, camera) || this;
  44168. }
  44169. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44170. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44171. return this;
  44172. };
  44173. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44174. if (touchEnabled === void 0) { touchEnabled = true; }
  44175. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44176. return this;
  44177. };
  44178. FreeCameraInputsManager.prototype.addGamepad = function () {
  44179. this.add(new BABYLON.FreeCameraGamepadInput());
  44180. return this;
  44181. };
  44182. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44183. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44184. return this;
  44185. };
  44186. FreeCameraInputsManager.prototype.addTouch = function () {
  44187. this.add(new BABYLON.FreeCameraTouchInput());
  44188. return this;
  44189. };
  44190. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44191. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44192. return this;
  44193. };
  44194. return FreeCameraInputsManager;
  44195. }(BABYLON.CameraInputsManager));
  44196. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44197. })(BABYLON || (BABYLON = {}));
  44198. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44199. "use strict";
  44200. var BABYLON;
  44201. (function (BABYLON) {
  44202. var FreeCamera = /** @class */ (function (_super) {
  44203. __extends(FreeCamera, _super);
  44204. function FreeCamera(name, position, scene) {
  44205. var _this = _super.call(this, name, position, scene) || this;
  44206. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44207. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44208. _this.checkCollisions = false;
  44209. _this.applyGravity = false;
  44210. _this._needMoveForGravity = false;
  44211. _this._oldPosition = BABYLON.Vector3.Zero();
  44212. _this._diffPosition = BABYLON.Vector3.Zero();
  44213. _this._newPosition = BABYLON.Vector3.Zero();
  44214. // Collisions
  44215. _this._collisionMask = -1;
  44216. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44217. if (collidedMesh === void 0) { collidedMesh = null; }
  44218. //TODO move this to the collision coordinator!
  44219. if (_this.getScene().workerCollisions)
  44220. newPosition.multiplyInPlace(_this._collider._radius);
  44221. var updatePosition = function (newPos) {
  44222. _this._newPosition.copyFrom(newPos);
  44223. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44224. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44225. _this.position.addInPlace(_this._diffPosition);
  44226. if (_this.onCollide && collidedMesh) {
  44227. _this.onCollide(collidedMesh);
  44228. }
  44229. }
  44230. };
  44231. updatePosition(newPosition);
  44232. };
  44233. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44234. _this.inputs.addKeyboard().addMouse();
  44235. return _this;
  44236. }
  44237. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44238. //-- begin properties for backward compatibility for inputs
  44239. /**
  44240. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44241. * Higher values reduce sensitivity.
  44242. */
  44243. get: function () {
  44244. var mouse = this.inputs.attached["mouse"];
  44245. if (mouse)
  44246. return mouse.angularSensibility;
  44247. return 0;
  44248. },
  44249. /**
  44250. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44251. * Higher values reduce sensitivity.
  44252. */
  44253. set: function (value) {
  44254. var mouse = this.inputs.attached["mouse"];
  44255. if (mouse)
  44256. mouse.angularSensibility = value;
  44257. },
  44258. enumerable: true,
  44259. configurable: true
  44260. });
  44261. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44262. get: function () {
  44263. var keyboard = this.inputs.attached["keyboard"];
  44264. if (keyboard)
  44265. return keyboard.keysUp;
  44266. return [];
  44267. },
  44268. set: function (value) {
  44269. var keyboard = this.inputs.attached["keyboard"];
  44270. if (keyboard)
  44271. keyboard.keysUp = value;
  44272. },
  44273. enumerable: true,
  44274. configurable: true
  44275. });
  44276. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44277. get: function () {
  44278. var keyboard = this.inputs.attached["keyboard"];
  44279. if (keyboard)
  44280. return keyboard.keysDown;
  44281. return [];
  44282. },
  44283. set: function (value) {
  44284. var keyboard = this.inputs.attached["keyboard"];
  44285. if (keyboard)
  44286. keyboard.keysDown = value;
  44287. },
  44288. enumerable: true,
  44289. configurable: true
  44290. });
  44291. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44292. get: function () {
  44293. var keyboard = this.inputs.attached["keyboard"];
  44294. if (keyboard)
  44295. return keyboard.keysLeft;
  44296. return [];
  44297. },
  44298. set: function (value) {
  44299. var keyboard = this.inputs.attached["keyboard"];
  44300. if (keyboard)
  44301. keyboard.keysLeft = value;
  44302. },
  44303. enumerable: true,
  44304. configurable: true
  44305. });
  44306. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44307. get: function () {
  44308. var keyboard = this.inputs.attached["keyboard"];
  44309. if (keyboard)
  44310. return keyboard.keysRight;
  44311. return [];
  44312. },
  44313. set: function (value) {
  44314. var keyboard = this.inputs.attached["keyboard"];
  44315. if (keyboard)
  44316. keyboard.keysRight = value;
  44317. },
  44318. enumerable: true,
  44319. configurable: true
  44320. });
  44321. // Controls
  44322. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44323. this.inputs.attachElement(element, noPreventDefault);
  44324. };
  44325. FreeCamera.prototype.detachControl = function (element) {
  44326. this.inputs.detachElement(element);
  44327. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44328. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44329. };
  44330. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44331. get: function () {
  44332. return this._collisionMask;
  44333. },
  44334. set: function (mask) {
  44335. this._collisionMask = !isNaN(mask) ? mask : -1;
  44336. },
  44337. enumerable: true,
  44338. configurable: true
  44339. });
  44340. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44341. var globalPosition;
  44342. if (this.parent) {
  44343. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44344. }
  44345. else {
  44346. globalPosition = this.position;
  44347. }
  44348. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44349. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44350. if (!this._collider) {
  44351. this._collider = new BABYLON.Collider();
  44352. }
  44353. this._collider._radius = this.ellipsoid;
  44354. this._collider.collisionMask = this._collisionMask;
  44355. //no need for clone, as long as gravity is not on.
  44356. var actualDisplacement = displacement;
  44357. //add gravity to the direction to prevent the dual-collision checking
  44358. if (this.applyGravity) {
  44359. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44360. actualDisplacement = displacement.add(this.getScene().gravity);
  44361. }
  44362. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44363. };
  44364. FreeCamera.prototype._checkInputs = function () {
  44365. if (!this._localDirection) {
  44366. this._localDirection = BABYLON.Vector3.Zero();
  44367. this._transformedDirection = BABYLON.Vector3.Zero();
  44368. }
  44369. this.inputs.checkInputs();
  44370. _super.prototype._checkInputs.call(this);
  44371. };
  44372. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44373. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44374. };
  44375. FreeCamera.prototype._updatePosition = function () {
  44376. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44377. this._collideWithWorld(this.cameraDirection);
  44378. }
  44379. else {
  44380. _super.prototype._updatePosition.call(this);
  44381. }
  44382. };
  44383. FreeCamera.prototype.dispose = function () {
  44384. this.inputs.clear();
  44385. _super.prototype.dispose.call(this);
  44386. };
  44387. FreeCamera.prototype.getClassName = function () {
  44388. return "FreeCamera";
  44389. };
  44390. __decorate([
  44391. BABYLON.serializeAsVector3()
  44392. ], FreeCamera.prototype, "ellipsoid", void 0);
  44393. __decorate([
  44394. BABYLON.serializeAsVector3()
  44395. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44396. __decorate([
  44397. BABYLON.serialize()
  44398. ], FreeCamera.prototype, "checkCollisions", void 0);
  44399. __decorate([
  44400. BABYLON.serialize()
  44401. ], FreeCamera.prototype, "applyGravity", void 0);
  44402. return FreeCamera;
  44403. }(BABYLON.TargetCamera));
  44404. BABYLON.FreeCamera = FreeCamera;
  44405. })(BABYLON || (BABYLON = {}));
  44406. //# sourceMappingURL=babylon.freeCamera.js.map
  44407. "use strict";
  44408. var BABYLON;
  44409. (function (BABYLON) {
  44410. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44411. function ArcRotateCameraKeyboardMoveInput() {
  44412. this._keys = new Array();
  44413. this.keysUp = [38];
  44414. this.keysDown = [40];
  44415. this.keysLeft = [37];
  44416. this.keysRight = [39];
  44417. this.keysReset = [220];
  44418. this.panningSensibility = 50.0;
  44419. this.zoomingSensibility = 25.0;
  44420. this.useAltToZoom = true;
  44421. }
  44422. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44423. var _this = this;
  44424. if (this._onCanvasBlurObserver) {
  44425. return;
  44426. }
  44427. this._scene = this.camera.getScene();
  44428. this._engine = this._scene.getEngine();
  44429. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44430. _this._keys = [];
  44431. });
  44432. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44433. var evt = info.event;
  44434. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44435. _this._ctrlPressed = evt.ctrlKey;
  44436. _this._altPressed = evt.altKey;
  44437. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44438. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44439. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44440. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44441. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44442. var index = _this._keys.indexOf(evt.keyCode);
  44443. if (index === -1) {
  44444. _this._keys.push(evt.keyCode);
  44445. }
  44446. if (evt.preventDefault) {
  44447. if (!noPreventDefault) {
  44448. evt.preventDefault();
  44449. }
  44450. }
  44451. }
  44452. }
  44453. else {
  44454. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44455. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44456. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44457. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44458. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44459. var index = _this._keys.indexOf(evt.keyCode);
  44460. if (index >= 0) {
  44461. _this._keys.splice(index, 1);
  44462. }
  44463. if (evt.preventDefault) {
  44464. if (!noPreventDefault) {
  44465. evt.preventDefault();
  44466. }
  44467. }
  44468. }
  44469. }
  44470. });
  44471. };
  44472. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44473. if (this._scene) {
  44474. if (this._onKeyboardObserver) {
  44475. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44476. }
  44477. if (this._onCanvasBlurObserver) {
  44478. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44479. }
  44480. this._onKeyboardObserver = null;
  44481. this._onCanvasBlurObserver = null;
  44482. }
  44483. this._keys = [];
  44484. };
  44485. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44486. if (this._onKeyboardObserver) {
  44487. var camera = this.camera;
  44488. for (var index = 0; index < this._keys.length; index++) {
  44489. var keyCode = this._keys[index];
  44490. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44491. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44492. camera.inertialPanningX -= 1 / this.panningSensibility;
  44493. }
  44494. else {
  44495. camera.inertialAlphaOffset -= 0.01;
  44496. }
  44497. }
  44498. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44499. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44500. camera.inertialPanningY += 1 / this.panningSensibility;
  44501. }
  44502. else if (this._altPressed && this.useAltToZoom) {
  44503. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44504. }
  44505. else {
  44506. camera.inertialBetaOffset -= 0.01;
  44507. }
  44508. }
  44509. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44510. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44511. camera.inertialPanningX += 1 / this.panningSensibility;
  44512. }
  44513. else {
  44514. camera.inertialAlphaOffset += 0.01;
  44515. }
  44516. }
  44517. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44518. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44519. camera.inertialPanningY -= 1 / this.panningSensibility;
  44520. }
  44521. else if (this._altPressed && this.useAltToZoom) {
  44522. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44523. }
  44524. else {
  44525. camera.inertialBetaOffset += 0.01;
  44526. }
  44527. }
  44528. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44529. camera.restoreState();
  44530. }
  44531. }
  44532. }
  44533. };
  44534. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44535. return "ArcRotateCameraKeyboardMoveInput";
  44536. };
  44537. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44538. return "keyboard";
  44539. };
  44540. __decorate([
  44541. BABYLON.serialize()
  44542. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44543. __decorate([
  44544. BABYLON.serialize()
  44545. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44546. __decorate([
  44547. BABYLON.serialize()
  44548. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44549. __decorate([
  44550. BABYLON.serialize()
  44551. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44552. __decorate([
  44553. BABYLON.serialize()
  44554. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44555. __decorate([
  44556. BABYLON.serialize()
  44557. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44558. __decorate([
  44559. BABYLON.serialize()
  44560. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44561. __decorate([
  44562. BABYLON.serialize()
  44563. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44564. return ArcRotateCameraKeyboardMoveInput;
  44565. }());
  44566. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44567. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44568. })(BABYLON || (BABYLON = {}));
  44569. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44570. "use strict";
  44571. var BABYLON;
  44572. (function (BABYLON) {
  44573. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44574. function ArcRotateCameraMouseWheelInput() {
  44575. this.wheelPrecision = 3.0;
  44576. /**
  44577. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44578. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44579. */
  44580. this.wheelDeltaPercentage = 0;
  44581. }
  44582. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44583. var _this = this;
  44584. this._wheel = function (p, s) {
  44585. //sanity check - this should be a PointerWheel event.
  44586. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44587. return;
  44588. var event = p.event;
  44589. var delta = 0;
  44590. if (event.wheelDelta) {
  44591. if (_this.wheelDeltaPercentage) {
  44592. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  44593. if (event.wheelDelta > 0) {
  44594. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  44595. }
  44596. else {
  44597. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  44598. }
  44599. }
  44600. else {
  44601. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  44602. }
  44603. }
  44604. else if (event.detail) {
  44605. delta = -event.detail / _this.wheelPrecision;
  44606. }
  44607. if (delta)
  44608. _this.camera.inertialRadiusOffset += delta;
  44609. if (event.preventDefault) {
  44610. if (!noPreventDefault) {
  44611. event.preventDefault();
  44612. }
  44613. }
  44614. };
  44615. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44616. };
  44617. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44618. if (this._observer && element) {
  44619. this.camera.getScene().onPointerObservable.remove(this._observer);
  44620. this._observer = null;
  44621. this._wheel = null;
  44622. }
  44623. };
  44624. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44625. return "ArcRotateCameraMouseWheelInput";
  44626. };
  44627. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44628. return "mousewheel";
  44629. };
  44630. __decorate([
  44631. BABYLON.serialize()
  44632. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44633. __decorate([
  44634. BABYLON.serialize()
  44635. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44636. return ArcRotateCameraMouseWheelInput;
  44637. }());
  44638. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44639. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44640. })(BABYLON || (BABYLON = {}));
  44641. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44642. "use strict";
  44643. var BABYLON;
  44644. (function (BABYLON) {
  44645. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44646. function ArcRotateCameraPointersInput() {
  44647. this.buttons = [0, 1, 2];
  44648. this.angularSensibilityX = 1000.0;
  44649. this.angularSensibilityY = 1000.0;
  44650. this.pinchPrecision = 12.0;
  44651. /**
  44652. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44653. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44654. */
  44655. this.pinchDeltaPercentage = 0;
  44656. this.panningSensibility = 1000.0;
  44657. this.multiTouchPanning = true;
  44658. this.multiTouchPanAndZoom = true;
  44659. this._isPanClick = false;
  44660. this.pinchInwards = true;
  44661. }
  44662. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44663. var _this = this;
  44664. var engine = this.camera.getEngine();
  44665. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44666. var pointA = null;
  44667. var pointB = null;
  44668. var previousPinchSquaredDistance = 0;
  44669. var initialDistance = 0;
  44670. var twoFingerActivityCount = 0;
  44671. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44672. this._pointerInput = function (p, s) {
  44673. var evt = p.event;
  44674. var isTouch = p.event.pointerType === "touch";
  44675. if (engine.isInVRExclusivePointerMode) {
  44676. return;
  44677. }
  44678. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44679. return;
  44680. }
  44681. var srcElement = (evt.srcElement || evt.target);
  44682. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44683. try {
  44684. srcElement.setPointerCapture(evt.pointerId);
  44685. }
  44686. catch (e) {
  44687. //Nothing to do with the error. Execution will continue.
  44688. }
  44689. // Manage panning with pan button click
  44690. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44691. // manage pointers
  44692. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44693. if (pointA === null) {
  44694. pointA = cacheSoloPointer;
  44695. }
  44696. else if (pointB === null) {
  44697. pointB = cacheSoloPointer;
  44698. }
  44699. if (!noPreventDefault) {
  44700. evt.preventDefault();
  44701. element.focus();
  44702. }
  44703. }
  44704. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44705. _this.camera.restoreState();
  44706. }
  44707. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44708. try {
  44709. srcElement.releasePointerCapture(evt.pointerId);
  44710. }
  44711. catch (e) {
  44712. //Nothing to do with the error.
  44713. }
  44714. cacheSoloPointer = null;
  44715. previousPinchSquaredDistance = 0;
  44716. previousMultiTouchPanPosition.isPaning = false;
  44717. previousMultiTouchPanPosition.isPinching = false;
  44718. twoFingerActivityCount = 0;
  44719. initialDistance = 0;
  44720. if (!isTouch) {
  44721. pointB = null; // Mouse and pen are mono pointer
  44722. }
  44723. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44724. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44725. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44726. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44727. if (engine.badOS) {
  44728. pointA = pointB = null;
  44729. }
  44730. else {
  44731. //only remove the impacted pointer in case of multitouch allowing on most
  44732. //platforms switching from rotate to zoom and pan seamlessly.
  44733. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44734. pointA = pointB;
  44735. pointB = null;
  44736. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44737. }
  44738. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44739. pointB = null;
  44740. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44741. }
  44742. else {
  44743. pointA = pointB = null;
  44744. }
  44745. }
  44746. if (!noPreventDefault) {
  44747. evt.preventDefault();
  44748. }
  44749. }
  44750. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44751. if (!noPreventDefault) {
  44752. evt.preventDefault();
  44753. }
  44754. // One button down
  44755. if (pointA && pointB === null && cacheSoloPointer) {
  44756. if (_this.panningSensibility !== 0 &&
  44757. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44758. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44759. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44760. }
  44761. else {
  44762. var offsetX = evt.clientX - cacheSoloPointer.x;
  44763. var offsetY = evt.clientY - cacheSoloPointer.y;
  44764. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44765. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44766. }
  44767. cacheSoloPointer.x = evt.clientX;
  44768. cacheSoloPointer.y = evt.clientY;
  44769. }
  44770. else if (pointA && pointB) {
  44771. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44772. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44773. ed.x = evt.clientX;
  44774. ed.y = evt.clientY;
  44775. var direction = _this.pinchInwards ? 1 : -1;
  44776. var distX = pointA.x - pointB.x;
  44777. var distY = pointA.y - pointB.y;
  44778. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44779. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44780. if (previousPinchSquaredDistance === 0) {
  44781. initialDistance = pinchDistance;
  44782. previousPinchSquaredDistance = pinchSquaredDistance;
  44783. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44784. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44785. return;
  44786. }
  44787. if (_this.multiTouchPanAndZoom) {
  44788. if (_this.pinchDeltaPercentage) {
  44789. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44790. }
  44791. else {
  44792. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44793. (_this.pinchPrecision *
  44794. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44795. direction);
  44796. }
  44797. if (_this.panningSensibility !== 0) {
  44798. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44799. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44800. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44801. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44802. previousMultiTouchPanPosition.x = pointersCenterX;
  44803. previousMultiTouchPanPosition.y = pointersCenterY;
  44804. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44805. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44806. }
  44807. }
  44808. else {
  44809. twoFingerActivityCount++;
  44810. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44811. if (_this.pinchDeltaPercentage) {
  44812. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44813. }
  44814. else {
  44815. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44816. (_this.pinchPrecision *
  44817. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44818. direction);
  44819. }
  44820. previousMultiTouchPanPosition.isPaning = false;
  44821. previousMultiTouchPanPosition.isPinching = true;
  44822. }
  44823. else {
  44824. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44825. if (!previousMultiTouchPanPosition.isPaning) {
  44826. previousMultiTouchPanPosition.isPaning = true;
  44827. previousMultiTouchPanPosition.isPinching = false;
  44828. previousMultiTouchPanPosition.x = ed.x;
  44829. previousMultiTouchPanPosition.y = ed.y;
  44830. return;
  44831. }
  44832. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44833. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44834. }
  44835. }
  44836. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44837. previousMultiTouchPanPosition.x = ed.x;
  44838. previousMultiTouchPanPosition.y = ed.y;
  44839. }
  44840. }
  44841. previousPinchSquaredDistance = pinchSquaredDistance;
  44842. }
  44843. }
  44844. };
  44845. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44846. this._onContextMenu = function (evt) {
  44847. evt.preventDefault();
  44848. };
  44849. if (!this.camera._useCtrlForPanning) {
  44850. element.addEventListener("contextmenu", this._onContextMenu, false);
  44851. }
  44852. this._onLostFocus = function () {
  44853. //this._keys = [];
  44854. pointA = pointB = null;
  44855. previousPinchSquaredDistance = 0;
  44856. previousMultiTouchPanPosition.isPaning = false;
  44857. previousMultiTouchPanPosition.isPinching = false;
  44858. twoFingerActivityCount = 0;
  44859. cacheSoloPointer = null;
  44860. initialDistance = 0;
  44861. };
  44862. this._onMouseMove = function (evt) {
  44863. if (!engine.isPointerLock) {
  44864. return;
  44865. }
  44866. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44867. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44868. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44869. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44870. if (!noPreventDefault) {
  44871. evt.preventDefault();
  44872. }
  44873. };
  44874. this._onGestureStart = function (e) {
  44875. if (window.MSGesture === undefined) {
  44876. return;
  44877. }
  44878. if (!_this._MSGestureHandler) {
  44879. _this._MSGestureHandler = new MSGesture();
  44880. _this._MSGestureHandler.target = element;
  44881. }
  44882. _this._MSGestureHandler.addPointer(e.pointerId);
  44883. };
  44884. this._onGesture = function (e) {
  44885. _this.camera.radius *= e.scale;
  44886. if (e.preventDefault) {
  44887. if (!noPreventDefault) {
  44888. e.stopPropagation();
  44889. e.preventDefault();
  44890. }
  44891. }
  44892. };
  44893. element.addEventListener("mousemove", this._onMouseMove, false);
  44894. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44895. element.addEventListener("MSGestureChange", this._onGesture, false);
  44896. BABYLON.Tools.RegisterTopRootEvents([
  44897. { name: "blur", handler: this._onLostFocus }
  44898. ]);
  44899. };
  44900. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44901. if (this._onLostFocus) {
  44902. BABYLON.Tools.UnregisterTopRootEvents([
  44903. { name: "blur", handler: this._onLostFocus }
  44904. ]);
  44905. }
  44906. if (element && this._observer) {
  44907. this.camera.getScene().onPointerObservable.remove(this._observer);
  44908. this._observer = null;
  44909. if (this._onContextMenu) {
  44910. element.removeEventListener("contextmenu", this._onContextMenu);
  44911. }
  44912. if (this._onMouseMove) {
  44913. element.removeEventListener("mousemove", this._onMouseMove);
  44914. }
  44915. if (this._onGestureStart) {
  44916. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44917. }
  44918. if (this._onGesture) {
  44919. element.removeEventListener("MSGestureChange", this._onGesture);
  44920. }
  44921. this._isPanClick = false;
  44922. this.pinchInwards = true;
  44923. this._onMouseMove = null;
  44924. this._onGestureStart = null;
  44925. this._onGesture = null;
  44926. this._MSGestureHandler = null;
  44927. this._onLostFocus = null;
  44928. this._onContextMenu = null;
  44929. }
  44930. };
  44931. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44932. return "ArcRotateCameraPointersInput";
  44933. };
  44934. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44935. return "pointers";
  44936. };
  44937. __decorate([
  44938. BABYLON.serialize()
  44939. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44940. __decorate([
  44941. BABYLON.serialize()
  44942. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44943. __decorate([
  44944. BABYLON.serialize()
  44945. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44946. __decorate([
  44947. BABYLON.serialize()
  44948. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44949. __decorate([
  44950. BABYLON.serialize()
  44951. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44952. __decorate([
  44953. BABYLON.serialize()
  44954. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44955. __decorate([
  44956. BABYLON.serialize()
  44957. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44958. __decorate([
  44959. BABYLON.serialize()
  44960. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44961. return ArcRotateCameraPointersInput;
  44962. }());
  44963. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44964. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44965. })(BABYLON || (BABYLON = {}));
  44966. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44967. "use strict";
  44968. var BABYLON;
  44969. (function (BABYLON) {
  44970. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44971. __extends(ArcRotateCameraInputsManager, _super);
  44972. function ArcRotateCameraInputsManager(camera) {
  44973. return _super.call(this, camera) || this;
  44974. }
  44975. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44976. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44977. return this;
  44978. };
  44979. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44980. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44981. return this;
  44982. };
  44983. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44984. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44985. return this;
  44986. };
  44987. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44988. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44989. return this;
  44990. };
  44991. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44992. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44993. return this;
  44994. };
  44995. return ArcRotateCameraInputsManager;
  44996. }(BABYLON.CameraInputsManager));
  44997. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44998. })(BABYLON || (BABYLON = {}));
  44999. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45000. "use strict";
  45001. var BABYLON;
  45002. (function (BABYLON) {
  45003. var ArcRotateCamera = /** @class */ (function (_super) {
  45004. __extends(ArcRotateCamera, _super);
  45005. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45006. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45007. _this.inertialAlphaOffset = 0;
  45008. _this.inertialBetaOffset = 0;
  45009. _this.inertialRadiusOffset = 0;
  45010. _this.lowerAlphaLimit = null;
  45011. _this.upperAlphaLimit = null;
  45012. _this.lowerBetaLimit = 0.01;
  45013. _this.upperBetaLimit = Math.PI;
  45014. _this.lowerRadiusLimit = null;
  45015. _this.upperRadiusLimit = null;
  45016. _this.inertialPanningX = 0;
  45017. _this.inertialPanningY = 0;
  45018. _this.pinchToPanMaxDistance = 20;
  45019. _this.panningDistanceLimit = null;
  45020. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45021. _this.panningInertia = 0.9;
  45022. //-- end properties for backward compatibility for inputs
  45023. _this.zoomOnFactor = 1;
  45024. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45025. _this.allowUpsideDown = true;
  45026. _this._viewMatrix = new BABYLON.Matrix();
  45027. // Panning
  45028. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45029. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45030. _this.checkCollisions = false;
  45031. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45032. _this._previousPosition = BABYLON.Vector3.Zero();
  45033. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45034. _this._newPosition = BABYLON.Vector3.Zero();
  45035. _this._computationVector = BABYLON.Vector3.Zero();
  45036. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45037. if (collidedMesh === void 0) { collidedMesh = null; }
  45038. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45039. newPosition.multiplyInPlace(_this._collider._radius);
  45040. }
  45041. if (!collidedMesh) {
  45042. _this._previousPosition.copyFrom(_this.position);
  45043. }
  45044. else {
  45045. _this.setPosition(newPosition);
  45046. if (_this.onCollide) {
  45047. _this.onCollide(collidedMesh);
  45048. }
  45049. }
  45050. // Recompute because of constraints
  45051. var cosa = Math.cos(_this.alpha);
  45052. var sina = Math.sin(_this.alpha);
  45053. var cosb = Math.cos(_this.beta);
  45054. var sinb = Math.sin(_this.beta);
  45055. if (sinb === 0) {
  45056. sinb = 0.0001;
  45057. }
  45058. var target = _this._getTargetPosition();
  45059. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45060. target.addToRef(_this._computationVector, _this._newPosition);
  45061. _this.position.copyFrom(_this._newPosition);
  45062. var up = _this.upVector;
  45063. if (_this.allowUpsideDown && _this.beta < 0) {
  45064. up = up.clone();
  45065. up = up.negate();
  45066. }
  45067. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45068. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45069. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45070. _this._collisionTriggered = false;
  45071. };
  45072. _this._target = BABYLON.Vector3.Zero();
  45073. if (target) {
  45074. _this.setTarget(target);
  45075. }
  45076. _this.alpha = alpha;
  45077. _this.beta = beta;
  45078. _this.radius = radius;
  45079. _this.getViewMatrix();
  45080. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45081. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45082. return _this;
  45083. }
  45084. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45085. get: function () {
  45086. return this._target;
  45087. },
  45088. set: function (value) {
  45089. this.setTarget(value);
  45090. },
  45091. enumerable: true,
  45092. configurable: true
  45093. });
  45094. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45095. //-- begin properties for backward compatibility for inputs
  45096. get: function () {
  45097. var pointers = this.inputs.attached["pointers"];
  45098. if (pointers)
  45099. return pointers.angularSensibilityX;
  45100. return 0;
  45101. },
  45102. set: function (value) {
  45103. var pointers = this.inputs.attached["pointers"];
  45104. if (pointers) {
  45105. pointers.angularSensibilityX = value;
  45106. }
  45107. },
  45108. enumerable: true,
  45109. configurable: true
  45110. });
  45111. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45112. get: function () {
  45113. var pointers = this.inputs.attached["pointers"];
  45114. if (pointers)
  45115. return pointers.angularSensibilityY;
  45116. return 0;
  45117. },
  45118. set: function (value) {
  45119. var pointers = this.inputs.attached["pointers"];
  45120. if (pointers) {
  45121. pointers.angularSensibilityY = value;
  45122. }
  45123. },
  45124. enumerable: true,
  45125. configurable: true
  45126. });
  45127. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45128. get: function () {
  45129. var pointers = this.inputs.attached["pointers"];
  45130. if (pointers)
  45131. return pointers.pinchPrecision;
  45132. return 0;
  45133. },
  45134. set: function (value) {
  45135. var pointers = this.inputs.attached["pointers"];
  45136. if (pointers) {
  45137. pointers.pinchPrecision = value;
  45138. }
  45139. },
  45140. enumerable: true,
  45141. configurable: true
  45142. });
  45143. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45144. get: function () {
  45145. var pointers = this.inputs.attached["pointers"];
  45146. if (pointers)
  45147. return pointers.pinchDeltaPercentage;
  45148. return 0;
  45149. },
  45150. set: function (value) {
  45151. var pointers = this.inputs.attached["pointers"];
  45152. if (pointers) {
  45153. pointers.pinchDeltaPercentage = value;
  45154. }
  45155. },
  45156. enumerable: true,
  45157. configurable: true
  45158. });
  45159. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45160. get: function () {
  45161. var pointers = this.inputs.attached["pointers"];
  45162. if (pointers)
  45163. return pointers.panningSensibility;
  45164. return 0;
  45165. },
  45166. set: function (value) {
  45167. var pointers = this.inputs.attached["pointers"];
  45168. if (pointers) {
  45169. pointers.panningSensibility = value;
  45170. }
  45171. },
  45172. enumerable: true,
  45173. configurable: true
  45174. });
  45175. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45176. get: function () {
  45177. var keyboard = this.inputs.attached["keyboard"];
  45178. if (keyboard)
  45179. return keyboard.keysUp;
  45180. return [];
  45181. },
  45182. set: function (value) {
  45183. var keyboard = this.inputs.attached["keyboard"];
  45184. if (keyboard)
  45185. keyboard.keysUp = value;
  45186. },
  45187. enumerable: true,
  45188. configurable: true
  45189. });
  45190. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45191. get: function () {
  45192. var keyboard = this.inputs.attached["keyboard"];
  45193. if (keyboard)
  45194. return keyboard.keysDown;
  45195. return [];
  45196. },
  45197. set: function (value) {
  45198. var keyboard = this.inputs.attached["keyboard"];
  45199. if (keyboard)
  45200. keyboard.keysDown = value;
  45201. },
  45202. enumerable: true,
  45203. configurable: true
  45204. });
  45205. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45206. get: function () {
  45207. var keyboard = this.inputs.attached["keyboard"];
  45208. if (keyboard)
  45209. return keyboard.keysLeft;
  45210. return [];
  45211. },
  45212. set: function (value) {
  45213. var keyboard = this.inputs.attached["keyboard"];
  45214. if (keyboard)
  45215. keyboard.keysLeft = value;
  45216. },
  45217. enumerable: true,
  45218. configurable: true
  45219. });
  45220. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45221. get: function () {
  45222. var keyboard = this.inputs.attached["keyboard"];
  45223. if (keyboard)
  45224. return keyboard.keysRight;
  45225. return [];
  45226. },
  45227. set: function (value) {
  45228. var keyboard = this.inputs.attached["keyboard"];
  45229. if (keyboard)
  45230. keyboard.keysRight = value;
  45231. },
  45232. enumerable: true,
  45233. configurable: true
  45234. });
  45235. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45236. get: function () {
  45237. var mousewheel = this.inputs.attached["mousewheel"];
  45238. if (mousewheel)
  45239. return mousewheel.wheelPrecision;
  45240. return 0;
  45241. },
  45242. set: function (value) {
  45243. var mousewheel = this.inputs.attached["mousewheel"];
  45244. if (mousewheel)
  45245. mousewheel.wheelPrecision = value;
  45246. },
  45247. enumerable: true,
  45248. configurable: true
  45249. });
  45250. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45251. get: function () {
  45252. var mousewheel = this.inputs.attached["mousewheel"];
  45253. if (mousewheel)
  45254. return mousewheel.wheelDeltaPercentage;
  45255. return 0;
  45256. },
  45257. set: function (value) {
  45258. var mousewheel = this.inputs.attached["mousewheel"];
  45259. if (mousewheel)
  45260. mousewheel.wheelDeltaPercentage = value;
  45261. },
  45262. enumerable: true,
  45263. configurable: true
  45264. });
  45265. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45266. get: function () {
  45267. return this._bouncingBehavior;
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45273. get: function () {
  45274. return this._bouncingBehavior != null;
  45275. },
  45276. set: function (value) {
  45277. if (value === this.useBouncingBehavior) {
  45278. return;
  45279. }
  45280. if (value) {
  45281. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45282. this.addBehavior(this._bouncingBehavior);
  45283. }
  45284. else if (this._bouncingBehavior) {
  45285. this.removeBehavior(this._bouncingBehavior);
  45286. this._bouncingBehavior = null;
  45287. }
  45288. },
  45289. enumerable: true,
  45290. configurable: true
  45291. });
  45292. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45293. get: function () {
  45294. return this._framingBehavior;
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45300. get: function () {
  45301. return this._framingBehavior != null;
  45302. },
  45303. set: function (value) {
  45304. if (value === this.useFramingBehavior) {
  45305. return;
  45306. }
  45307. if (value) {
  45308. this._framingBehavior = new BABYLON.FramingBehavior();
  45309. this.addBehavior(this._framingBehavior);
  45310. }
  45311. else if (this._framingBehavior) {
  45312. this.removeBehavior(this._framingBehavior);
  45313. this._framingBehavior = null;
  45314. }
  45315. },
  45316. enumerable: true,
  45317. configurable: true
  45318. });
  45319. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45320. get: function () {
  45321. return this._autoRotationBehavior;
  45322. },
  45323. enumerable: true,
  45324. configurable: true
  45325. });
  45326. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45327. get: function () {
  45328. return this._autoRotationBehavior != null;
  45329. },
  45330. set: function (value) {
  45331. if (value === this.useAutoRotationBehavior) {
  45332. return;
  45333. }
  45334. if (value) {
  45335. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45336. this.addBehavior(this._autoRotationBehavior);
  45337. }
  45338. else if (this._autoRotationBehavior) {
  45339. this.removeBehavior(this._autoRotationBehavior);
  45340. this._autoRotationBehavior = null;
  45341. }
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. // Cache
  45347. ArcRotateCamera.prototype._initCache = function () {
  45348. _super.prototype._initCache.call(this);
  45349. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45350. this._cache.alpha = undefined;
  45351. this._cache.beta = undefined;
  45352. this._cache.radius = undefined;
  45353. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45354. };
  45355. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45356. if (!ignoreParentClass) {
  45357. _super.prototype._updateCache.call(this);
  45358. }
  45359. this._cache._target.copyFrom(this._getTargetPosition());
  45360. this._cache.alpha = this.alpha;
  45361. this._cache.beta = this.beta;
  45362. this._cache.radius = this.radius;
  45363. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45364. };
  45365. ArcRotateCamera.prototype._getTargetPosition = function () {
  45366. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45367. var pos = this._targetHost.getAbsolutePosition();
  45368. if (this._targetBoundingCenter) {
  45369. pos.addToRef(this._targetBoundingCenter, this._target);
  45370. }
  45371. else {
  45372. this._target.copyFrom(pos);
  45373. }
  45374. }
  45375. var lockedTargetPosition = this._getLockedTargetPosition();
  45376. if (lockedTargetPosition) {
  45377. return lockedTargetPosition;
  45378. }
  45379. return this._target;
  45380. };
  45381. ArcRotateCamera.prototype.storeState = function () {
  45382. this._storedAlpha = this.alpha;
  45383. this._storedBeta = this.beta;
  45384. this._storedRadius = this.radius;
  45385. this._storedTarget = this._getTargetPosition().clone();
  45386. return _super.prototype.storeState.call(this);
  45387. };
  45388. /**
  45389. * Restored camera state. You must call storeState() first
  45390. */
  45391. ArcRotateCamera.prototype._restoreStateValues = function () {
  45392. if (!_super.prototype._restoreStateValues.call(this)) {
  45393. return false;
  45394. }
  45395. this.alpha = this._storedAlpha;
  45396. this.beta = this._storedBeta;
  45397. this.radius = this._storedRadius;
  45398. this.setTarget(this._storedTarget.clone());
  45399. this.inertialAlphaOffset = 0;
  45400. this.inertialBetaOffset = 0;
  45401. this.inertialRadiusOffset = 0;
  45402. this.inertialPanningX = 0;
  45403. this.inertialPanningY = 0;
  45404. return true;
  45405. };
  45406. // Synchronized
  45407. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45408. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45409. return false;
  45410. return this._cache._target.equals(this._getTargetPosition())
  45411. && this._cache.alpha === this.alpha
  45412. && this._cache.beta === this.beta
  45413. && this._cache.radius === this.radius
  45414. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45415. };
  45416. // Methods
  45417. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45418. var _this = this;
  45419. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45420. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45421. this._useCtrlForPanning = useCtrlForPanning;
  45422. this._panningMouseButton = panningMouseButton;
  45423. this.inputs.attachElement(element, noPreventDefault);
  45424. this._reset = function () {
  45425. _this.inertialAlphaOffset = 0;
  45426. _this.inertialBetaOffset = 0;
  45427. _this.inertialRadiusOffset = 0;
  45428. _this.inertialPanningX = 0;
  45429. _this.inertialPanningY = 0;
  45430. };
  45431. };
  45432. ArcRotateCamera.prototype.detachControl = function (element) {
  45433. this.inputs.detachElement(element);
  45434. if (this._reset) {
  45435. this._reset();
  45436. }
  45437. };
  45438. ArcRotateCamera.prototype._checkInputs = function () {
  45439. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45440. if (this._collisionTriggered) {
  45441. return;
  45442. }
  45443. this.inputs.checkInputs();
  45444. // Inertia
  45445. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45446. if (this.getScene().useRightHandedSystem) {
  45447. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45448. }
  45449. else {
  45450. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45451. }
  45452. this.beta += this.inertialBetaOffset;
  45453. this.radius -= this.inertialRadiusOffset;
  45454. this.inertialAlphaOffset *= this.inertia;
  45455. this.inertialBetaOffset *= this.inertia;
  45456. this.inertialRadiusOffset *= this.inertia;
  45457. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45458. this.inertialAlphaOffset = 0;
  45459. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45460. this.inertialBetaOffset = 0;
  45461. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45462. this.inertialRadiusOffset = 0;
  45463. }
  45464. // Panning inertia
  45465. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45466. if (!this._localDirection) {
  45467. this._localDirection = BABYLON.Vector3.Zero();
  45468. this._transformedDirection = BABYLON.Vector3.Zero();
  45469. }
  45470. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45471. this._localDirection.multiplyInPlace(this.panningAxis);
  45472. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45473. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45474. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45475. if (!this.panningAxis.y) {
  45476. this._transformedDirection.y = 0;
  45477. }
  45478. if (!this._targetHost) {
  45479. if (this.panningDistanceLimit) {
  45480. this._transformedDirection.addInPlace(this._target);
  45481. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45482. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45483. this._target.copyFrom(this._transformedDirection);
  45484. }
  45485. }
  45486. else {
  45487. this._target.addInPlace(this._transformedDirection);
  45488. }
  45489. }
  45490. this.inertialPanningX *= this.panningInertia;
  45491. this.inertialPanningY *= this.panningInertia;
  45492. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45493. this.inertialPanningX = 0;
  45494. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45495. this.inertialPanningY = 0;
  45496. }
  45497. // Limits
  45498. this._checkLimits();
  45499. _super.prototype._checkInputs.call(this);
  45500. };
  45501. ArcRotateCamera.prototype._checkLimits = function () {
  45502. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45503. if (this.allowUpsideDown && this.beta > Math.PI) {
  45504. this.beta = this.beta - (2 * Math.PI);
  45505. }
  45506. }
  45507. else {
  45508. if (this.beta < this.lowerBetaLimit) {
  45509. this.beta = this.lowerBetaLimit;
  45510. }
  45511. }
  45512. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45513. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45514. this.beta = this.beta + (2 * Math.PI);
  45515. }
  45516. }
  45517. else {
  45518. if (this.beta > this.upperBetaLimit) {
  45519. this.beta = this.upperBetaLimit;
  45520. }
  45521. }
  45522. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45523. this.alpha = this.lowerAlphaLimit;
  45524. }
  45525. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45526. this.alpha = this.upperAlphaLimit;
  45527. }
  45528. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45529. this.radius = this.lowerRadiusLimit;
  45530. }
  45531. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45532. this.radius = this.upperRadiusLimit;
  45533. }
  45534. };
  45535. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45536. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45537. this.radius = this._computationVector.length();
  45538. if (this.radius === 0) {
  45539. this.radius = 0.0001; // Just to avoid division by zero
  45540. }
  45541. // Alpha
  45542. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45543. if (this._computationVector.z < 0) {
  45544. this.alpha = 2 * Math.PI - this.alpha;
  45545. }
  45546. // Beta
  45547. this.beta = Math.acos(this._computationVector.y / this.radius);
  45548. this._checkLimits();
  45549. };
  45550. ArcRotateCamera.prototype.setPosition = function (position) {
  45551. if (this.position.equals(position)) {
  45552. return;
  45553. }
  45554. this.position.copyFrom(position);
  45555. this.rebuildAnglesAndRadius();
  45556. };
  45557. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45558. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45559. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45560. if (target.getBoundingInfo) {
  45561. if (toBoundingCenter) {
  45562. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45563. }
  45564. else {
  45565. this._targetBoundingCenter = null;
  45566. }
  45567. this._targetHost = target;
  45568. this._target = this._getTargetPosition();
  45569. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45570. }
  45571. else {
  45572. var newTarget = target;
  45573. var currentTarget = this._getTargetPosition();
  45574. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45575. return;
  45576. }
  45577. this._targetHost = null;
  45578. this._target = newTarget;
  45579. this._targetBoundingCenter = null;
  45580. this.onMeshTargetChangedObservable.notifyObservers(null);
  45581. }
  45582. this.rebuildAnglesAndRadius();
  45583. };
  45584. ArcRotateCamera.prototype._getViewMatrix = function () {
  45585. // Compute
  45586. var cosa = Math.cos(this.alpha);
  45587. var sina = Math.sin(this.alpha);
  45588. var cosb = Math.cos(this.beta);
  45589. var sinb = Math.sin(this.beta);
  45590. if (sinb === 0) {
  45591. sinb = 0.0001;
  45592. }
  45593. var target = this._getTargetPosition();
  45594. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45595. target.addToRef(this._computationVector, this._newPosition);
  45596. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45597. if (!this._collider) {
  45598. this._collider = new BABYLON.Collider();
  45599. }
  45600. this._collider._radius = this.collisionRadius;
  45601. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45602. this._collisionTriggered = true;
  45603. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45604. }
  45605. else {
  45606. this.position.copyFrom(this._newPosition);
  45607. var up = this.upVector;
  45608. if (this.allowUpsideDown && sinb < 0) {
  45609. up = up.clone();
  45610. up = up.negate();
  45611. }
  45612. if (this.getScene().useRightHandedSystem) {
  45613. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45614. }
  45615. else {
  45616. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45617. }
  45618. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45619. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45620. }
  45621. this._currentTarget = target;
  45622. return this._viewMatrix;
  45623. };
  45624. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45625. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45626. meshes = meshes || this.getScene().meshes;
  45627. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45628. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45629. this.radius = distance * this.zoomOnFactor;
  45630. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45631. };
  45632. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45633. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45634. var meshesOrMinMaxVector;
  45635. var distance;
  45636. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45637. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45638. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45639. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45640. }
  45641. else {
  45642. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45643. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45644. distance = minMaxVectorAndDistance.distance;
  45645. }
  45646. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45647. if (!doNotUpdateMaxZ) {
  45648. this.maxZ = distance * 2;
  45649. }
  45650. };
  45651. /**
  45652. * @override
  45653. * Override Camera.createRigCamera
  45654. */
  45655. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45656. var alphaShift = 0;
  45657. switch (this.cameraRigMode) {
  45658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45661. case BABYLON.Camera.RIG_MODE_VR:
  45662. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45663. break;
  45664. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45665. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45666. break;
  45667. }
  45668. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45669. rigCam._cameraRigParams = {};
  45670. return rigCam;
  45671. };
  45672. /**
  45673. * @override
  45674. * Override Camera._updateRigCameras
  45675. */
  45676. ArcRotateCamera.prototype._updateRigCameras = function () {
  45677. var camLeft = this._rigCameras[0];
  45678. var camRight = this._rigCameras[1];
  45679. camLeft.beta = camRight.beta = this.beta;
  45680. camLeft.radius = camRight.radius = this.radius;
  45681. switch (this.cameraRigMode) {
  45682. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45683. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45684. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45685. case BABYLON.Camera.RIG_MODE_VR:
  45686. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45687. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45688. break;
  45689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45690. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45691. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45692. break;
  45693. }
  45694. _super.prototype._updateRigCameras.call(this);
  45695. };
  45696. ArcRotateCamera.prototype.dispose = function () {
  45697. this.inputs.clear();
  45698. _super.prototype.dispose.call(this);
  45699. };
  45700. ArcRotateCamera.prototype.getClassName = function () {
  45701. return "ArcRotateCamera";
  45702. };
  45703. __decorate([
  45704. BABYLON.serialize()
  45705. ], ArcRotateCamera.prototype, "alpha", void 0);
  45706. __decorate([
  45707. BABYLON.serialize()
  45708. ], ArcRotateCamera.prototype, "beta", void 0);
  45709. __decorate([
  45710. BABYLON.serialize()
  45711. ], ArcRotateCamera.prototype, "radius", void 0);
  45712. __decorate([
  45713. BABYLON.serializeAsVector3("target")
  45714. ], ArcRotateCamera.prototype, "_target", void 0);
  45715. __decorate([
  45716. BABYLON.serialize()
  45717. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45718. __decorate([
  45719. BABYLON.serialize()
  45720. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45721. __decorate([
  45722. BABYLON.serialize()
  45723. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45724. __decorate([
  45725. BABYLON.serialize()
  45726. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45727. __decorate([
  45728. BABYLON.serialize()
  45729. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45730. __decorate([
  45731. BABYLON.serialize()
  45732. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45733. __decorate([
  45734. BABYLON.serialize()
  45735. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45736. __decorate([
  45737. BABYLON.serialize()
  45738. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45739. __decorate([
  45740. BABYLON.serialize()
  45741. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45742. __decorate([
  45743. BABYLON.serialize()
  45744. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45745. __decorate([
  45746. BABYLON.serialize()
  45747. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45748. __decorate([
  45749. BABYLON.serialize()
  45750. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45751. __decorate([
  45752. BABYLON.serialize()
  45753. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45754. __decorate([
  45755. BABYLON.serializeAsVector3()
  45756. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45757. __decorate([
  45758. BABYLON.serialize()
  45759. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45760. __decorate([
  45761. BABYLON.serialize()
  45762. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45763. __decorate([
  45764. BABYLON.serialize()
  45765. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45766. return ArcRotateCamera;
  45767. }(BABYLON.TargetCamera));
  45768. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45769. })(BABYLON || (BABYLON = {}));
  45770. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45771. "use strict";
  45772. var BABYLON;
  45773. (function (BABYLON) {
  45774. /**
  45775. * The HemisphericLight simulates the ambient environment light,
  45776. * so the passed direction is the light reflection direction, not the incoming direction.
  45777. */
  45778. var HemisphericLight = /** @class */ (function (_super) {
  45779. __extends(HemisphericLight, _super);
  45780. /**
  45781. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45782. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45783. * The HemisphericLight can't cast shadows.
  45784. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45785. * @param name The friendly name of the light
  45786. * @param direction The direction of the light reflection
  45787. * @param scene The scene the light belongs to
  45788. */
  45789. function HemisphericLight(name, direction, scene) {
  45790. var _this = _super.call(this, name, scene) || this;
  45791. /**
  45792. * The groundColor is the light in the opposite direction to the one specified during creation.
  45793. * 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.
  45794. */
  45795. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45796. _this.direction = direction || BABYLON.Vector3.Up();
  45797. return _this;
  45798. }
  45799. HemisphericLight.prototype._buildUniformLayout = function () {
  45800. this._uniformBuffer.addUniform("vLightData", 4);
  45801. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45802. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45803. this._uniformBuffer.addUniform("vLightGround", 3);
  45804. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45805. this._uniformBuffer.addUniform("depthValues", 2);
  45806. this._uniformBuffer.create();
  45807. };
  45808. /**
  45809. * Returns the string "HemisphericLight".
  45810. * @return The class name
  45811. */
  45812. HemisphericLight.prototype.getClassName = function () {
  45813. return "HemisphericLight";
  45814. };
  45815. /**
  45816. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45817. * Returns the updated direction.
  45818. * @param target The target the direction should point to
  45819. * @return The computed direction
  45820. */
  45821. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45822. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45823. return this.direction;
  45824. };
  45825. /**
  45826. * Returns the shadow generator associated to the light.
  45827. * @returns Always null for hemispheric lights because it does not support shadows.
  45828. */
  45829. HemisphericLight.prototype.getShadowGenerator = function () {
  45830. return null;
  45831. };
  45832. /**
  45833. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45834. * @param effect The effect to update
  45835. * @param lightIndex The index of the light in the effect to update
  45836. * @returns The hemispheric light
  45837. */
  45838. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45839. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45840. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45841. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45842. return this;
  45843. };
  45844. /**
  45845. * @ignore internal use only.
  45846. */
  45847. HemisphericLight.prototype._getWorldMatrix = function () {
  45848. if (!this._worldMatrix) {
  45849. this._worldMatrix = BABYLON.Matrix.Identity();
  45850. }
  45851. return this._worldMatrix;
  45852. };
  45853. /**
  45854. * Returns the integer 3.
  45855. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45856. */
  45857. HemisphericLight.prototype.getTypeID = function () {
  45858. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45859. };
  45860. __decorate([
  45861. BABYLON.serializeAsColor3()
  45862. ], HemisphericLight.prototype, "groundColor", void 0);
  45863. __decorate([
  45864. BABYLON.serializeAsVector3()
  45865. ], HemisphericLight.prototype, "direction", void 0);
  45866. return HemisphericLight;
  45867. }(BABYLON.Light));
  45868. BABYLON.HemisphericLight = HemisphericLight;
  45869. })(BABYLON || (BABYLON = {}));
  45870. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45871. "use strict";
  45872. var BABYLON;
  45873. (function (BABYLON) {
  45874. /**
  45875. * Base implementation IShadowLight
  45876. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45877. */
  45878. var ShadowLight = /** @class */ (function (_super) {
  45879. __extends(ShadowLight, _super);
  45880. function ShadowLight() {
  45881. var _this = _super !== null && _super.apply(this, arguments) || this;
  45882. _this._needProjectionMatrixCompute = true;
  45883. return _this;
  45884. }
  45885. ShadowLight.prototype._setPosition = function (value) {
  45886. this._position = value;
  45887. };
  45888. Object.defineProperty(ShadowLight.prototype, "position", {
  45889. /**
  45890. * Sets the position the shadow will be casted from. Also use as the light position for both
  45891. * point and spot lights.
  45892. */
  45893. get: function () {
  45894. return this._position;
  45895. },
  45896. /**
  45897. * Sets the position the shadow will be casted from. Also use as the light position for both
  45898. * point and spot lights.
  45899. */
  45900. set: function (value) {
  45901. this._setPosition(value);
  45902. },
  45903. enumerable: true,
  45904. configurable: true
  45905. });
  45906. ShadowLight.prototype._setDirection = function (value) {
  45907. this._direction = value;
  45908. };
  45909. Object.defineProperty(ShadowLight.prototype, "direction", {
  45910. /**
  45911. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45912. * Also use as the light direction on spot and directional lights.
  45913. */
  45914. get: function () {
  45915. return this._direction;
  45916. },
  45917. /**
  45918. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45919. * Also use as the light direction on spot and directional lights.
  45920. */
  45921. set: function (value) {
  45922. this._setDirection(value);
  45923. },
  45924. enumerable: true,
  45925. configurable: true
  45926. });
  45927. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45928. /**
  45929. * Gets the shadow projection clipping minimum z value.
  45930. */
  45931. get: function () {
  45932. return this._shadowMinZ;
  45933. },
  45934. /**
  45935. * Sets the shadow projection clipping minimum z value.
  45936. */
  45937. set: function (value) {
  45938. this._shadowMinZ = value;
  45939. this.forceProjectionMatrixCompute();
  45940. },
  45941. enumerable: true,
  45942. configurable: true
  45943. });
  45944. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45945. /**
  45946. * Sets the shadow projection clipping maximum z value.
  45947. */
  45948. get: function () {
  45949. return this._shadowMaxZ;
  45950. },
  45951. /**
  45952. * Gets the shadow projection clipping maximum z value.
  45953. */
  45954. set: function (value) {
  45955. this._shadowMaxZ = value;
  45956. this.forceProjectionMatrixCompute();
  45957. },
  45958. enumerable: true,
  45959. configurable: true
  45960. });
  45961. /**
  45962. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45963. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45964. */
  45965. ShadowLight.prototype.computeTransformedInformation = function () {
  45966. if (this.parent && this.parent.getWorldMatrix) {
  45967. if (!this.transformedPosition) {
  45968. this.transformedPosition = BABYLON.Vector3.Zero();
  45969. }
  45970. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45971. // In case the direction is present.
  45972. if (this.direction) {
  45973. if (!this.transformedDirection) {
  45974. this.transformedDirection = BABYLON.Vector3.Zero();
  45975. }
  45976. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45977. }
  45978. return true;
  45979. }
  45980. return false;
  45981. };
  45982. /**
  45983. * Return the depth scale used for the shadow map.
  45984. * @returns the depth scale.
  45985. */
  45986. ShadowLight.prototype.getDepthScale = function () {
  45987. return 50.0;
  45988. };
  45989. /**
  45990. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45991. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45992. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45993. */
  45994. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45995. return this.transformedDirection ? this.transformedDirection : this.direction;
  45996. };
  45997. /**
  45998. * Returns the ShadowLight absolute position in the World.
  45999. * @returns the position vector in world space
  46000. */
  46001. ShadowLight.prototype.getAbsolutePosition = function () {
  46002. return this.transformedPosition ? this.transformedPosition : this.position;
  46003. };
  46004. /**
  46005. * Sets the ShadowLight direction toward the passed target.
  46006. * @param target The point tot target in local space
  46007. * @returns the updated ShadowLight direction
  46008. */
  46009. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46010. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46011. return this.direction;
  46012. };
  46013. /**
  46014. * Returns the light rotation in euler definition.
  46015. * @returns the x y z rotation in local space.
  46016. */
  46017. ShadowLight.prototype.getRotation = function () {
  46018. this.direction.normalize();
  46019. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46020. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46021. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46022. };
  46023. /**
  46024. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46025. * @returns true if a cube texture needs to be use
  46026. */
  46027. ShadowLight.prototype.needCube = function () {
  46028. return false;
  46029. };
  46030. /**
  46031. * Detects if the projection matrix requires to be recomputed this frame.
  46032. * @returns true if it requires to be recomputed otherwise, false.
  46033. */
  46034. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46035. return this._needProjectionMatrixCompute;
  46036. };
  46037. /**
  46038. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46039. */
  46040. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46041. this._needProjectionMatrixCompute = true;
  46042. };
  46043. /**
  46044. * Get the world matrix of the sahdow lights.
  46045. * @ignore Internal Use Only
  46046. */
  46047. ShadowLight.prototype._getWorldMatrix = function () {
  46048. if (!this._worldMatrix) {
  46049. this._worldMatrix = BABYLON.Matrix.Identity();
  46050. }
  46051. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46052. return this._worldMatrix;
  46053. };
  46054. /**
  46055. * Gets the minZ used for shadow according to both the scene and the light.
  46056. * @param activeCamera The camera we are returning the min for
  46057. * @returns the depth min z
  46058. */
  46059. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46060. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46061. };
  46062. /**
  46063. * Gets the maxZ used for shadow according to both the scene and the light.
  46064. * @param activeCamera The camera we are returning the max for
  46065. * @returns the depth max z
  46066. */
  46067. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46068. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46069. };
  46070. /**
  46071. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46072. * @param matrix The materix to updated with the projection information
  46073. * @param viewMatrix The transform matrix of the light
  46074. * @param renderList The list of mesh to render in the map
  46075. * @returns The current light
  46076. */
  46077. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46078. if (this.customProjectionMatrixBuilder) {
  46079. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46080. }
  46081. else {
  46082. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46083. }
  46084. return this;
  46085. };
  46086. __decorate([
  46087. BABYLON.serializeAsVector3()
  46088. ], ShadowLight.prototype, "position", null);
  46089. __decorate([
  46090. BABYLON.serializeAsVector3()
  46091. ], ShadowLight.prototype, "direction", null);
  46092. __decorate([
  46093. BABYLON.serialize()
  46094. ], ShadowLight.prototype, "shadowMinZ", null);
  46095. __decorate([
  46096. BABYLON.serialize()
  46097. ], ShadowLight.prototype, "shadowMaxZ", null);
  46098. return ShadowLight;
  46099. }(BABYLON.Light));
  46100. BABYLON.ShadowLight = ShadowLight;
  46101. })(BABYLON || (BABYLON = {}));
  46102. //# sourceMappingURL=babylon.shadowLight.js.map
  46103. "use strict";
  46104. var BABYLON;
  46105. (function (BABYLON) {
  46106. /**
  46107. * A point light is a light defined by an unique point in world space.
  46108. * The light is emitted in every direction from this point.
  46109. * A good example of a point light is a standard light bulb.
  46110. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46111. */
  46112. var PointLight = /** @class */ (function (_super) {
  46113. __extends(PointLight, _super);
  46114. /**
  46115. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46116. * A PointLight emits the light in every direction.
  46117. * It can cast shadows.
  46118. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46119. * ```javascript
  46120. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46121. * ```
  46122. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46123. * @param name The light friendly name
  46124. * @param position The position of the point light in the scene
  46125. * @param scene The scene the lights belongs to
  46126. */
  46127. function PointLight(name, position, scene) {
  46128. var _this = _super.call(this, name, scene) || this;
  46129. _this._shadowAngle = Math.PI / 2;
  46130. _this.position = position;
  46131. return _this;
  46132. }
  46133. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46134. /**
  46135. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46136. * This specifies what angle the shadow will use to be created.
  46137. *
  46138. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46139. */
  46140. get: function () {
  46141. return this._shadowAngle;
  46142. },
  46143. /**
  46144. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46145. * This specifies what angle the shadow will use to be created.
  46146. *
  46147. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46148. */
  46149. set: function (value) {
  46150. this._shadowAngle = value;
  46151. this.forceProjectionMatrixCompute();
  46152. },
  46153. enumerable: true,
  46154. configurable: true
  46155. });
  46156. Object.defineProperty(PointLight.prototype, "direction", {
  46157. /**
  46158. * Gets the direction if it has been set.
  46159. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46160. */
  46161. get: function () {
  46162. return this._direction;
  46163. },
  46164. /**
  46165. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46166. */
  46167. set: function (value) {
  46168. var previousNeedCube = this.needCube();
  46169. this._direction = value;
  46170. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46171. this._shadowGenerator.recreateShadowMap();
  46172. }
  46173. },
  46174. enumerable: true,
  46175. configurable: true
  46176. });
  46177. /**
  46178. * Returns the string "PointLight"
  46179. * @returns the class name
  46180. */
  46181. PointLight.prototype.getClassName = function () {
  46182. return "PointLight";
  46183. };
  46184. /**
  46185. * Returns the integer 0.
  46186. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46187. */
  46188. PointLight.prototype.getTypeID = function () {
  46189. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46190. };
  46191. /**
  46192. * Specifies wether or not the shadowmap should be a cube texture.
  46193. * @returns true if the shadowmap needs to be a cube texture.
  46194. */
  46195. PointLight.prototype.needCube = function () {
  46196. return !this.direction;
  46197. };
  46198. /**
  46199. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46200. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46201. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46202. */
  46203. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46204. if (this.direction) {
  46205. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46206. }
  46207. else {
  46208. switch (faceIndex) {
  46209. case 0:
  46210. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46211. case 1:
  46212. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46213. case 2:
  46214. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46215. case 3:
  46216. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46217. case 4:
  46218. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46219. case 5:
  46220. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46221. }
  46222. }
  46223. return BABYLON.Vector3.Zero();
  46224. };
  46225. /**
  46226. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46227. * - fov = PI / 2
  46228. * - aspect ratio : 1.0
  46229. * - z-near and far equal to the active camera minZ and maxZ.
  46230. * Returns the PointLight.
  46231. */
  46232. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46233. var activeCamera = this.getScene().activeCamera;
  46234. if (!activeCamera) {
  46235. return;
  46236. }
  46237. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46238. };
  46239. PointLight.prototype._buildUniformLayout = function () {
  46240. this._uniformBuffer.addUniform("vLightData", 4);
  46241. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46242. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46243. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46244. this._uniformBuffer.addUniform("depthValues", 2);
  46245. this._uniformBuffer.create();
  46246. };
  46247. /**
  46248. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46249. * @param effect The effect to update
  46250. * @param lightIndex The index of the light in the effect to update
  46251. * @returns The point light
  46252. */
  46253. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46254. if (this.computeTransformedInformation()) {
  46255. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46256. return this;
  46257. }
  46258. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46259. return this;
  46260. };
  46261. __decorate([
  46262. BABYLON.serialize()
  46263. ], PointLight.prototype, "shadowAngle", null);
  46264. return PointLight;
  46265. }(BABYLON.ShadowLight));
  46266. BABYLON.PointLight = PointLight;
  46267. })(BABYLON || (BABYLON = {}));
  46268. //# sourceMappingURL=babylon.pointLight.js.map
  46269. "use strict";
  46270. var BABYLON;
  46271. (function (BABYLON) {
  46272. /**
  46273. * A directional light is defined by a direction (what a surprise!).
  46274. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46275. * 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.
  46276. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46277. */
  46278. var DirectionalLight = /** @class */ (function (_super) {
  46279. __extends(DirectionalLight, _super);
  46280. /**
  46281. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46282. * The directional light is emitted from everywhere in the given direction.
  46283. * It can cast shawdows.
  46284. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46285. * @param name The friendly name of the light
  46286. * @param direction The direction of the light
  46287. * @param scene The scene the light belongs to
  46288. */
  46289. function DirectionalLight(name, direction, scene) {
  46290. var _this = _super.call(this, name, scene) || this;
  46291. _this._shadowFrustumSize = 0;
  46292. _this._shadowOrthoScale = 0.1;
  46293. /**
  46294. * Automatically compute the projection matrix to best fit (including all the casters)
  46295. * on each frame.
  46296. */
  46297. _this.autoUpdateExtends = true;
  46298. // Cache
  46299. _this._orthoLeft = Number.MAX_VALUE;
  46300. _this._orthoRight = Number.MIN_VALUE;
  46301. _this._orthoTop = Number.MIN_VALUE;
  46302. _this._orthoBottom = Number.MAX_VALUE;
  46303. _this.position = direction.scale(-1.0);
  46304. _this.direction = direction;
  46305. return _this;
  46306. }
  46307. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46308. /**
  46309. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46310. */
  46311. get: function () {
  46312. return this._shadowFrustumSize;
  46313. },
  46314. /**
  46315. * Specifies a fix frustum size for the shadow generation.
  46316. */
  46317. set: function (value) {
  46318. this._shadowFrustumSize = value;
  46319. this.forceProjectionMatrixCompute();
  46320. },
  46321. enumerable: true,
  46322. configurable: true
  46323. });
  46324. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46325. /**
  46326. * Gets the shadow projection scale against the optimal computed one.
  46327. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46328. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46329. */
  46330. get: function () {
  46331. return this._shadowOrthoScale;
  46332. },
  46333. /**
  46334. * Sets the shadow projection scale against the optimal computed one.
  46335. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46336. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46337. */
  46338. set: function (value) {
  46339. this._shadowOrthoScale = value;
  46340. this.forceProjectionMatrixCompute();
  46341. },
  46342. enumerable: true,
  46343. configurable: true
  46344. });
  46345. /**
  46346. * Returns the string "DirectionalLight".
  46347. * @return The class name
  46348. */
  46349. DirectionalLight.prototype.getClassName = function () {
  46350. return "DirectionalLight";
  46351. };
  46352. /**
  46353. * Returns the integer 1.
  46354. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46355. */
  46356. DirectionalLight.prototype.getTypeID = function () {
  46357. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46358. };
  46359. /**
  46360. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46361. * Returns the DirectionalLight Shadow projection matrix.
  46362. */
  46363. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46364. if (this.shadowFrustumSize > 0) {
  46365. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46366. }
  46367. else {
  46368. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46369. }
  46370. };
  46371. /**
  46372. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46373. * Returns the DirectionalLight Shadow projection matrix.
  46374. */
  46375. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46376. var activeCamera = this.getScene().activeCamera;
  46377. if (!activeCamera) {
  46378. return;
  46379. }
  46380. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46381. };
  46382. /**
  46383. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46384. * Returns the DirectionalLight Shadow projection matrix.
  46385. */
  46386. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46387. var activeCamera = this.getScene().activeCamera;
  46388. if (!activeCamera) {
  46389. return;
  46390. }
  46391. // Check extends
  46392. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46393. var tempVector3 = BABYLON.Vector3.Zero();
  46394. this._orthoLeft = Number.MAX_VALUE;
  46395. this._orthoRight = Number.MIN_VALUE;
  46396. this._orthoTop = Number.MIN_VALUE;
  46397. this._orthoBottom = Number.MAX_VALUE;
  46398. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46399. var mesh = renderList[meshIndex];
  46400. if (!mesh) {
  46401. continue;
  46402. }
  46403. var boundingInfo = mesh.getBoundingInfo();
  46404. var boundingBox = boundingInfo.boundingBox;
  46405. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46406. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46407. if (tempVector3.x < this._orthoLeft)
  46408. this._orthoLeft = tempVector3.x;
  46409. if (tempVector3.y < this._orthoBottom)
  46410. this._orthoBottom = tempVector3.y;
  46411. if (tempVector3.x > this._orthoRight)
  46412. this._orthoRight = tempVector3.x;
  46413. if (tempVector3.y > this._orthoTop)
  46414. this._orthoTop = tempVector3.y;
  46415. }
  46416. }
  46417. }
  46418. var xOffset = this._orthoRight - this._orthoLeft;
  46419. var yOffset = this._orthoTop - this._orthoBottom;
  46420. 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);
  46421. };
  46422. DirectionalLight.prototype._buildUniformLayout = function () {
  46423. this._uniformBuffer.addUniform("vLightData", 4);
  46424. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46425. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46426. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46427. this._uniformBuffer.addUniform("depthValues", 2);
  46428. this._uniformBuffer.create();
  46429. };
  46430. /**
  46431. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46432. * @param effect The effect to update
  46433. * @param lightIndex The index of the light in the effect to update
  46434. * @returns The directional light
  46435. */
  46436. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46437. if (this.computeTransformedInformation()) {
  46438. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46439. return this;
  46440. }
  46441. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46442. return this;
  46443. };
  46444. /**
  46445. * Gets the minZ used for shadow according to both the scene and the light.
  46446. *
  46447. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46448. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46449. * @param activeCamera The camera we are returning the min for
  46450. * @returns the depth min z
  46451. */
  46452. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46453. return 1;
  46454. };
  46455. /**
  46456. * Gets the maxZ used for shadow according to both the scene and the light.
  46457. *
  46458. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46459. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46460. * @param activeCamera The camera we are returning the max for
  46461. * @returns the depth max z
  46462. */
  46463. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46464. return 1;
  46465. };
  46466. __decorate([
  46467. BABYLON.serialize()
  46468. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46469. __decorate([
  46470. BABYLON.serialize()
  46471. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46472. __decorate([
  46473. BABYLON.serialize()
  46474. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46475. return DirectionalLight;
  46476. }(BABYLON.ShadowLight));
  46477. BABYLON.DirectionalLight = DirectionalLight;
  46478. })(BABYLON || (BABYLON = {}));
  46479. //# sourceMappingURL=babylon.directionalLight.js.map
  46480. "use strict";
  46481. var BABYLON;
  46482. (function (BABYLON) {
  46483. /**
  46484. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46485. * These values define a cone of light starting from the position, emitting toward the direction.
  46486. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46487. * and the exponent defines the speed of the decay of the light with distance (reach).
  46488. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46489. */
  46490. var SpotLight = /** @class */ (function (_super) {
  46491. __extends(SpotLight, _super);
  46492. /**
  46493. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46494. * It can cast shadows.
  46495. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46496. * @param name The light friendly name
  46497. * @param position The position of the spot light in the scene
  46498. * @param direction The direction of the light in the scene
  46499. * @param angle The cone angle of the light in Radians
  46500. * @param exponent The light decay speed with the distance from the emission spot
  46501. * @param scene The scene the lights belongs to
  46502. */
  46503. function SpotLight(name, position, direction, angle, exponent, scene) {
  46504. var _this = _super.call(this, name, scene) || this;
  46505. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46506. _this._projectionTextureLightNear = 1e-6;
  46507. _this._projectionTextureLightFar = 1000.0;
  46508. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46509. _this._projectionTextureViewLightDirty = true;
  46510. _this._projectionTextureProjectionLightDirty = true;
  46511. _this._projectionTextureDirty = true;
  46512. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46513. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46514. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46515. _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);
  46516. _this.position = position;
  46517. _this.direction = direction;
  46518. _this.angle = angle;
  46519. _this.exponent = exponent;
  46520. return _this;
  46521. }
  46522. Object.defineProperty(SpotLight.prototype, "angle", {
  46523. /**
  46524. * Gets the cone angle of the spot light in Radians.
  46525. */
  46526. get: function () {
  46527. return this._angle;
  46528. },
  46529. /**
  46530. * Sets the cone angle of the spot light in Radians.
  46531. */
  46532. set: function (value) {
  46533. this._angle = value;
  46534. this._projectionTextureProjectionLightDirty = true;
  46535. this.forceProjectionMatrixCompute();
  46536. },
  46537. enumerable: true,
  46538. configurable: true
  46539. });
  46540. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46541. /**
  46542. * Allows scaling the angle of the light for shadow generation only.
  46543. */
  46544. get: function () {
  46545. return this._shadowAngleScale;
  46546. },
  46547. /**
  46548. * Allows scaling the angle of the light for shadow generation only.
  46549. */
  46550. set: function (value) {
  46551. this._shadowAngleScale = value;
  46552. this.forceProjectionMatrixCompute();
  46553. },
  46554. enumerable: true,
  46555. configurable: true
  46556. });
  46557. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46558. /**
  46559. * Allows reading the projecton texture
  46560. */
  46561. get: function () {
  46562. return this._projectionTextureMatrix;
  46563. },
  46564. enumerable: true,
  46565. configurable: true
  46566. });
  46567. ;
  46568. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46569. /**
  46570. * Gets the near clip of the Spotlight for texture projection.
  46571. */
  46572. get: function () {
  46573. return this._projectionTextureLightNear;
  46574. },
  46575. /**
  46576. * Sets the near clip of the Spotlight for texture projection.
  46577. */
  46578. set: function (value) {
  46579. this._projectionTextureLightNear = value;
  46580. this._projectionTextureProjectionLightDirty = true;
  46581. },
  46582. enumerable: true,
  46583. configurable: true
  46584. });
  46585. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46586. /**
  46587. * Gets the far clip of the Spotlight for texture projection.
  46588. */
  46589. get: function () {
  46590. return this._projectionTextureLightFar;
  46591. },
  46592. /**
  46593. * Sets the far clip of the Spotlight for texture projection.
  46594. */
  46595. set: function (value) {
  46596. this._projectionTextureLightFar = value;
  46597. this._projectionTextureProjectionLightDirty = true;
  46598. },
  46599. enumerable: true,
  46600. configurable: true
  46601. });
  46602. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46603. /**
  46604. * Gets the Up vector of the Spotlight for texture projection.
  46605. */
  46606. get: function () {
  46607. return this._projectionTextureUpDirection;
  46608. },
  46609. /**
  46610. * Sets the Up vector of the Spotlight for texture projection.
  46611. */
  46612. set: function (value) {
  46613. this._projectionTextureUpDirection = value;
  46614. this._projectionTextureProjectionLightDirty = true;
  46615. },
  46616. enumerable: true,
  46617. configurable: true
  46618. });
  46619. ;
  46620. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46621. /**
  46622. * Gets the projection texture of the light.
  46623. */
  46624. get: function () {
  46625. return this._projectionTexture;
  46626. },
  46627. /**
  46628. * Sets the projection texture of the light.
  46629. */
  46630. set: function (value) {
  46631. this._projectionTexture = value;
  46632. this._projectionTextureDirty = true;
  46633. },
  46634. enumerable: true,
  46635. configurable: true
  46636. });
  46637. /**
  46638. * Returns the string "SpotLight".
  46639. * @returns the class name
  46640. */
  46641. SpotLight.prototype.getClassName = function () {
  46642. return "SpotLight";
  46643. };
  46644. /**
  46645. * Returns the integer 2.
  46646. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46647. */
  46648. SpotLight.prototype.getTypeID = function () {
  46649. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46650. };
  46651. /**
  46652. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46653. */
  46654. SpotLight.prototype._setDirection = function (value) {
  46655. _super.prototype._setDirection.call(this, value);
  46656. this._projectionTextureViewLightDirty = true;
  46657. };
  46658. /**
  46659. * Overrides the position setter to recompute the projection texture view light Matrix.
  46660. */
  46661. SpotLight.prototype._setPosition = function (value) {
  46662. _super.prototype._setPosition.call(this, value);
  46663. this._projectionTextureViewLightDirty = true;
  46664. };
  46665. /**
  46666. * 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.
  46667. * Returns the SpotLight.
  46668. */
  46669. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46670. var activeCamera = this.getScene().activeCamera;
  46671. if (!activeCamera) {
  46672. return;
  46673. }
  46674. this._shadowAngleScale = this._shadowAngleScale || 1;
  46675. var angle = this._shadowAngleScale * this._angle;
  46676. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46677. };
  46678. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46679. this._projectionTextureViewLightDirty = false;
  46680. this._projectionTextureDirty = true;
  46681. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46682. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46683. };
  46684. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46685. this._projectionTextureProjectionLightDirty = false;
  46686. this._projectionTextureDirty = true;
  46687. var light_far = this.projectionTextureLightFar;
  46688. var light_near = this.projectionTextureLightNear;
  46689. var P = light_far / (light_far - light_near);
  46690. var Q = -P * light_near;
  46691. var S = 1.0 / Math.tan(this._angle / 2.0);
  46692. var A = 1.0;
  46693. 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);
  46694. };
  46695. /**
  46696. * Main function for light texture projection matrix computing.
  46697. */
  46698. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46699. this._projectionTextureDirty = false;
  46700. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46701. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46702. };
  46703. SpotLight.prototype._buildUniformLayout = function () {
  46704. this._uniformBuffer.addUniform("vLightData", 4);
  46705. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46706. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46707. this._uniformBuffer.addUniform("vLightDirection", 3);
  46708. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46709. this._uniformBuffer.addUniform("depthValues", 2);
  46710. this._uniformBuffer.create();
  46711. };
  46712. /**
  46713. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46714. * @param effect The effect to update
  46715. * @param lightIndex The index of the light in the effect to update
  46716. * @returns The spot light
  46717. */
  46718. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46719. var normalizeDirection;
  46720. if (this.computeTransformedInformation()) {
  46721. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46722. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46723. }
  46724. else {
  46725. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46726. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46727. }
  46728. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46729. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46730. if (this._projectionTextureViewLightDirty) {
  46731. this._computeProjectionTextureViewLightMatrix();
  46732. }
  46733. if (this._projectionTextureProjectionLightDirty) {
  46734. this._computeProjectionTextureProjectionLightMatrix();
  46735. }
  46736. if (this._projectionTextureDirty) {
  46737. this._computeProjectionTextureMatrix();
  46738. }
  46739. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46740. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46741. }
  46742. return this;
  46743. };
  46744. /**
  46745. * Disposes the light and the associated resources.
  46746. */
  46747. SpotLight.prototype.dispose = function () {
  46748. _super.prototype.dispose.call(this);
  46749. if (this._projectionTexture) {
  46750. this._projectionTexture.dispose();
  46751. }
  46752. };
  46753. __decorate([
  46754. BABYLON.serialize()
  46755. ], SpotLight.prototype, "angle", null);
  46756. __decorate([
  46757. BABYLON.serialize()
  46758. ], SpotLight.prototype, "shadowAngleScale", null);
  46759. __decorate([
  46760. BABYLON.serialize()
  46761. ], SpotLight.prototype, "exponent", void 0);
  46762. __decorate([
  46763. BABYLON.serialize()
  46764. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46765. __decorate([
  46766. BABYLON.serialize()
  46767. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46768. __decorate([
  46769. BABYLON.serialize()
  46770. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46771. __decorate([
  46772. BABYLON.serializeAsTexture("projectedLightTexture")
  46773. ], SpotLight.prototype, "_projectionTexture", void 0);
  46774. return SpotLight;
  46775. }(BABYLON.ShadowLight));
  46776. BABYLON.SpotLight = SpotLight;
  46777. })(BABYLON || (BABYLON = {}));
  46778. //# sourceMappingURL=babylon.spotLight.js.map
  46779. "use strict";
  46780. var BABYLON;
  46781. (function (BABYLON) {
  46782. /**
  46783. * Class used to override all child animations of a given target
  46784. */
  46785. var AnimationPropertiesOverride = /** @class */ (function () {
  46786. function AnimationPropertiesOverride() {
  46787. /**
  46788. * Gets or sets a value indicating if animation blending must be used
  46789. */
  46790. this.enableBlending = false;
  46791. /**
  46792. * Gets or sets the blending speed to use when enableBlending is true
  46793. */
  46794. this.blendingSpeed = 0.01;
  46795. /**
  46796. * Gets or sets the default loop mode to use
  46797. */
  46798. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46799. }
  46800. return AnimationPropertiesOverride;
  46801. }());
  46802. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46803. })(BABYLON || (BABYLON = {}));
  46804. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46805. "use strict";
  46806. var BABYLON;
  46807. (function (BABYLON) {
  46808. var AnimationRange = /** @class */ (function () {
  46809. function AnimationRange(name, from, to) {
  46810. this.name = name;
  46811. this.from = from;
  46812. this.to = to;
  46813. }
  46814. AnimationRange.prototype.clone = function () {
  46815. return new AnimationRange(this.name, this.from, this.to);
  46816. };
  46817. return AnimationRange;
  46818. }());
  46819. BABYLON.AnimationRange = AnimationRange;
  46820. /**
  46821. * Composed of a frame, and an action function
  46822. */
  46823. var AnimationEvent = /** @class */ (function () {
  46824. function AnimationEvent(frame, action, onlyOnce) {
  46825. this.frame = frame;
  46826. this.action = action;
  46827. this.onlyOnce = onlyOnce;
  46828. this.isDone = false;
  46829. }
  46830. return AnimationEvent;
  46831. }());
  46832. BABYLON.AnimationEvent = AnimationEvent;
  46833. var PathCursor = /** @class */ (function () {
  46834. function PathCursor(path) {
  46835. this.path = path;
  46836. this._onchange = new Array();
  46837. this.value = 0;
  46838. this.animations = new Array();
  46839. }
  46840. PathCursor.prototype.getPoint = function () {
  46841. var point = this.path.getPointAtLengthPosition(this.value);
  46842. return new BABYLON.Vector3(point.x, 0, point.y);
  46843. };
  46844. PathCursor.prototype.moveAhead = function (step) {
  46845. if (step === void 0) { step = 0.002; }
  46846. this.move(step);
  46847. return this;
  46848. };
  46849. PathCursor.prototype.moveBack = function (step) {
  46850. if (step === void 0) { step = 0.002; }
  46851. this.move(-step);
  46852. return this;
  46853. };
  46854. PathCursor.prototype.move = function (step) {
  46855. if (Math.abs(step) > 1) {
  46856. throw "step size should be less than 1.";
  46857. }
  46858. this.value += step;
  46859. this.ensureLimits();
  46860. this.raiseOnChange();
  46861. return this;
  46862. };
  46863. PathCursor.prototype.ensureLimits = function () {
  46864. while (this.value > 1) {
  46865. this.value -= 1;
  46866. }
  46867. while (this.value < 0) {
  46868. this.value += 1;
  46869. }
  46870. return this;
  46871. };
  46872. // used by animation engine
  46873. PathCursor.prototype.raiseOnChange = function () {
  46874. var _this = this;
  46875. this._onchange.forEach(function (f) { return f(_this); });
  46876. return this;
  46877. };
  46878. PathCursor.prototype.onchange = function (f) {
  46879. this._onchange.push(f);
  46880. return this;
  46881. };
  46882. return PathCursor;
  46883. }());
  46884. BABYLON.PathCursor = PathCursor;
  46885. var AnimationKeyInterpolation;
  46886. (function (AnimationKeyInterpolation) {
  46887. /**
  46888. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46889. */
  46890. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46891. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46892. var Animation = /** @class */ (function () {
  46893. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46894. this.name = name;
  46895. this.targetProperty = targetProperty;
  46896. this.framePerSecond = framePerSecond;
  46897. this.dataType = dataType;
  46898. this.loopMode = loopMode;
  46899. this.enableBlending = enableBlending;
  46900. this._runtimeAnimations = new Array();
  46901. // The set of event that will be linked to this animation
  46902. this._events = new Array();
  46903. this.blendingSpeed = 0.01;
  46904. this._ranges = {};
  46905. this.targetPropertyPath = targetProperty.split(".");
  46906. this.dataType = dataType;
  46907. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46908. }
  46909. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46910. var dataType = undefined;
  46911. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46912. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46913. }
  46914. else if (from instanceof BABYLON.Quaternion) {
  46915. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46916. }
  46917. else if (from instanceof BABYLON.Vector3) {
  46918. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46919. }
  46920. else if (from instanceof BABYLON.Vector2) {
  46921. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46922. }
  46923. else if (from instanceof BABYLON.Color3) {
  46924. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46925. }
  46926. else if (from instanceof BABYLON.Size) {
  46927. dataType = Animation.ANIMATIONTYPE_SIZE;
  46928. }
  46929. if (dataType == undefined) {
  46930. return null;
  46931. }
  46932. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46933. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46934. animation.setKeys(keys);
  46935. if (easingFunction !== undefined) {
  46936. animation.setEasingFunction(easingFunction);
  46937. }
  46938. return animation;
  46939. };
  46940. /**
  46941. * Sets up an animation.
  46942. * @param property the property to animate
  46943. * @param animationType the animation type to apply
  46944. * @param easingFunction the easing function used in the animation
  46945. * @returns The created animation
  46946. */
  46947. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46948. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46949. animation.setEasingFunction(easingFunction);
  46950. return animation;
  46951. };
  46952. /**
  46953. * Create and start an animation on a node
  46954. * @param {string} name defines the name of the global animation that will be run on all nodes
  46955. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46956. * @param {string} targetProperty defines property to animate
  46957. * @param {number} framePerSecond defines the number of frame per second yo use
  46958. * @param {number} totalFrame defines the number of frames in total
  46959. * @param {any} from defines the initial value
  46960. * @param {any} to defines the final value
  46961. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46962. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46963. * @param onAnimationEnd defines the callback to call when animation end
  46964. * @returns the animatable created for this animation
  46965. */
  46966. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46967. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46968. if (!animation) {
  46969. return null;
  46970. }
  46971. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46972. };
  46973. /**
  46974. * Create and start an animation on a node and its descendants
  46975. * @param {string} name defines the name of the global animation that will be run on all nodes
  46976. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46977. * @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.
  46978. * @param {string} targetProperty defines property to animate
  46979. * @param {number} framePerSecond defines the number of frame per second yo use
  46980. * @param {number} totalFrame defines the number of frames in total
  46981. * @param {any} from defines the initial value
  46982. * @param {any} to defines the final value
  46983. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46984. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46985. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46986. * @returns the list of animatables created for all nodes
  46987. * @example https://www.babylonjs-playground.com/#MH0VLI
  46988. */
  46989. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46990. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46991. if (!animation) {
  46992. return null;
  46993. }
  46994. var scene = node.getScene();
  46995. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46996. };
  46997. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46998. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46999. if (!animation) {
  47000. return null;
  47001. }
  47002. node.animations.push(animation);
  47003. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47004. };
  47005. /**
  47006. * Transition property of the Camera to the target Value.
  47007. * @param property The property to transition
  47008. * @param targetValue The target Value of the property
  47009. * @param host The object where the property to animate belongs
  47010. * @param scene Scene used to run the animation
  47011. * @param frameRate Framerate (in frame/s) to use
  47012. * @param transition The transition type we want to use
  47013. * @param duration The duration of the animation, in milliseconds
  47014. * @param onAnimationEnd Call back trigger at the end of the animation.
  47015. */
  47016. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47017. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47018. if (duration <= 0) {
  47019. host[property] = targetValue;
  47020. if (onAnimationEnd) {
  47021. onAnimationEnd();
  47022. }
  47023. return null;
  47024. }
  47025. var endFrame = frameRate * (duration / 1000);
  47026. transition.setKeys([{
  47027. frame: 0,
  47028. value: host[property].clone ? host[property].clone() : host[property]
  47029. },
  47030. {
  47031. frame: endFrame,
  47032. value: targetValue
  47033. }]);
  47034. if (!host.animations) {
  47035. host.animations = [];
  47036. }
  47037. host.animations.push(transition);
  47038. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47039. animation.onAnimationEnd = onAnimationEnd;
  47040. return animation;
  47041. };
  47042. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47043. /**
  47044. * Return the array of runtime animations currently using this animation
  47045. */
  47046. get: function () {
  47047. return this._runtimeAnimations;
  47048. },
  47049. enumerable: true,
  47050. configurable: true
  47051. });
  47052. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47053. get: function () {
  47054. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47055. var runtimeAnimation = _a[_i];
  47056. if (!runtimeAnimation.isStopped) {
  47057. return true;
  47058. }
  47059. }
  47060. return false;
  47061. },
  47062. enumerable: true,
  47063. configurable: true
  47064. });
  47065. // Methods
  47066. /**
  47067. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47068. */
  47069. Animation.prototype.toString = function (fullDetails) {
  47070. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47071. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47072. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47073. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47074. if (fullDetails) {
  47075. ret += ", Ranges: {";
  47076. var first = true;
  47077. for (var name in this._ranges) {
  47078. if (first) {
  47079. ret += ", ";
  47080. first = false;
  47081. }
  47082. ret += name;
  47083. }
  47084. ret += "}";
  47085. }
  47086. return ret;
  47087. };
  47088. /**
  47089. * Add an event to this animation.
  47090. */
  47091. Animation.prototype.addEvent = function (event) {
  47092. this._events.push(event);
  47093. };
  47094. /**
  47095. * Remove all events found at the given frame
  47096. * @param frame
  47097. */
  47098. Animation.prototype.removeEvents = function (frame) {
  47099. for (var index = 0; index < this._events.length; index++) {
  47100. if (this._events[index].frame === frame) {
  47101. this._events.splice(index, 1);
  47102. index--;
  47103. }
  47104. }
  47105. };
  47106. Animation.prototype.getEvents = function () {
  47107. return this._events;
  47108. };
  47109. Animation.prototype.createRange = function (name, from, to) {
  47110. // check name not already in use; could happen for bones after serialized
  47111. if (!this._ranges[name]) {
  47112. this._ranges[name] = new AnimationRange(name, from, to);
  47113. }
  47114. };
  47115. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47116. if (deleteFrames === void 0) { deleteFrames = true; }
  47117. var range = this._ranges[name];
  47118. if (!range) {
  47119. return;
  47120. }
  47121. if (deleteFrames) {
  47122. var from = range.from;
  47123. var to = range.to;
  47124. // this loop MUST go high to low for multiple splices to work
  47125. for (var key = this._keys.length - 1; key >= 0; key--) {
  47126. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47127. this._keys.splice(key, 1);
  47128. }
  47129. }
  47130. }
  47131. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47132. };
  47133. Animation.prototype.getRange = function (name) {
  47134. return this._ranges[name];
  47135. };
  47136. Animation.prototype.getKeys = function () {
  47137. return this._keys;
  47138. };
  47139. Animation.prototype.getHighestFrame = function () {
  47140. var ret = 0;
  47141. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47142. if (ret < this._keys[key].frame) {
  47143. ret = this._keys[key].frame;
  47144. }
  47145. }
  47146. return ret;
  47147. };
  47148. Animation.prototype.getEasingFunction = function () {
  47149. return this._easingFunction;
  47150. };
  47151. Animation.prototype.setEasingFunction = function (easingFunction) {
  47152. this._easingFunction = easingFunction;
  47153. };
  47154. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47155. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47156. };
  47157. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47158. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47159. };
  47160. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47161. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47162. };
  47163. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47164. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47165. };
  47166. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47167. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47168. };
  47169. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47170. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47171. };
  47172. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47173. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47174. };
  47175. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47176. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47177. };
  47178. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47179. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47180. };
  47181. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47182. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47183. };
  47184. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47185. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47186. };
  47187. Animation.prototype.clone = function () {
  47188. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47189. clone.enableBlending = this.enableBlending;
  47190. clone.blendingSpeed = this.blendingSpeed;
  47191. if (this._keys) {
  47192. clone.setKeys(this._keys);
  47193. }
  47194. if (this._ranges) {
  47195. clone._ranges = {};
  47196. for (var name in this._ranges) {
  47197. var range = this._ranges[name];
  47198. if (!range) {
  47199. continue;
  47200. }
  47201. clone._ranges[name] = range.clone();
  47202. }
  47203. }
  47204. return clone;
  47205. };
  47206. Animation.prototype.setKeys = function (values) {
  47207. this._keys = values.slice(0);
  47208. };
  47209. Animation.prototype.serialize = function () {
  47210. var serializationObject = {};
  47211. serializationObject.name = this.name;
  47212. serializationObject.property = this.targetProperty;
  47213. serializationObject.framePerSecond = this.framePerSecond;
  47214. serializationObject.dataType = this.dataType;
  47215. serializationObject.loopBehavior = this.loopMode;
  47216. serializationObject.enableBlending = this.enableBlending;
  47217. serializationObject.blendingSpeed = this.blendingSpeed;
  47218. var dataType = this.dataType;
  47219. serializationObject.keys = [];
  47220. var keys = this.getKeys();
  47221. for (var index = 0; index < keys.length; index++) {
  47222. var animationKey = keys[index];
  47223. var key = {};
  47224. key.frame = animationKey.frame;
  47225. switch (dataType) {
  47226. case Animation.ANIMATIONTYPE_FLOAT:
  47227. key.values = [animationKey.value];
  47228. break;
  47229. case Animation.ANIMATIONTYPE_QUATERNION:
  47230. case Animation.ANIMATIONTYPE_MATRIX:
  47231. case Animation.ANIMATIONTYPE_VECTOR3:
  47232. case Animation.ANIMATIONTYPE_COLOR3:
  47233. key.values = animationKey.value.asArray();
  47234. break;
  47235. }
  47236. serializationObject.keys.push(key);
  47237. }
  47238. serializationObject.ranges = [];
  47239. for (var name in this._ranges) {
  47240. var source = this._ranges[name];
  47241. if (!source) {
  47242. continue;
  47243. }
  47244. var range = {};
  47245. range.name = name;
  47246. range.from = source.from;
  47247. range.to = source.to;
  47248. serializationObject.ranges.push(range);
  47249. }
  47250. return serializationObject;
  47251. };
  47252. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47253. get: function () {
  47254. return Animation._ANIMATIONTYPE_FLOAT;
  47255. },
  47256. enumerable: true,
  47257. configurable: true
  47258. });
  47259. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47260. get: function () {
  47261. return Animation._ANIMATIONTYPE_VECTOR3;
  47262. },
  47263. enumerable: true,
  47264. configurable: true
  47265. });
  47266. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47267. get: function () {
  47268. return Animation._ANIMATIONTYPE_VECTOR2;
  47269. },
  47270. enumerable: true,
  47271. configurable: true
  47272. });
  47273. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47274. get: function () {
  47275. return Animation._ANIMATIONTYPE_SIZE;
  47276. },
  47277. enumerable: true,
  47278. configurable: true
  47279. });
  47280. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47281. get: function () {
  47282. return Animation._ANIMATIONTYPE_QUATERNION;
  47283. },
  47284. enumerable: true,
  47285. configurable: true
  47286. });
  47287. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47288. get: function () {
  47289. return Animation._ANIMATIONTYPE_MATRIX;
  47290. },
  47291. enumerable: true,
  47292. configurable: true
  47293. });
  47294. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47295. get: function () {
  47296. return Animation._ANIMATIONTYPE_COLOR3;
  47297. },
  47298. enumerable: true,
  47299. configurable: true
  47300. });
  47301. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47302. get: function () {
  47303. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47304. },
  47305. enumerable: true,
  47306. configurable: true
  47307. });
  47308. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47309. get: function () {
  47310. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47311. },
  47312. enumerable: true,
  47313. configurable: true
  47314. });
  47315. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47316. get: function () {
  47317. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47318. },
  47319. enumerable: true,
  47320. configurable: true
  47321. });
  47322. Animation.Parse = function (parsedAnimation) {
  47323. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47324. var dataType = parsedAnimation.dataType;
  47325. var keys = [];
  47326. var data;
  47327. var index;
  47328. if (parsedAnimation.enableBlending) {
  47329. animation.enableBlending = parsedAnimation.enableBlending;
  47330. }
  47331. if (parsedAnimation.blendingSpeed) {
  47332. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47333. }
  47334. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47335. var key = parsedAnimation.keys[index];
  47336. var inTangent;
  47337. var outTangent;
  47338. switch (dataType) {
  47339. case Animation.ANIMATIONTYPE_FLOAT:
  47340. data = key.values[0];
  47341. if (key.values.length >= 1) {
  47342. inTangent = key.values[1];
  47343. }
  47344. if (key.values.length >= 2) {
  47345. outTangent = key.values[2];
  47346. }
  47347. break;
  47348. case Animation.ANIMATIONTYPE_QUATERNION:
  47349. data = BABYLON.Quaternion.FromArray(key.values);
  47350. if (key.values.length >= 8) {
  47351. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47352. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47353. inTangent = _inTangent;
  47354. }
  47355. }
  47356. if (key.values.length >= 12) {
  47357. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47358. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47359. outTangent = _outTangent;
  47360. }
  47361. }
  47362. break;
  47363. case Animation.ANIMATIONTYPE_MATRIX:
  47364. data = BABYLON.Matrix.FromArray(key.values);
  47365. break;
  47366. case Animation.ANIMATIONTYPE_COLOR3:
  47367. data = BABYLON.Color3.FromArray(key.values);
  47368. break;
  47369. case Animation.ANIMATIONTYPE_VECTOR3:
  47370. default:
  47371. data = BABYLON.Vector3.FromArray(key.values);
  47372. break;
  47373. }
  47374. var keyData = {};
  47375. keyData.frame = key.frame;
  47376. keyData.value = data;
  47377. if (inTangent != undefined) {
  47378. keyData.inTangent = inTangent;
  47379. }
  47380. if (outTangent != undefined) {
  47381. keyData.outTangent = outTangent;
  47382. }
  47383. keys.push(keyData);
  47384. }
  47385. animation.setKeys(keys);
  47386. if (parsedAnimation.ranges) {
  47387. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47388. data = parsedAnimation.ranges[index];
  47389. animation.createRange(data.name, data.from, data.to);
  47390. }
  47391. }
  47392. return animation;
  47393. };
  47394. Animation.AppendSerializedAnimations = function (source, destination) {
  47395. if (source.animations) {
  47396. destination.animations = [];
  47397. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47398. var animation = source.animations[animationIndex];
  47399. destination.animations.push(animation.serialize());
  47400. }
  47401. }
  47402. };
  47403. Animation.AllowMatricesInterpolation = false;
  47404. // Statics
  47405. Animation._ANIMATIONTYPE_FLOAT = 0;
  47406. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47407. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47408. Animation._ANIMATIONTYPE_MATRIX = 3;
  47409. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47410. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47411. Animation._ANIMATIONTYPE_SIZE = 6;
  47412. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47413. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47414. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47415. return Animation;
  47416. }());
  47417. BABYLON.Animation = Animation;
  47418. })(BABYLON || (BABYLON = {}));
  47419. //# sourceMappingURL=babylon.animation.js.map
  47420. "use strict";
  47421. var BABYLON;
  47422. (function (BABYLON) {
  47423. /**
  47424. * This class defines the direct association between an animation and a target
  47425. */
  47426. var TargetedAnimation = /** @class */ (function () {
  47427. function TargetedAnimation() {
  47428. }
  47429. return TargetedAnimation;
  47430. }());
  47431. BABYLON.TargetedAnimation = TargetedAnimation;
  47432. /**
  47433. * Use this class to create coordinated animations on multiple targets
  47434. */
  47435. var AnimationGroup = /** @class */ (function () {
  47436. function AnimationGroup(name, scene) {
  47437. if (scene === void 0) { scene = null; }
  47438. this.name = name;
  47439. this._targetedAnimations = new Array();
  47440. this._animatables = new Array();
  47441. this._from = Number.MAX_VALUE;
  47442. this._to = -Number.MAX_VALUE;
  47443. this._speedRatio = 1;
  47444. this.onAnimationEndObservable = new BABYLON.Observable();
  47445. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47446. this._scene.animationGroups.push(this);
  47447. }
  47448. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47449. /**
  47450. * Define if the animations are started
  47451. */
  47452. get: function () {
  47453. return this._isStarted;
  47454. },
  47455. enumerable: true,
  47456. configurable: true
  47457. });
  47458. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47459. /**
  47460. * Gets or sets the speed ratio to use for all animations
  47461. */
  47462. get: function () {
  47463. return this._speedRatio;
  47464. },
  47465. /**
  47466. * Gets or sets the speed ratio to use for all animations
  47467. */
  47468. set: function (value) {
  47469. if (this._speedRatio === value) {
  47470. return;
  47471. }
  47472. this._speedRatio = value;
  47473. for (var index = 0; index < this._animatables.length; index++) {
  47474. var animatable = this._animatables[index];
  47475. animatable.speedRatio = this._speedRatio;
  47476. }
  47477. },
  47478. enumerable: true,
  47479. configurable: true
  47480. });
  47481. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47482. /**
  47483. * Gets the targeted animations for this animation group
  47484. */
  47485. get: function () {
  47486. return this._targetedAnimations;
  47487. },
  47488. enumerable: true,
  47489. configurable: true
  47490. });
  47491. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47492. /**
  47493. * returning the list of animatables controlled by this animation group.
  47494. */
  47495. get: function () {
  47496. return this._animatables;
  47497. },
  47498. enumerable: true,
  47499. configurable: true
  47500. });
  47501. /**
  47502. * Add an animation (with its target) in the group
  47503. * @param animation defines the animation we want to add
  47504. * @param target defines the target of the animation
  47505. * @returns the {BABYLON.TargetedAnimation} object
  47506. */
  47507. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47508. var targetedAnimation = {
  47509. animation: animation,
  47510. target: target
  47511. };
  47512. var keys = animation.getKeys();
  47513. if (this._from > keys[0].frame) {
  47514. this._from = keys[0].frame;
  47515. }
  47516. if (this._to < keys[keys.length - 1].frame) {
  47517. this._to = keys[keys.length - 1].frame;
  47518. }
  47519. this._targetedAnimations.push(targetedAnimation);
  47520. return targetedAnimation;
  47521. };
  47522. /**
  47523. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47524. * It can add constant keys at begin or end
  47525. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47526. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47527. */
  47528. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47529. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47530. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47531. beginFrame = Math.max(beginFrame, this._from);
  47532. endFrame = Math.min(endFrame, this._to);
  47533. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47534. var targetedAnimation = this._targetedAnimations[index];
  47535. var keys = targetedAnimation.animation.getKeys();
  47536. var startKey = keys[0];
  47537. var endKey = keys[keys.length - 1];
  47538. if (startKey.frame > beginFrame) {
  47539. var newKey = {
  47540. frame: beginFrame,
  47541. value: startKey.value,
  47542. inTangent: startKey.inTangent,
  47543. outTangent: startKey.outTangent,
  47544. interpolation: startKey.interpolation
  47545. };
  47546. keys.splice(0, 0, newKey);
  47547. }
  47548. if (endKey.frame < endFrame) {
  47549. var newKey = {
  47550. frame: endFrame,
  47551. value: endKey.value,
  47552. inTangent: endKey.outTangent,
  47553. outTangent: endKey.outTangent,
  47554. interpolation: endKey.interpolation
  47555. };
  47556. keys.push(newKey);
  47557. }
  47558. }
  47559. return this;
  47560. };
  47561. /**
  47562. * Start all animations on given targets
  47563. * @param loop defines if animations must loop
  47564. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47565. * @param from defines the from key (optional)
  47566. * @param to defines the to key (optional)
  47567. * @returns the current animation group
  47568. */
  47569. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47570. var _this = this;
  47571. if (loop === void 0) { loop = false; }
  47572. if (speedRatio === void 0) { speedRatio = 1; }
  47573. if (this._isStarted || this._targetedAnimations.length === 0) {
  47574. return this;
  47575. }
  47576. var _loop_1 = function () {
  47577. var targetedAnimation = this_1._targetedAnimations[index];
  47578. if (!targetedAnimation.target.animations) {
  47579. targetedAnimation.target.animations = [];
  47580. }
  47581. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47582. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47583. }
  47584. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  47585. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47586. }));
  47587. };
  47588. var this_1 = this;
  47589. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47590. _loop_1();
  47591. }
  47592. this._speedRatio = speedRatio;
  47593. this._isStarted = true;
  47594. return this;
  47595. };
  47596. /**
  47597. * Pause all animations
  47598. */
  47599. AnimationGroup.prototype.pause = function () {
  47600. if (!this._isStarted) {
  47601. return this;
  47602. }
  47603. for (var index = 0; index < this._animatables.length; index++) {
  47604. var animatable = this._animatables[index];
  47605. animatable.pause();
  47606. }
  47607. return this;
  47608. };
  47609. /**
  47610. * Play all animations to initial state
  47611. * This function will start() the animations if they were not started or will restart() them if they were paused
  47612. * @param loop defines if animations must loop
  47613. */
  47614. AnimationGroup.prototype.play = function (loop) {
  47615. if (this.isStarted) {
  47616. if (loop !== undefined) {
  47617. for (var index = 0; index < this._animatables.length; index++) {
  47618. var animatable = this._animatables[index];
  47619. animatable.loopAnimation = loop;
  47620. }
  47621. }
  47622. this.restart();
  47623. }
  47624. else {
  47625. this.start(loop, this._speedRatio);
  47626. }
  47627. return this;
  47628. };
  47629. /**
  47630. * Reset all animations to initial state
  47631. */
  47632. AnimationGroup.prototype.reset = function () {
  47633. if (!this._isStarted) {
  47634. return this;
  47635. }
  47636. for (var index = 0; index < this._animatables.length; index++) {
  47637. var animatable = this._animatables[index];
  47638. animatable.reset();
  47639. }
  47640. return this;
  47641. };
  47642. /**
  47643. * Restart animations from key 0
  47644. */
  47645. AnimationGroup.prototype.restart = function () {
  47646. if (!this._isStarted) {
  47647. return this;
  47648. }
  47649. for (var index = 0; index < this._animatables.length; index++) {
  47650. var animatable = this._animatables[index];
  47651. animatable.restart();
  47652. }
  47653. return this;
  47654. };
  47655. /**
  47656. * Stop all animations
  47657. */
  47658. AnimationGroup.prototype.stop = function () {
  47659. if (!this._isStarted) {
  47660. return this;
  47661. }
  47662. for (var index = 0; index < this._animatables.length; index++) {
  47663. var animatable = this._animatables[index];
  47664. animatable.stop();
  47665. }
  47666. this._isStarted = false;
  47667. return this;
  47668. };
  47669. /**
  47670. * Goes to a specific frame in this animation group
  47671. *
  47672. * @param frame the frame number to go to
  47673. * @return the animationGroup
  47674. */
  47675. AnimationGroup.prototype.goToFrame = function (frame) {
  47676. if (!this._isStarted) {
  47677. return this;
  47678. }
  47679. for (var index = 0; index < this._animatables.length; index++) {
  47680. var animatable = this._animatables[index];
  47681. animatable.goToFrame(frame);
  47682. }
  47683. return this;
  47684. };
  47685. /**
  47686. * Dispose all associated resources
  47687. */
  47688. AnimationGroup.prototype.dispose = function () {
  47689. this._targetedAnimations = [];
  47690. this._animatables = [];
  47691. var index = this._scene.animationGroups.indexOf(this);
  47692. if (index > -1) {
  47693. this._scene.animationGroups.splice(index, 1);
  47694. }
  47695. };
  47696. return AnimationGroup;
  47697. }());
  47698. BABYLON.AnimationGroup = AnimationGroup;
  47699. })(BABYLON || (BABYLON = {}));
  47700. //# sourceMappingURL=babylon.animationGroup.js.map
  47701. "use strict";
  47702. var BABYLON;
  47703. (function (BABYLON) {
  47704. var RuntimeAnimation = /** @class */ (function () {
  47705. /**
  47706. * Create a new RuntimeAnimation object
  47707. * @param target defines the target of the animation
  47708. * @param animation defines the source {BABYLON.Animation} object
  47709. * @param scene defines the hosting scene
  47710. * @param host defines the initiating Animatable
  47711. */
  47712. function RuntimeAnimation(target, animation, scene, host) {
  47713. this._currentFrame = 0;
  47714. this._offsetsCache = {};
  47715. this._highLimitsCache = {};
  47716. this._stopped = false;
  47717. this._blendingFactor = 0;
  47718. this._targetPath = "";
  47719. this._weight = 1.0;
  47720. this._ratioOffset = 0;
  47721. this._previousDelay = 0;
  47722. this._previousRatio = 0;
  47723. this._animation = animation;
  47724. this._target = target;
  47725. this._scene = scene;
  47726. this._host = host;
  47727. animation._runtimeAnimations.push(this);
  47728. }
  47729. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47730. /**
  47731. * Gets the current frame
  47732. */
  47733. get: function () {
  47734. return this._currentFrame;
  47735. },
  47736. enumerable: true,
  47737. configurable: true
  47738. });
  47739. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47740. /**
  47741. * Gets the weight of the runtime animation
  47742. */
  47743. get: function () {
  47744. return this._weight;
  47745. },
  47746. enumerable: true,
  47747. configurable: true
  47748. });
  47749. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47750. /**
  47751. * Gets the original value of the runtime animation
  47752. */
  47753. get: function () {
  47754. return this._originalValue;
  47755. },
  47756. enumerable: true,
  47757. configurable: true
  47758. });
  47759. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47760. /**
  47761. * Gets the current value of the runtime animation
  47762. */
  47763. get: function () {
  47764. return this._currentValue;
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47770. /**
  47771. * Gets the path where to store the animated value in the target
  47772. */
  47773. get: function () {
  47774. return this._targetPath;
  47775. },
  47776. enumerable: true,
  47777. configurable: true
  47778. });
  47779. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47780. /**
  47781. * Gets the actual target of the runtime animation
  47782. */
  47783. get: function () {
  47784. return this._activeTarget;
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47790. get: function () {
  47791. return this._animation;
  47792. },
  47793. enumerable: true,
  47794. configurable: true
  47795. });
  47796. RuntimeAnimation.prototype.reset = function () {
  47797. this._offsetsCache = {};
  47798. this._highLimitsCache = {};
  47799. this._currentFrame = 0;
  47800. this._blendingFactor = 0;
  47801. this._originalValue = null;
  47802. };
  47803. RuntimeAnimation.prototype.isStopped = function () {
  47804. return this._stopped;
  47805. };
  47806. RuntimeAnimation.prototype.dispose = function () {
  47807. var index = this._animation.runtimeAnimations.indexOf(this);
  47808. if (index > -1) {
  47809. this._animation.runtimeAnimations.splice(index, 1);
  47810. }
  47811. };
  47812. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47813. if (typeof value === "function") {
  47814. return value();
  47815. }
  47816. return value;
  47817. };
  47818. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47819. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47820. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47821. }
  47822. this._currentFrame = currentFrame;
  47823. var keys = this._animation.getKeys();
  47824. // Try to get a hash to find the right key
  47825. 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));
  47826. if (keys[startKeyIndex].frame >= currentFrame) {
  47827. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47828. startKeyIndex--;
  47829. }
  47830. }
  47831. for (var key = startKeyIndex; key < keys.length; key++) {
  47832. var endKey = keys[key + 1];
  47833. if (endKey.frame >= currentFrame) {
  47834. var startKey = keys[key];
  47835. var startValue = this._getKeyValue(startKey.value);
  47836. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47837. return startValue;
  47838. }
  47839. var endValue = this._getKeyValue(endKey.value);
  47840. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47841. var frameDelta = endKey.frame - startKey.frame;
  47842. // gradient : percent of currentFrame between the frame inf and the frame sup
  47843. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47844. // check for easingFunction and correction of gradient
  47845. var easingFunction = this._animation.getEasingFunction();
  47846. if (easingFunction != null) {
  47847. gradient = easingFunction.ease(gradient);
  47848. }
  47849. switch (this._animation.dataType) {
  47850. // Float
  47851. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47852. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47853. switch (loopMode) {
  47854. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47855. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47856. return floatValue;
  47857. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47858. return offsetValue * repeatCount + floatValue;
  47859. }
  47860. break;
  47861. // Quaternion
  47862. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47863. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47864. switch (loopMode) {
  47865. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47866. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47867. return quatValue;
  47868. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47869. return quatValue.add(offsetValue.scale(repeatCount));
  47870. }
  47871. return quatValue;
  47872. // Vector3
  47873. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47874. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47875. switch (loopMode) {
  47876. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47877. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47878. return vec3Value;
  47879. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47880. return vec3Value.add(offsetValue.scale(repeatCount));
  47881. }
  47882. // Vector2
  47883. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47884. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47885. switch (loopMode) {
  47886. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47887. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47888. return vec2Value;
  47889. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47890. return vec2Value.add(offsetValue.scale(repeatCount));
  47891. }
  47892. // Size
  47893. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47894. switch (loopMode) {
  47895. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47896. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47897. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47898. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47899. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47900. }
  47901. // Color3
  47902. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47903. switch (loopMode) {
  47904. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47905. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47906. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47907. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47908. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47909. }
  47910. // Matrix
  47911. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47912. switch (loopMode) {
  47913. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47914. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47915. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47916. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47917. }
  47918. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47919. return startValue;
  47920. }
  47921. default:
  47922. break;
  47923. }
  47924. break;
  47925. }
  47926. }
  47927. return this._getKeyValue(keys[keys.length - 1].value);
  47928. };
  47929. /**
  47930. * Affect the interpolated value to the target
  47931. * @param currentValue defines the value computed by the animation
  47932. * @param weight defines the weight to apply to this value
  47933. */
  47934. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47935. if (weight === void 0) { weight = 1.0; }
  47936. // Set value
  47937. var path;
  47938. var destination;
  47939. var targetPropertyPath = this._animation.targetPropertyPath;
  47940. if (targetPropertyPath.length > 1) {
  47941. var property = this._target[targetPropertyPath[0]];
  47942. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47943. property = property[targetPropertyPath[index]];
  47944. }
  47945. path = targetPropertyPath[targetPropertyPath.length - 1];
  47946. destination = property;
  47947. }
  47948. else {
  47949. path = targetPropertyPath[0];
  47950. destination = this._target;
  47951. }
  47952. this._targetPath = path;
  47953. this._activeTarget = destination;
  47954. this._weight = weight;
  47955. // Blending
  47956. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47957. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47958. if (enableBlending && this._blendingFactor <= 1.0) {
  47959. if (!this._originalBlendValue) {
  47960. var originalValue = destination[path];
  47961. if (originalValue.clone) {
  47962. this._originalBlendValue = originalValue.clone();
  47963. }
  47964. else {
  47965. this._originalBlendValue = originalValue;
  47966. }
  47967. }
  47968. }
  47969. if (weight !== -1.0) {
  47970. if (!this._originalValue) {
  47971. var originalValue = void 0;
  47972. if (destination.getRestPose) {
  47973. originalValue = destination.getRestPose();
  47974. }
  47975. else {
  47976. originalValue = destination[path];
  47977. }
  47978. if (originalValue.clone) {
  47979. this._originalValue = originalValue.clone();
  47980. }
  47981. else {
  47982. this._originalValue = originalValue;
  47983. }
  47984. }
  47985. }
  47986. if (enableBlending && this._blendingFactor <= 1.0) {
  47987. if (this._originalBlendValue.prototype) {
  47988. if (this._originalBlendValue.prototype.Lerp) {
  47989. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47990. }
  47991. else {
  47992. this._currentValue = currentValue;
  47993. }
  47994. }
  47995. else if (this._originalBlendValue.m) {
  47996. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47997. }
  47998. else {
  47999. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48000. }
  48001. this._blendingFactor += blendingSpeed;
  48002. }
  48003. else {
  48004. this._currentValue = currentValue;
  48005. }
  48006. if (weight !== -1.0) {
  48007. this._scene._registerTargetForLateAnimationBinding(this);
  48008. }
  48009. else {
  48010. destination[path] = this._currentValue;
  48011. }
  48012. if (this._target.markAsDirty) {
  48013. this._target.markAsDirty(this._animation.targetProperty);
  48014. }
  48015. };
  48016. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48017. if (this._target && this._target.animationPropertiesOverride) {
  48018. return this._target.animationPropertiesOverride.loopMode;
  48019. }
  48020. return this._animation.loopMode;
  48021. };
  48022. /**
  48023. * Move the current animation to a given frame
  48024. * @param frame defines the frame to move to
  48025. */
  48026. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48027. var keys = this._animation.getKeys();
  48028. if (frame < keys[0].frame) {
  48029. frame = keys[0].frame;
  48030. }
  48031. else if (frame > keys[keys.length - 1].frame) {
  48032. frame = keys[keys.length - 1].frame;
  48033. }
  48034. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48035. this.setValue(currentValue, -1);
  48036. };
  48037. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48038. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48039. this._ratioOffset = this._previousRatio - newRatio;
  48040. };
  48041. /**
  48042. * Execute the current animation
  48043. * @param delay defines the delay to add to the current frame
  48044. * @param from defines the lower bound of the animation range
  48045. * @param to defines the upper bound of the animation range
  48046. * @param loop defines if the current animation must loop
  48047. * @param speedRatio defines the current speed ratio
  48048. * @param weight defines the weight of the animation (default is -1 so no weight)
  48049. * @returns a boolean indicating if the animation has ended
  48050. */
  48051. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48052. if (weight === void 0) { weight = -1.0; }
  48053. var targetPropertyPath = this._animation.targetPropertyPath;
  48054. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48055. this._stopped = true;
  48056. return false;
  48057. }
  48058. var returnValue = true;
  48059. var keys = this._animation.getKeys();
  48060. // Adding a start key at frame 0 if missing
  48061. if (keys[0].frame !== 0) {
  48062. var newKey = { frame: 0, value: keys[0].value };
  48063. keys.splice(0, 0, newKey);
  48064. }
  48065. // Check limits
  48066. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48067. from = keys[0].frame;
  48068. }
  48069. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48070. to = keys[keys.length - 1].frame;
  48071. }
  48072. //to and from cannot be the same key
  48073. if (from === to) {
  48074. if (from > keys[0].frame) {
  48075. from--;
  48076. }
  48077. else if (to < keys[keys.length - 1].frame) {
  48078. to++;
  48079. }
  48080. }
  48081. // Compute ratio
  48082. var range = to - from;
  48083. var offsetValue;
  48084. // ratio represents the frame delta between from and to
  48085. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48086. var highLimitValue = 0;
  48087. this._previousDelay = delay;
  48088. this._previousRatio = ratio;
  48089. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48090. returnValue = false;
  48091. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48092. }
  48093. else {
  48094. // Get max value if required
  48095. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48096. var keyOffset = to.toString() + from.toString();
  48097. if (!this._offsetsCache[keyOffset]) {
  48098. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48099. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48100. switch (this._animation.dataType) {
  48101. // Float
  48102. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48103. this._offsetsCache[keyOffset] = toValue - fromValue;
  48104. break;
  48105. // Quaternion
  48106. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48107. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48108. break;
  48109. // Vector3
  48110. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48111. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48112. // Vector2
  48113. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48114. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48115. // Size
  48116. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48117. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48118. // Color3
  48119. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48120. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48121. default:
  48122. break;
  48123. }
  48124. this._highLimitsCache[keyOffset] = toValue;
  48125. }
  48126. highLimitValue = this._highLimitsCache[keyOffset];
  48127. offsetValue = this._offsetsCache[keyOffset];
  48128. }
  48129. }
  48130. if (offsetValue === undefined) {
  48131. switch (this._animation.dataType) {
  48132. // Float
  48133. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48134. offsetValue = 0;
  48135. break;
  48136. // Quaternion
  48137. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48138. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48139. break;
  48140. // Vector3
  48141. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48142. offsetValue = BABYLON.Vector3.Zero();
  48143. break;
  48144. // Vector2
  48145. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48146. offsetValue = BABYLON.Vector2.Zero();
  48147. break;
  48148. // Size
  48149. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48150. offsetValue = BABYLON.Size.Zero();
  48151. break;
  48152. // Color3
  48153. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48154. offsetValue = BABYLON.Color3.Black();
  48155. }
  48156. }
  48157. // Compute value
  48158. var repeatCount = (ratio / range) >> 0;
  48159. var currentFrame = returnValue ? from + ratio % range : to;
  48160. // Need to normalize?
  48161. if (this._host && this._host.syncRoot) {
  48162. var syncRoot = this._host.syncRoot;
  48163. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48164. currentFrame = from + (to - from) * hostNormalizedFrame;
  48165. }
  48166. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48167. // Set value
  48168. this.setValue(currentValue, weight);
  48169. // Check events
  48170. var events = this._animation.getEvents();
  48171. for (var index = 0; index < events.length; index++) {
  48172. // Make sure current frame has passed event frame and that event frame is within the current range
  48173. // Also, handle both forward and reverse animations
  48174. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48175. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48176. var event = events[index];
  48177. if (!event.isDone) {
  48178. // If event should be done only once, remove it.
  48179. if (event.onlyOnce) {
  48180. events.splice(index, 1);
  48181. index--;
  48182. }
  48183. event.isDone = true;
  48184. event.action();
  48185. } // Don't do anything if the event has already be done.
  48186. }
  48187. else if (events[index].isDone && !events[index].onlyOnce) {
  48188. // reset event, the animation is looping
  48189. events[index].isDone = false;
  48190. }
  48191. }
  48192. if (!returnValue) {
  48193. this._stopped = true;
  48194. }
  48195. return returnValue;
  48196. };
  48197. return RuntimeAnimation;
  48198. }());
  48199. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48200. })(BABYLON || (BABYLON = {}));
  48201. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48202. "use strict";
  48203. var BABYLON;
  48204. (function (BABYLON) {
  48205. var Animatable = /** @class */ (function () {
  48206. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48207. if (fromFrame === void 0) { fromFrame = 0; }
  48208. if (toFrame === void 0) { toFrame = 100; }
  48209. if (loopAnimation === void 0) { loopAnimation = false; }
  48210. if (speedRatio === void 0) { speedRatio = 1.0; }
  48211. this.target = target;
  48212. this.fromFrame = fromFrame;
  48213. this.toFrame = toFrame;
  48214. this.loopAnimation = loopAnimation;
  48215. this.onAnimationEnd = onAnimationEnd;
  48216. this._localDelayOffset = null;
  48217. this._pausedDelay = null;
  48218. this._runtimeAnimations = new Array();
  48219. this._paused = false;
  48220. this._speedRatio = 1;
  48221. this._weight = -1.0;
  48222. this.animationStarted = false;
  48223. if (animations) {
  48224. this.appendAnimations(target, animations);
  48225. }
  48226. this._speedRatio = speedRatio;
  48227. this._scene = scene;
  48228. scene._activeAnimatables.push(this);
  48229. }
  48230. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48231. /**
  48232. * Gets the root Animatable used to synchronize and normalize animations
  48233. */
  48234. get: function () {
  48235. return this._syncRoot;
  48236. },
  48237. enumerable: true,
  48238. configurable: true
  48239. });
  48240. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48241. /**
  48242. * Gets the current frame of the first RuntimeAnimation
  48243. * Used to synchronize Animatables
  48244. */
  48245. get: function () {
  48246. if (this._runtimeAnimations.length === 0) {
  48247. return 0;
  48248. }
  48249. return this._runtimeAnimations[0].currentFrame;
  48250. },
  48251. enumerable: true,
  48252. configurable: true
  48253. });
  48254. Object.defineProperty(Animatable.prototype, "weight", {
  48255. /**
  48256. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48257. */
  48258. get: function () {
  48259. return this._weight;
  48260. },
  48261. set: function (value) {
  48262. if (value === -1) {
  48263. this._weight = -1;
  48264. return;
  48265. }
  48266. // Else weight must be in [0, 1] range
  48267. this._weight = Math.min(Math.max(value, 0), 1.0);
  48268. },
  48269. enumerable: true,
  48270. configurable: true
  48271. });
  48272. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48273. /**
  48274. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48275. */
  48276. get: function () {
  48277. return this._speedRatio;
  48278. },
  48279. set: function (value) {
  48280. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48281. var animation = this._runtimeAnimations[index];
  48282. animation._prepareForSpeedRatioChange(value);
  48283. }
  48284. this._speedRatio = value;
  48285. },
  48286. enumerable: true,
  48287. configurable: true
  48288. });
  48289. // Methods
  48290. /**
  48291. * Synchronize and normalize current Animatable with a source Animatable.
  48292. * This is useful when using animation weights and when animations are not of the same length
  48293. * @param root defines the root Animatable to synchronize with
  48294. * @returns the current Animatable
  48295. */
  48296. Animatable.prototype.syncWith = function (root) {
  48297. this._syncRoot = root;
  48298. if (root) {
  48299. // Make sure this animatable will animate after the root
  48300. var index = this._scene._activeAnimatables.indexOf(this);
  48301. if (index > -1) {
  48302. this._scene._activeAnimatables.splice(index, 1);
  48303. this._scene._activeAnimatables.push(this);
  48304. }
  48305. }
  48306. return this;
  48307. };
  48308. Animatable.prototype.getAnimations = function () {
  48309. return this._runtimeAnimations;
  48310. };
  48311. Animatable.prototype.appendAnimations = function (target, animations) {
  48312. for (var index = 0; index < animations.length; index++) {
  48313. var animation = animations[index];
  48314. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48315. }
  48316. };
  48317. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48318. var runtimeAnimations = this._runtimeAnimations;
  48319. for (var index = 0; index < runtimeAnimations.length; index++) {
  48320. if (runtimeAnimations[index].animation.targetProperty === property) {
  48321. return runtimeAnimations[index].animation;
  48322. }
  48323. }
  48324. return null;
  48325. };
  48326. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48327. var runtimeAnimations = this._runtimeAnimations;
  48328. for (var index = 0; index < runtimeAnimations.length; index++) {
  48329. if (runtimeAnimations[index].animation.targetProperty === property) {
  48330. return runtimeAnimations[index];
  48331. }
  48332. }
  48333. return null;
  48334. };
  48335. Animatable.prototype.reset = function () {
  48336. var runtimeAnimations = this._runtimeAnimations;
  48337. for (var index = 0; index < runtimeAnimations.length; index++) {
  48338. runtimeAnimations[index].reset();
  48339. }
  48340. // Reset to original value
  48341. for (index = 0; index < runtimeAnimations.length; index++) {
  48342. var animation = runtimeAnimations[index];
  48343. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48344. }
  48345. this._localDelayOffset = null;
  48346. this._pausedDelay = null;
  48347. };
  48348. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48349. var runtimeAnimations = this._runtimeAnimations;
  48350. for (var index = 0; index < runtimeAnimations.length; index++) {
  48351. runtimeAnimations[index].animation.enableBlending = true;
  48352. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48353. }
  48354. };
  48355. Animatable.prototype.disableBlending = function () {
  48356. var runtimeAnimations = this._runtimeAnimations;
  48357. for (var index = 0; index < runtimeAnimations.length; index++) {
  48358. runtimeAnimations[index].animation.enableBlending = false;
  48359. }
  48360. };
  48361. Animatable.prototype.goToFrame = function (frame) {
  48362. var runtimeAnimations = this._runtimeAnimations;
  48363. if (runtimeAnimations[0]) {
  48364. var fps = runtimeAnimations[0].animation.framePerSecond;
  48365. var currentFrame = runtimeAnimations[0].currentFrame;
  48366. var adjustTime = frame - currentFrame;
  48367. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48368. if (this._localDelayOffset === null) {
  48369. this._localDelayOffset = 0;
  48370. }
  48371. this._localDelayOffset -= delay;
  48372. }
  48373. for (var index = 0; index < runtimeAnimations.length; index++) {
  48374. runtimeAnimations[index].goToFrame(frame);
  48375. }
  48376. };
  48377. Animatable.prototype.pause = function () {
  48378. if (this._paused) {
  48379. return;
  48380. }
  48381. this._paused = true;
  48382. };
  48383. Animatable.prototype.restart = function () {
  48384. this._paused = false;
  48385. };
  48386. Animatable.prototype.stop = function (animationName) {
  48387. if (animationName) {
  48388. var idx = this._scene._activeAnimatables.indexOf(this);
  48389. if (idx > -1) {
  48390. var runtimeAnimations = this._runtimeAnimations;
  48391. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48392. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48393. continue;
  48394. }
  48395. runtimeAnimations[index].dispose();
  48396. runtimeAnimations.splice(index, 1);
  48397. }
  48398. if (runtimeAnimations.length == 0) {
  48399. this._scene._activeAnimatables.splice(idx, 1);
  48400. if (this.onAnimationEnd) {
  48401. this.onAnimationEnd();
  48402. }
  48403. }
  48404. }
  48405. }
  48406. else {
  48407. var index = this._scene._activeAnimatables.indexOf(this);
  48408. if (index > -1) {
  48409. this._scene._activeAnimatables.splice(index, 1);
  48410. var runtimeAnimations = this._runtimeAnimations;
  48411. for (var index = 0; index < runtimeAnimations.length; index++) {
  48412. runtimeAnimations[index].dispose();
  48413. }
  48414. if (this.onAnimationEnd) {
  48415. this.onAnimationEnd();
  48416. }
  48417. }
  48418. }
  48419. };
  48420. Animatable.prototype._animate = function (delay) {
  48421. if (this._paused) {
  48422. this.animationStarted = false;
  48423. if (this._pausedDelay === null) {
  48424. this._pausedDelay = delay;
  48425. }
  48426. return true;
  48427. }
  48428. if (this._localDelayOffset === null) {
  48429. this._localDelayOffset = delay;
  48430. this._pausedDelay = null;
  48431. }
  48432. else if (this._pausedDelay !== null) {
  48433. this._localDelayOffset += delay - this._pausedDelay;
  48434. this._pausedDelay = null;
  48435. }
  48436. if (this._weight === 0) {
  48437. return true;
  48438. }
  48439. // Animating
  48440. var running = false;
  48441. var runtimeAnimations = this._runtimeAnimations;
  48442. var index;
  48443. for (index = 0; index < runtimeAnimations.length; index++) {
  48444. var animation = runtimeAnimations[index];
  48445. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48446. running = running || isRunning;
  48447. }
  48448. this.animationStarted = running;
  48449. if (!running) {
  48450. // Remove from active animatables
  48451. index = this._scene._activeAnimatables.indexOf(this);
  48452. this._scene._activeAnimatables.splice(index, 1);
  48453. // Dispose all runtime animations
  48454. for (index = 0; index < runtimeAnimations.length; index++) {
  48455. runtimeAnimations[index].dispose();
  48456. }
  48457. }
  48458. if (!running && this.onAnimationEnd) {
  48459. this.onAnimationEnd();
  48460. this.onAnimationEnd = null;
  48461. }
  48462. return running;
  48463. };
  48464. return Animatable;
  48465. }());
  48466. BABYLON.Animatable = Animatable;
  48467. })(BABYLON || (BABYLON = {}));
  48468. //# sourceMappingURL=babylon.animatable.js.map
  48469. "use strict";
  48470. var BABYLON;
  48471. (function (BABYLON) {
  48472. var EasingFunction = /** @class */ (function () {
  48473. function EasingFunction() {
  48474. // Properties
  48475. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48476. }
  48477. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48478. get: function () {
  48479. return EasingFunction._EASINGMODE_EASEIN;
  48480. },
  48481. enumerable: true,
  48482. configurable: true
  48483. });
  48484. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48485. get: function () {
  48486. return EasingFunction._EASINGMODE_EASEOUT;
  48487. },
  48488. enumerable: true,
  48489. configurable: true
  48490. });
  48491. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48492. get: function () {
  48493. return EasingFunction._EASINGMODE_EASEINOUT;
  48494. },
  48495. enumerable: true,
  48496. configurable: true
  48497. });
  48498. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48499. var n = Math.min(Math.max(easingMode, 0), 2);
  48500. this._easingMode = n;
  48501. };
  48502. EasingFunction.prototype.getEasingMode = function () {
  48503. return this._easingMode;
  48504. };
  48505. EasingFunction.prototype.easeInCore = function (gradient) {
  48506. throw new Error('You must implement this method');
  48507. };
  48508. EasingFunction.prototype.ease = function (gradient) {
  48509. switch (this._easingMode) {
  48510. case EasingFunction.EASINGMODE_EASEIN:
  48511. return this.easeInCore(gradient);
  48512. case EasingFunction.EASINGMODE_EASEOUT:
  48513. return (1 - this.easeInCore(1 - gradient));
  48514. }
  48515. if (gradient >= 0.5) {
  48516. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48517. }
  48518. return (this.easeInCore(gradient * 2) * 0.5);
  48519. };
  48520. //Statics
  48521. EasingFunction._EASINGMODE_EASEIN = 0;
  48522. EasingFunction._EASINGMODE_EASEOUT = 1;
  48523. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48524. return EasingFunction;
  48525. }());
  48526. BABYLON.EasingFunction = EasingFunction;
  48527. var CircleEase = /** @class */ (function (_super) {
  48528. __extends(CircleEase, _super);
  48529. function CircleEase() {
  48530. return _super !== null && _super.apply(this, arguments) || this;
  48531. }
  48532. CircleEase.prototype.easeInCore = function (gradient) {
  48533. gradient = Math.max(0, Math.min(1, gradient));
  48534. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48535. };
  48536. return CircleEase;
  48537. }(EasingFunction));
  48538. BABYLON.CircleEase = CircleEase;
  48539. var BackEase = /** @class */ (function (_super) {
  48540. __extends(BackEase, _super);
  48541. function BackEase(amplitude) {
  48542. if (amplitude === void 0) { amplitude = 1; }
  48543. var _this = _super.call(this) || this;
  48544. _this.amplitude = amplitude;
  48545. return _this;
  48546. }
  48547. BackEase.prototype.easeInCore = function (gradient) {
  48548. var num = Math.max(0, this.amplitude);
  48549. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48550. };
  48551. return BackEase;
  48552. }(EasingFunction));
  48553. BABYLON.BackEase = BackEase;
  48554. var BounceEase = /** @class */ (function (_super) {
  48555. __extends(BounceEase, _super);
  48556. function BounceEase(bounces, bounciness) {
  48557. if (bounces === void 0) { bounces = 3; }
  48558. if (bounciness === void 0) { bounciness = 2; }
  48559. var _this = _super.call(this) || this;
  48560. _this.bounces = bounces;
  48561. _this.bounciness = bounciness;
  48562. return _this;
  48563. }
  48564. BounceEase.prototype.easeInCore = function (gradient) {
  48565. var y = Math.max(0.0, this.bounces);
  48566. var bounciness = this.bounciness;
  48567. if (bounciness <= 1.0) {
  48568. bounciness = 1.001;
  48569. }
  48570. var num9 = Math.pow(bounciness, y);
  48571. var num5 = 1.0 - bounciness;
  48572. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48573. var num15 = gradient * num4;
  48574. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48575. var num3 = Math.floor(num65);
  48576. var num13 = num3 + 1.0;
  48577. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48578. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48579. var num7 = (num8 + num12) * 0.5;
  48580. var num6 = gradient - num7;
  48581. var num2 = num7 - num8;
  48582. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48583. };
  48584. return BounceEase;
  48585. }(EasingFunction));
  48586. BABYLON.BounceEase = BounceEase;
  48587. var CubicEase = /** @class */ (function (_super) {
  48588. __extends(CubicEase, _super);
  48589. function CubicEase() {
  48590. return _super !== null && _super.apply(this, arguments) || this;
  48591. }
  48592. CubicEase.prototype.easeInCore = function (gradient) {
  48593. return (gradient * gradient * gradient);
  48594. };
  48595. return CubicEase;
  48596. }(EasingFunction));
  48597. BABYLON.CubicEase = CubicEase;
  48598. var ElasticEase = /** @class */ (function (_super) {
  48599. __extends(ElasticEase, _super);
  48600. function ElasticEase(oscillations, springiness) {
  48601. if (oscillations === void 0) { oscillations = 3; }
  48602. if (springiness === void 0) { springiness = 3; }
  48603. var _this = _super.call(this) || this;
  48604. _this.oscillations = oscillations;
  48605. _this.springiness = springiness;
  48606. return _this;
  48607. }
  48608. ElasticEase.prototype.easeInCore = function (gradient) {
  48609. var num2;
  48610. var num3 = Math.max(0.0, this.oscillations);
  48611. var num = Math.max(0.0, this.springiness);
  48612. if (num == 0) {
  48613. num2 = gradient;
  48614. }
  48615. else {
  48616. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48617. }
  48618. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48619. };
  48620. return ElasticEase;
  48621. }(EasingFunction));
  48622. BABYLON.ElasticEase = ElasticEase;
  48623. var ExponentialEase = /** @class */ (function (_super) {
  48624. __extends(ExponentialEase, _super);
  48625. function ExponentialEase(exponent) {
  48626. if (exponent === void 0) { exponent = 2; }
  48627. var _this = _super.call(this) || this;
  48628. _this.exponent = exponent;
  48629. return _this;
  48630. }
  48631. ExponentialEase.prototype.easeInCore = function (gradient) {
  48632. if (this.exponent <= 0) {
  48633. return gradient;
  48634. }
  48635. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48636. };
  48637. return ExponentialEase;
  48638. }(EasingFunction));
  48639. BABYLON.ExponentialEase = ExponentialEase;
  48640. var PowerEase = /** @class */ (function (_super) {
  48641. __extends(PowerEase, _super);
  48642. function PowerEase(power) {
  48643. if (power === void 0) { power = 2; }
  48644. var _this = _super.call(this) || this;
  48645. _this.power = power;
  48646. return _this;
  48647. }
  48648. PowerEase.prototype.easeInCore = function (gradient) {
  48649. var y = Math.max(0.0, this.power);
  48650. return Math.pow(gradient, y);
  48651. };
  48652. return PowerEase;
  48653. }(EasingFunction));
  48654. BABYLON.PowerEase = PowerEase;
  48655. var QuadraticEase = /** @class */ (function (_super) {
  48656. __extends(QuadraticEase, _super);
  48657. function QuadraticEase() {
  48658. return _super !== null && _super.apply(this, arguments) || this;
  48659. }
  48660. QuadraticEase.prototype.easeInCore = function (gradient) {
  48661. return (gradient * gradient);
  48662. };
  48663. return QuadraticEase;
  48664. }(EasingFunction));
  48665. BABYLON.QuadraticEase = QuadraticEase;
  48666. var QuarticEase = /** @class */ (function (_super) {
  48667. __extends(QuarticEase, _super);
  48668. function QuarticEase() {
  48669. return _super !== null && _super.apply(this, arguments) || this;
  48670. }
  48671. QuarticEase.prototype.easeInCore = function (gradient) {
  48672. return (gradient * gradient * gradient * gradient);
  48673. };
  48674. return QuarticEase;
  48675. }(EasingFunction));
  48676. BABYLON.QuarticEase = QuarticEase;
  48677. var QuinticEase = /** @class */ (function (_super) {
  48678. __extends(QuinticEase, _super);
  48679. function QuinticEase() {
  48680. return _super !== null && _super.apply(this, arguments) || this;
  48681. }
  48682. QuinticEase.prototype.easeInCore = function (gradient) {
  48683. return (gradient * gradient * gradient * gradient * gradient);
  48684. };
  48685. return QuinticEase;
  48686. }(EasingFunction));
  48687. BABYLON.QuinticEase = QuinticEase;
  48688. var SineEase = /** @class */ (function (_super) {
  48689. __extends(SineEase, _super);
  48690. function SineEase() {
  48691. return _super !== null && _super.apply(this, arguments) || this;
  48692. }
  48693. SineEase.prototype.easeInCore = function (gradient) {
  48694. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48695. };
  48696. return SineEase;
  48697. }(EasingFunction));
  48698. BABYLON.SineEase = SineEase;
  48699. var BezierCurveEase = /** @class */ (function (_super) {
  48700. __extends(BezierCurveEase, _super);
  48701. function BezierCurveEase(x1, y1, x2, y2) {
  48702. if (x1 === void 0) { x1 = 0; }
  48703. if (y1 === void 0) { y1 = 0; }
  48704. if (x2 === void 0) { x2 = 1; }
  48705. if (y2 === void 0) { y2 = 1; }
  48706. var _this = _super.call(this) || this;
  48707. _this.x1 = x1;
  48708. _this.y1 = y1;
  48709. _this.x2 = x2;
  48710. _this.y2 = y2;
  48711. return _this;
  48712. }
  48713. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48714. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48715. };
  48716. return BezierCurveEase;
  48717. }(EasingFunction));
  48718. BABYLON.BezierCurveEase = BezierCurveEase;
  48719. })(BABYLON || (BABYLON = {}));
  48720. //# sourceMappingURL=babylon.easing.js.map
  48721. "use strict";
  48722. var BABYLON;
  48723. (function (BABYLON) {
  48724. /**
  48725. * A Condition applied to an Action
  48726. */
  48727. var Condition = /** @class */ (function () {
  48728. /**
  48729. * Creates a new Condition
  48730. * @param actionManager the manager of the action the condition is applied to
  48731. */
  48732. function Condition(actionManager) {
  48733. this._actionManager = actionManager;
  48734. }
  48735. /**
  48736. * Check if the current condition is valid
  48737. * @returns a boolean
  48738. */
  48739. Condition.prototype.isValid = function () {
  48740. return true;
  48741. };
  48742. /**
  48743. * Internal only
  48744. * @ignore
  48745. */
  48746. Condition.prototype._getProperty = function (propertyPath) {
  48747. return this._actionManager._getProperty(propertyPath);
  48748. };
  48749. /**
  48750. * Internal only
  48751. * @ignore
  48752. */
  48753. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48754. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48755. };
  48756. /**
  48757. * Serialize placeholder for child classes
  48758. * @returns the serialized object
  48759. */
  48760. Condition.prototype.serialize = function () {
  48761. };
  48762. /**
  48763. * Internal only
  48764. * @ignore
  48765. */
  48766. Condition.prototype._serialize = function (serializedCondition) {
  48767. return {
  48768. type: 2,
  48769. children: [],
  48770. name: serializedCondition.name,
  48771. properties: serializedCondition.properties
  48772. };
  48773. };
  48774. return Condition;
  48775. }());
  48776. BABYLON.Condition = Condition;
  48777. /**
  48778. * Defines specific conditional operators as extensions of Condition
  48779. */
  48780. var ValueCondition = /** @class */ (function (_super) {
  48781. __extends(ValueCondition, _super);
  48782. /**
  48783. * Creates a new ValueCondition
  48784. * @param actionManager manager for the action the condition applies to
  48785. * @param target for the action
  48786. * @param propertyPath path to specify the property of the target the conditional operator uses
  48787. * @param value the vale compared by the conditional operator against the current value of the property
  48788. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  48789. */
  48790. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48791. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48792. var _this = _super.call(this, actionManager) || this;
  48793. _this.propertyPath = propertyPath;
  48794. _this.value = value;
  48795. _this.operator = operator;
  48796. _this._target = target;
  48797. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48798. _this._property = _this._getProperty(_this.propertyPath);
  48799. return _this;
  48800. }
  48801. Object.defineProperty(ValueCondition, "IsEqual", {
  48802. /**
  48803. * returns the number for IsEqual
  48804. */
  48805. get: function () {
  48806. return ValueCondition._IsEqual;
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. Object.defineProperty(ValueCondition, "IsDifferent", {
  48812. /**
  48813. * Returns the number for IsDifferent
  48814. */
  48815. get: function () {
  48816. return ValueCondition._IsDifferent;
  48817. },
  48818. enumerable: true,
  48819. configurable: true
  48820. });
  48821. Object.defineProperty(ValueCondition, "IsGreater", {
  48822. /**
  48823. * Returns the number for IsGreater
  48824. */
  48825. get: function () {
  48826. return ValueCondition._IsGreater;
  48827. },
  48828. enumerable: true,
  48829. configurable: true
  48830. });
  48831. Object.defineProperty(ValueCondition, "IsLesser", {
  48832. /**
  48833. * Returns the number for IsLesser
  48834. */
  48835. get: function () {
  48836. return ValueCondition._IsLesser;
  48837. },
  48838. enumerable: true,
  48839. configurable: true
  48840. });
  48841. /**
  48842. * Compares the given value with the property value for the specified conditional operator
  48843. * @returns the result of the comparison
  48844. */
  48845. ValueCondition.prototype.isValid = function () {
  48846. switch (this.operator) {
  48847. case ValueCondition.IsGreater:
  48848. return this._effectiveTarget[this._property] > this.value;
  48849. case ValueCondition.IsLesser:
  48850. return this._effectiveTarget[this._property] < this.value;
  48851. case ValueCondition.IsEqual:
  48852. case ValueCondition.IsDifferent:
  48853. var check;
  48854. if (this.value.equals) {
  48855. check = this.value.equals(this._effectiveTarget[this._property]);
  48856. }
  48857. else {
  48858. check = this.value === this._effectiveTarget[this._property];
  48859. }
  48860. return this.operator === ValueCondition.IsEqual ? check : !check;
  48861. }
  48862. return false;
  48863. };
  48864. /**
  48865. * Serialize the ValueCondition into a JSON compatible object
  48866. * @returns serialization object
  48867. */
  48868. ValueCondition.prototype.serialize = function () {
  48869. return this._serialize({
  48870. name: "ValueCondition",
  48871. properties: [
  48872. BABYLON.Action._GetTargetProperty(this._target),
  48873. { name: "propertyPath", value: this.propertyPath },
  48874. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48875. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48876. ]
  48877. });
  48878. };
  48879. /**
  48880. * Gets the name of the conditional operator for the ValueCondition
  48881. * @param operator the conditional operator
  48882. * @returns the name
  48883. */
  48884. ValueCondition.GetOperatorName = function (operator) {
  48885. switch (operator) {
  48886. case ValueCondition._IsEqual: return "IsEqual";
  48887. case ValueCondition._IsDifferent: return "IsDifferent";
  48888. case ValueCondition._IsGreater: return "IsGreater";
  48889. case ValueCondition._IsLesser: return "IsLesser";
  48890. default: return "";
  48891. }
  48892. };
  48893. /**
  48894. * Internal only
  48895. * @ignore
  48896. */
  48897. ValueCondition._IsEqual = 0;
  48898. /**
  48899. * Internal only
  48900. * @ignore
  48901. */
  48902. ValueCondition._IsDifferent = 1;
  48903. /**
  48904. * Internal only
  48905. * @ignore
  48906. */
  48907. ValueCondition._IsGreater = 2;
  48908. /**
  48909. * Internal only
  48910. * @ignore
  48911. */
  48912. ValueCondition._IsLesser = 3;
  48913. return ValueCondition;
  48914. }(Condition));
  48915. BABYLON.ValueCondition = ValueCondition;
  48916. /**
  48917. * Defines a predicate condition as an extension of Condition
  48918. */
  48919. var PredicateCondition = /** @class */ (function (_super) {
  48920. __extends(PredicateCondition, _super);
  48921. /**
  48922. * Creates a new {BABYLON.PredicateCondition}
  48923. * @param actionManager manager for the action the condition applies to
  48924. * @param predicate
  48925. */
  48926. function PredicateCondition(actionManager, predicate) {
  48927. var _this = _super.call(this, actionManager) || this;
  48928. _this.predicate = predicate;
  48929. return _this;
  48930. }
  48931. /**
  48932. * @returns the validity of the predicate condition
  48933. */
  48934. PredicateCondition.prototype.isValid = function () {
  48935. return this.predicate();
  48936. };
  48937. return PredicateCondition;
  48938. }(Condition));
  48939. BABYLON.PredicateCondition = PredicateCondition;
  48940. /**
  48941. * Defines a state condition as an extension of {BABYLON.Condition}
  48942. */
  48943. var StateCondition = /** @class */ (function (_super) {
  48944. __extends(StateCondition, _super);
  48945. /**
  48946. * Creates a new {BABYLON.StateCondition}
  48947. * @param actionManager manager for the action the condition applies to
  48948. * @param target of the condition
  48949. * @param value to compare with target state
  48950. */
  48951. function StateCondition(actionManager, target, value) {
  48952. var _this = _super.call(this, actionManager) || this;
  48953. _this.value = value;
  48954. _this._target = target;
  48955. return _this;
  48956. }
  48957. /**
  48958. * @returns the validity of the state
  48959. */
  48960. StateCondition.prototype.isValid = function () {
  48961. return this._target.state === this.value;
  48962. };
  48963. /**
  48964. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  48965. * @returns serialization object
  48966. */
  48967. StateCondition.prototype.serialize = function () {
  48968. return this._serialize({
  48969. name: "StateCondition",
  48970. properties: [
  48971. BABYLON.Action._GetTargetProperty(this._target),
  48972. { name: "value", value: this.value }
  48973. ]
  48974. });
  48975. };
  48976. return StateCondition;
  48977. }(Condition));
  48978. BABYLON.StateCondition = StateCondition;
  48979. })(BABYLON || (BABYLON = {}));
  48980. //# sourceMappingURL=babylon.condition.js.map
  48981. "use strict";
  48982. var BABYLON;
  48983. (function (BABYLON) {
  48984. /**
  48985. * The action to be carried out following a trigger
  48986. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  48987. */
  48988. var Action = /** @class */ (function () {
  48989. /**
  48990. * Creates a new Action
  48991. * @param triggerOptions the trigger, with or without parameters, for the action
  48992. * @param condition an optional determinant of action
  48993. */
  48994. function Action(triggerOptions, condition) {
  48995. this.triggerOptions = triggerOptions;
  48996. /**
  48997. * An event triggered prior to action being executed.
  48998. */
  48999. this.onBeforeExecuteObservable = new BABYLON.Observable();
  49000. if (triggerOptions.parameter) {
  49001. this.trigger = triggerOptions.trigger;
  49002. this._triggerParameter = triggerOptions.parameter;
  49003. }
  49004. else {
  49005. this.trigger = triggerOptions;
  49006. }
  49007. this._nextActiveAction = this;
  49008. this._condition = condition;
  49009. }
  49010. /**
  49011. * Internal only
  49012. * @ignore
  49013. */
  49014. Action.prototype._prepare = function () {
  49015. };
  49016. /**
  49017. * Gets the trigger parameters
  49018. * @returns the trigger parameters
  49019. */
  49020. Action.prototype.getTriggerParameter = function () {
  49021. return this._triggerParameter;
  49022. };
  49023. /**
  49024. * Internal only - executes current action event
  49025. * @ignore
  49026. */
  49027. Action.prototype._executeCurrent = function (evt) {
  49028. if (this._nextActiveAction._condition) {
  49029. var condition = this._nextActiveAction._condition;
  49030. var currentRenderId = this._actionManager.getScene().getRenderId();
  49031. // We cache the current evaluation for the current frame
  49032. if (condition._evaluationId === currentRenderId) {
  49033. if (!condition._currentResult) {
  49034. return;
  49035. }
  49036. }
  49037. else {
  49038. condition._evaluationId = currentRenderId;
  49039. if (!condition.isValid()) {
  49040. condition._currentResult = false;
  49041. return;
  49042. }
  49043. condition._currentResult = true;
  49044. }
  49045. }
  49046. this.onBeforeExecuteObservable.notifyObservers(this);
  49047. this._nextActiveAction.execute(evt);
  49048. this.skipToNextActiveAction();
  49049. };
  49050. /**
  49051. * Execute placeholder for child classes
  49052. * @param evt optional action event
  49053. */
  49054. Action.prototype.execute = function (evt) {
  49055. };
  49056. /**
  49057. * Skips to next active action
  49058. */
  49059. Action.prototype.skipToNextActiveAction = function () {
  49060. if (this._nextActiveAction._child) {
  49061. if (!this._nextActiveAction._child._actionManager) {
  49062. this._nextActiveAction._child._actionManager = this._actionManager;
  49063. }
  49064. this._nextActiveAction = this._nextActiveAction._child;
  49065. }
  49066. else {
  49067. this._nextActiveAction = this;
  49068. }
  49069. };
  49070. /**
  49071. * Adds action to chain of actions, may be a DoNothingAction
  49072. * @param index The index of the attribute.
  49073. * @returns The action passed in
  49074. * @see https://www.babylonjs-playground.com/#1T30HR#0
  49075. */
  49076. Action.prototype.then = function (action) {
  49077. this._child = action;
  49078. action._actionManager = this._actionManager;
  49079. action._prepare();
  49080. return action;
  49081. };
  49082. /**
  49083. * Internal only
  49084. * @ignore
  49085. */
  49086. Action.prototype._getProperty = function (propertyPath) {
  49087. return this._actionManager._getProperty(propertyPath);
  49088. };
  49089. /**
  49090. * Internal only
  49091. * @ignore
  49092. */
  49093. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49094. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49095. };
  49096. /**
  49097. * Serialize placeholder for child classes
  49098. * @param parent of child
  49099. * @returns the serialized object
  49100. */
  49101. Action.prototype.serialize = function (parent) {
  49102. };
  49103. /**
  49104. * Internal only called by serialize
  49105. * @ignore
  49106. */
  49107. Action.prototype._serialize = function (serializedAction, parent) {
  49108. var serializationObject = {
  49109. type: 1,
  49110. children: [],
  49111. name: serializedAction.name,
  49112. properties: serializedAction.properties || []
  49113. };
  49114. // Serialize child
  49115. if (this._child) {
  49116. this._child.serialize(serializationObject);
  49117. }
  49118. // Check if "this" has a condition
  49119. if (this._condition) {
  49120. var serializedCondition = this._condition.serialize();
  49121. serializedCondition.children.push(serializationObject);
  49122. if (parent) {
  49123. parent.children.push(serializedCondition);
  49124. }
  49125. return serializedCondition;
  49126. }
  49127. if (parent) {
  49128. parent.children.push(serializationObject);
  49129. }
  49130. return serializationObject;
  49131. };
  49132. /**
  49133. * Internal only
  49134. * @ignore
  49135. */
  49136. Action._SerializeValueAsString = function (value) {
  49137. if (typeof value === "number") {
  49138. return value.toString();
  49139. }
  49140. if (typeof value === "boolean") {
  49141. return value ? "true" : "false";
  49142. }
  49143. if (value instanceof BABYLON.Vector2) {
  49144. return value.x + ", " + value.y;
  49145. }
  49146. if (value instanceof BABYLON.Vector3) {
  49147. return value.x + ", " + value.y + ", " + value.z;
  49148. }
  49149. if (value instanceof BABYLON.Color3) {
  49150. return value.r + ", " + value.g + ", " + value.b;
  49151. }
  49152. if (value instanceof BABYLON.Color4) {
  49153. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49154. }
  49155. return value; // string
  49156. };
  49157. /**
  49158. * Internal only
  49159. * @ignore
  49160. */
  49161. Action._GetTargetProperty = function (target) {
  49162. return {
  49163. name: "target",
  49164. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49165. : target instanceof BABYLON.Light ? "LightProperties"
  49166. : target instanceof BABYLON.Camera ? "CameraProperties"
  49167. : "SceneProperties",
  49168. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49169. };
  49170. };
  49171. return Action;
  49172. }());
  49173. BABYLON.Action = Action;
  49174. })(BABYLON || (BABYLON = {}));
  49175. //# sourceMappingURL=babylon.action.js.map
  49176. "use strict";
  49177. var BABYLON;
  49178. (function (BABYLON) {
  49179. /**
  49180. * ActionEvent is the event being sent when an action is triggered.
  49181. */
  49182. var ActionEvent = /** @class */ (function () {
  49183. /**
  49184. * @param source The mesh or sprite that triggered the action.
  49185. * @param pointerX The X mouse cursor position at the time of the event
  49186. * @param pointerY The Y mouse cursor position at the time of the event
  49187. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49188. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49189. */
  49190. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49191. this.source = source;
  49192. this.pointerX = pointerX;
  49193. this.pointerY = pointerY;
  49194. this.meshUnderPointer = meshUnderPointer;
  49195. this.sourceEvent = sourceEvent;
  49196. this.additionalData = additionalData;
  49197. }
  49198. /**
  49199. * Helper function to auto-create an ActionEvent from a source mesh.
  49200. * @param source The source mesh that triggered the event
  49201. * @param evt {Event} The original (browser) event
  49202. */
  49203. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49204. var scene = source.getScene();
  49205. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49206. };
  49207. /**
  49208. * Helper function to auto-create an ActionEvent from a source mesh.
  49209. * @param source The source sprite that triggered the event
  49210. * @param scene Scene associated with the sprite
  49211. * @param evt {Event} The original (browser) event
  49212. */
  49213. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49214. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49215. };
  49216. /**
  49217. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49218. * @param scene the scene where the event occurred
  49219. * @param evt {Event} The original (browser) event
  49220. */
  49221. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49222. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49223. };
  49224. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49225. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49226. };
  49227. return ActionEvent;
  49228. }());
  49229. BABYLON.ActionEvent = ActionEvent;
  49230. /**
  49231. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49232. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49233. */
  49234. var ActionManager = /** @class */ (function () {
  49235. function ActionManager(scene) {
  49236. // Members
  49237. this.actions = new Array();
  49238. this.hoverCursor = '';
  49239. this._scene = scene;
  49240. scene._actionManagers.push(this);
  49241. }
  49242. Object.defineProperty(ActionManager, "NothingTrigger", {
  49243. get: function () {
  49244. return ActionManager._NothingTrigger;
  49245. },
  49246. enumerable: true,
  49247. configurable: true
  49248. });
  49249. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49250. get: function () {
  49251. return ActionManager._OnPickTrigger;
  49252. },
  49253. enumerable: true,
  49254. configurable: true
  49255. });
  49256. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49257. get: function () {
  49258. return ActionManager._OnLeftPickTrigger;
  49259. },
  49260. enumerable: true,
  49261. configurable: true
  49262. });
  49263. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49264. get: function () {
  49265. return ActionManager._OnRightPickTrigger;
  49266. },
  49267. enumerable: true,
  49268. configurable: true
  49269. });
  49270. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49271. get: function () {
  49272. return ActionManager._OnCenterPickTrigger;
  49273. },
  49274. enumerable: true,
  49275. configurable: true
  49276. });
  49277. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49278. get: function () {
  49279. return ActionManager._OnPickDownTrigger;
  49280. },
  49281. enumerable: true,
  49282. configurable: true
  49283. });
  49284. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49285. get: function () {
  49286. return ActionManager._OnDoublePickTrigger;
  49287. },
  49288. enumerable: true,
  49289. configurable: true
  49290. });
  49291. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49292. get: function () {
  49293. return ActionManager._OnPickUpTrigger;
  49294. },
  49295. enumerable: true,
  49296. configurable: true
  49297. });
  49298. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49299. /// This trigger will only be raised if you also declared a OnPickDown
  49300. get: function () {
  49301. return ActionManager._OnPickOutTrigger;
  49302. },
  49303. enumerable: true,
  49304. configurable: true
  49305. });
  49306. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49307. get: function () {
  49308. return ActionManager._OnLongPressTrigger;
  49309. },
  49310. enumerable: true,
  49311. configurable: true
  49312. });
  49313. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49314. get: function () {
  49315. return ActionManager._OnPointerOverTrigger;
  49316. },
  49317. enumerable: true,
  49318. configurable: true
  49319. });
  49320. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49321. get: function () {
  49322. return ActionManager._OnPointerOutTrigger;
  49323. },
  49324. enumerable: true,
  49325. configurable: true
  49326. });
  49327. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49328. get: function () {
  49329. return ActionManager._OnEveryFrameTrigger;
  49330. },
  49331. enumerable: true,
  49332. configurable: true
  49333. });
  49334. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49335. get: function () {
  49336. return ActionManager._OnIntersectionEnterTrigger;
  49337. },
  49338. enumerable: true,
  49339. configurable: true
  49340. });
  49341. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49342. get: function () {
  49343. return ActionManager._OnIntersectionExitTrigger;
  49344. },
  49345. enumerable: true,
  49346. configurable: true
  49347. });
  49348. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49349. get: function () {
  49350. return ActionManager._OnKeyDownTrigger;
  49351. },
  49352. enumerable: true,
  49353. configurable: true
  49354. });
  49355. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49356. get: function () {
  49357. return ActionManager._OnKeyUpTrigger;
  49358. },
  49359. enumerable: true,
  49360. configurable: true
  49361. });
  49362. // Methods
  49363. ActionManager.prototype.dispose = function () {
  49364. var index = this._scene._actionManagers.indexOf(this);
  49365. for (var i = 0; i < this.actions.length; i++) {
  49366. var action = this.actions[i];
  49367. ActionManager.Triggers[action.trigger]--;
  49368. if (ActionManager.Triggers[action.trigger] === 0) {
  49369. delete ActionManager.Triggers[action.trigger];
  49370. }
  49371. }
  49372. if (index > -1) {
  49373. this._scene._actionManagers.splice(index, 1);
  49374. }
  49375. };
  49376. ActionManager.prototype.getScene = function () {
  49377. return this._scene;
  49378. };
  49379. /**
  49380. * Does this action manager handles actions of any of the given triggers
  49381. * @param {number[]} triggers - the triggers to be tested
  49382. * @return {boolean} whether one (or more) of the triggers is handeled
  49383. */
  49384. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49385. for (var index = 0; index < this.actions.length; index++) {
  49386. var action = this.actions[index];
  49387. if (triggers.indexOf(action.trigger) > -1) {
  49388. return true;
  49389. }
  49390. }
  49391. return false;
  49392. };
  49393. /**
  49394. * Does this action manager handles actions of a given trigger
  49395. * @param {number} trigger - the trigger to be tested
  49396. * @return {boolean} whether the trigger is handeled
  49397. */
  49398. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49399. for (var index = 0; index < this.actions.length; index++) {
  49400. var action = this.actions[index];
  49401. if (action.trigger === trigger) {
  49402. return true;
  49403. }
  49404. }
  49405. return false;
  49406. };
  49407. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49408. /**
  49409. * Does this action manager has pointer triggers
  49410. * @return {boolean} whether or not it has pointer triggers
  49411. */
  49412. get: function () {
  49413. for (var index = 0; index < this.actions.length; index++) {
  49414. var action = this.actions[index];
  49415. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49416. return true;
  49417. }
  49418. }
  49419. return false;
  49420. },
  49421. enumerable: true,
  49422. configurable: true
  49423. });
  49424. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49425. /**
  49426. * Does this action manager has pick triggers
  49427. * @return {boolean} whether or not it has pick triggers
  49428. */
  49429. get: function () {
  49430. for (var index = 0; index < this.actions.length; index++) {
  49431. var action = this.actions[index];
  49432. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49433. return true;
  49434. }
  49435. }
  49436. return false;
  49437. },
  49438. enumerable: true,
  49439. configurable: true
  49440. });
  49441. Object.defineProperty(ActionManager, "HasTriggers", {
  49442. /**
  49443. * Does exist one action manager with at least one trigger
  49444. * @return {boolean} whether or not it exists one action manager with one trigger
  49445. **/
  49446. get: function () {
  49447. for (var t in ActionManager.Triggers) {
  49448. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49449. return true;
  49450. }
  49451. }
  49452. return false;
  49453. },
  49454. enumerable: true,
  49455. configurable: true
  49456. });
  49457. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49458. /**
  49459. * Does exist one action manager with at least one pick trigger
  49460. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49461. **/
  49462. get: function () {
  49463. for (var t in ActionManager.Triggers) {
  49464. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49465. var t_int = parseInt(t);
  49466. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49467. return true;
  49468. }
  49469. }
  49470. }
  49471. return false;
  49472. },
  49473. enumerable: true,
  49474. configurable: true
  49475. });
  49476. /**
  49477. * Does exist one action manager that handles actions of a given trigger
  49478. * @param {number} trigger - the trigger to be tested
  49479. * @return {boolean} whether the trigger is handeled by at least one action manager
  49480. **/
  49481. ActionManager.HasSpecificTrigger = function (trigger) {
  49482. for (var t in ActionManager.Triggers) {
  49483. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49484. var t_int = parseInt(t);
  49485. if (t_int === trigger) {
  49486. return true;
  49487. }
  49488. }
  49489. }
  49490. return false;
  49491. };
  49492. /**
  49493. * Registers an action to this action manager
  49494. * @param {BABYLON.Action} action - the action to be registered
  49495. * @return {BABYLON.Action} the action amended (prepared) after registration
  49496. */
  49497. ActionManager.prototype.registerAction = function (action) {
  49498. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49499. if (this.getScene().actionManager !== this) {
  49500. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49501. return null;
  49502. }
  49503. }
  49504. this.actions.push(action);
  49505. if (ActionManager.Triggers[action.trigger]) {
  49506. ActionManager.Triggers[action.trigger]++;
  49507. }
  49508. else {
  49509. ActionManager.Triggers[action.trigger] = 1;
  49510. }
  49511. action._actionManager = this;
  49512. action._prepare();
  49513. return action;
  49514. };
  49515. /**
  49516. * Unregisters an action to this action manager
  49517. * @param action The action to be unregistered
  49518. * @return whether the action has been unregistered
  49519. */
  49520. ActionManager.prototype.unregisterAction = function (action) {
  49521. var index = this.actions.indexOf(action);
  49522. if (index !== -1) {
  49523. this.actions.splice(index, 1);
  49524. ActionManager.Triggers[action.trigger] -= 1;
  49525. if (ActionManager.Triggers[action.trigger] === 0) {
  49526. delete ActionManager.Triggers[action.trigger];
  49527. }
  49528. delete action._actionManager;
  49529. return true;
  49530. }
  49531. return false;
  49532. };
  49533. /**
  49534. * Process a specific trigger
  49535. * @param {number} trigger - the trigger to process
  49536. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49537. */
  49538. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49539. for (var index = 0; index < this.actions.length; index++) {
  49540. var action = this.actions[index];
  49541. if (action.trigger === trigger) {
  49542. if (evt) {
  49543. if (trigger === ActionManager.OnKeyUpTrigger
  49544. || trigger === ActionManager.OnKeyDownTrigger) {
  49545. var parameter = action.getTriggerParameter();
  49546. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49547. if (!parameter.toLowerCase) {
  49548. continue;
  49549. }
  49550. var lowerCase = parameter.toLowerCase();
  49551. if (lowerCase !== evt.sourceEvent.key) {
  49552. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49553. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49554. if (actualkey !== lowerCase) {
  49555. continue;
  49556. }
  49557. }
  49558. }
  49559. }
  49560. }
  49561. action._executeCurrent(evt);
  49562. }
  49563. }
  49564. };
  49565. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49566. var properties = propertyPath.split(".");
  49567. for (var index = 0; index < properties.length - 1; index++) {
  49568. target = target[properties[index]];
  49569. }
  49570. return target;
  49571. };
  49572. ActionManager.prototype._getProperty = function (propertyPath) {
  49573. var properties = propertyPath.split(".");
  49574. return properties[properties.length - 1];
  49575. };
  49576. ActionManager.prototype.serialize = function (name) {
  49577. var root = {
  49578. children: new Array(),
  49579. name: name,
  49580. type: 3,
  49581. properties: new Array() // Empty for root but required
  49582. };
  49583. for (var i = 0; i < this.actions.length; i++) {
  49584. var triggerObject = {
  49585. type: 0,
  49586. children: new Array(),
  49587. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49588. properties: new Array()
  49589. };
  49590. var triggerOptions = this.actions[i].triggerOptions;
  49591. if (triggerOptions && typeof triggerOptions !== "number") {
  49592. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49593. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49594. }
  49595. else {
  49596. var parameter = {};
  49597. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49598. if (triggerOptions.parameter.mesh) {
  49599. parameter._meshId = triggerOptions.parameter.mesh.id;
  49600. }
  49601. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49602. }
  49603. }
  49604. // Serialize child action, recursively
  49605. this.actions[i].serialize(triggerObject);
  49606. // Add serialized trigger
  49607. root.children.push(triggerObject);
  49608. }
  49609. return root;
  49610. };
  49611. ActionManager.Parse = function (parsedActions, object, scene) {
  49612. var actionManager = new ActionManager(scene);
  49613. if (object === null)
  49614. scene.actionManager = actionManager;
  49615. else
  49616. object.actionManager = actionManager;
  49617. // instanciate a new object
  49618. var instanciate = function (name, params) {
  49619. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49620. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49621. newInstance.constructor.apply(newInstance, params);
  49622. return newInstance;
  49623. };
  49624. var parseParameter = function (name, value, target, propertyPath) {
  49625. if (propertyPath === null) {
  49626. // String, boolean or float
  49627. var floatValue = parseFloat(value);
  49628. if (value === "true" || value === "false")
  49629. return value === "true";
  49630. else
  49631. return isNaN(floatValue) ? value : floatValue;
  49632. }
  49633. var effectiveTarget = propertyPath.split(".");
  49634. var values = value.split(",");
  49635. // Get effective Target
  49636. for (var i = 0; i < effectiveTarget.length; i++) {
  49637. target = target[effectiveTarget[i]];
  49638. }
  49639. // Return appropriate value with its type
  49640. if (typeof (target) === "boolean")
  49641. return values[0] === "true";
  49642. if (typeof (target) === "string")
  49643. return values[0];
  49644. // Parameters with multiple values such as Vector3 etc.
  49645. var split = new Array();
  49646. for (var i = 0; i < values.length; i++)
  49647. split.push(parseFloat(values[i]));
  49648. if (target instanceof BABYLON.Vector3)
  49649. return BABYLON.Vector3.FromArray(split);
  49650. if (target instanceof BABYLON.Vector4)
  49651. return BABYLON.Vector4.FromArray(split);
  49652. if (target instanceof BABYLON.Color3)
  49653. return BABYLON.Color3.FromArray(split);
  49654. if (target instanceof BABYLON.Color4)
  49655. return BABYLON.Color4.FromArray(split);
  49656. return parseFloat(values[0]);
  49657. };
  49658. // traverse graph per trigger
  49659. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49660. if (combineArray === void 0) { combineArray = null; }
  49661. if (parsedAction.detached)
  49662. return;
  49663. var parameters = new Array();
  49664. var target = null;
  49665. var propertyPath = null;
  49666. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49667. // Parameters
  49668. if (parsedAction.type === 2)
  49669. parameters.push(actionManager);
  49670. else
  49671. parameters.push(trigger);
  49672. if (combine) {
  49673. var actions = new Array();
  49674. for (var j = 0; j < parsedAction.combine.length; j++) {
  49675. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49676. }
  49677. parameters.push(actions);
  49678. }
  49679. else {
  49680. for (var i = 0; i < parsedAction.properties.length; i++) {
  49681. var value = parsedAction.properties[i].value;
  49682. var name = parsedAction.properties[i].name;
  49683. var targetType = parsedAction.properties[i].targetType;
  49684. if (name === "target")
  49685. if (targetType !== null && targetType === "SceneProperties")
  49686. value = target = scene;
  49687. else
  49688. value = target = scene.getNodeByName(value);
  49689. else if (name === "parent")
  49690. value = scene.getNodeByName(value);
  49691. else if (name === "sound")
  49692. value = scene.getSoundByName(value);
  49693. else if (name !== "propertyPath") {
  49694. if (parsedAction.type === 2 && name === "operator")
  49695. value = BABYLON.ValueCondition[value];
  49696. else
  49697. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49698. }
  49699. else {
  49700. propertyPath = value;
  49701. }
  49702. parameters.push(value);
  49703. }
  49704. }
  49705. if (combineArray === null) {
  49706. parameters.push(condition);
  49707. }
  49708. else {
  49709. parameters.push(null);
  49710. }
  49711. // If interpolate value action
  49712. if (parsedAction.name === "InterpolateValueAction") {
  49713. var param = parameters[parameters.length - 2];
  49714. parameters[parameters.length - 1] = param;
  49715. parameters[parameters.length - 2] = condition;
  49716. }
  49717. // Action or condition(s) and not CombineAction
  49718. var newAction = instanciate(parsedAction.name, parameters);
  49719. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49720. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49721. if (action)
  49722. action.then(nothing);
  49723. else
  49724. actionManager.registerAction(nothing);
  49725. action = nothing;
  49726. }
  49727. if (combineArray === null) {
  49728. if (newAction instanceof BABYLON.Condition) {
  49729. condition = newAction;
  49730. newAction = action;
  49731. }
  49732. else {
  49733. condition = null;
  49734. if (action)
  49735. action.then(newAction);
  49736. else
  49737. actionManager.registerAction(newAction);
  49738. }
  49739. }
  49740. else {
  49741. combineArray.push(newAction);
  49742. }
  49743. for (var i = 0; i < parsedAction.children.length; i++)
  49744. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49745. };
  49746. // triggers
  49747. for (var i = 0; i < parsedActions.children.length; i++) {
  49748. var triggerParams;
  49749. var trigger = parsedActions.children[i];
  49750. if (trigger.properties.length > 0) {
  49751. var param = trigger.properties[0].value;
  49752. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49753. if (value._meshId) {
  49754. value.mesh = scene.getMeshByID(value._meshId);
  49755. }
  49756. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49757. }
  49758. else
  49759. triggerParams = ActionManager[trigger.name];
  49760. for (var j = 0; j < trigger.children.length; j++) {
  49761. if (!trigger.detached)
  49762. traverse(trigger.children[j], triggerParams, null, null);
  49763. }
  49764. }
  49765. };
  49766. ActionManager.GetTriggerName = function (trigger) {
  49767. switch (trigger) {
  49768. case 0: return "NothingTrigger";
  49769. case 1: return "OnPickTrigger";
  49770. case 2: return "OnLeftPickTrigger";
  49771. case 3: return "OnRightPickTrigger";
  49772. case 4: return "OnCenterPickTrigger";
  49773. case 5: return "OnPickDownTrigger";
  49774. case 6: return "OnPickUpTrigger";
  49775. case 7: return "OnLongPressTrigger";
  49776. case 8: return "OnPointerOverTrigger";
  49777. case 9: return "OnPointerOutTrigger";
  49778. case 10: return "OnEveryFrameTrigger";
  49779. case 11: return "OnIntersectionEnterTrigger";
  49780. case 12: return "OnIntersectionExitTrigger";
  49781. case 13: return "OnKeyDownTrigger";
  49782. case 14: return "OnKeyUpTrigger";
  49783. case 15: return "OnPickOutTrigger";
  49784. default: return "";
  49785. }
  49786. };
  49787. // Statics
  49788. ActionManager._NothingTrigger = 0;
  49789. ActionManager._OnPickTrigger = 1;
  49790. ActionManager._OnLeftPickTrigger = 2;
  49791. ActionManager._OnRightPickTrigger = 3;
  49792. ActionManager._OnCenterPickTrigger = 4;
  49793. ActionManager._OnPickDownTrigger = 5;
  49794. ActionManager._OnDoublePickTrigger = 6;
  49795. ActionManager._OnPickUpTrigger = 7;
  49796. ActionManager._OnLongPressTrigger = 8;
  49797. ActionManager._OnPointerOverTrigger = 9;
  49798. ActionManager._OnPointerOutTrigger = 10;
  49799. ActionManager._OnEveryFrameTrigger = 11;
  49800. ActionManager._OnIntersectionEnterTrigger = 12;
  49801. ActionManager._OnIntersectionExitTrigger = 13;
  49802. ActionManager._OnKeyDownTrigger = 14;
  49803. ActionManager._OnKeyUpTrigger = 15;
  49804. ActionManager._OnPickOutTrigger = 16;
  49805. ActionManager.Triggers = {};
  49806. return ActionManager;
  49807. }());
  49808. BABYLON.ActionManager = ActionManager;
  49809. })(BABYLON || (BABYLON = {}));
  49810. //# sourceMappingURL=babylon.actionManager.js.map
  49811. "use strict";
  49812. var BABYLON;
  49813. (function (BABYLON) {
  49814. var InterpolateValueAction = /** @class */ (function (_super) {
  49815. __extends(InterpolateValueAction, _super);
  49816. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49817. if (duration === void 0) { duration = 1000; }
  49818. var _this = _super.call(this, triggerOptions, condition) || this;
  49819. _this.propertyPath = propertyPath;
  49820. _this.value = value;
  49821. _this.duration = duration;
  49822. _this.stopOtherAnimations = stopOtherAnimations;
  49823. _this.onInterpolationDone = onInterpolationDone;
  49824. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49825. _this._target = _this._effectiveTarget = target;
  49826. return _this;
  49827. }
  49828. InterpolateValueAction.prototype._prepare = function () {
  49829. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49830. this._property = this._getProperty(this.propertyPath);
  49831. };
  49832. InterpolateValueAction.prototype.execute = function () {
  49833. var _this = this;
  49834. var scene = this._actionManager.getScene();
  49835. var keys = [
  49836. {
  49837. frame: 0,
  49838. value: this._effectiveTarget[this._property]
  49839. }, {
  49840. frame: 100,
  49841. value: this.value
  49842. }
  49843. ];
  49844. var dataType;
  49845. if (typeof this.value === "number") {
  49846. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49847. }
  49848. else if (this.value instanceof BABYLON.Color3) {
  49849. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49850. }
  49851. else if (this.value instanceof BABYLON.Vector3) {
  49852. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49853. }
  49854. else if (this.value instanceof BABYLON.Matrix) {
  49855. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49856. }
  49857. else if (this.value instanceof BABYLON.Quaternion) {
  49858. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49859. }
  49860. else {
  49861. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49862. return;
  49863. }
  49864. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49865. animation.setKeys(keys);
  49866. if (this.stopOtherAnimations) {
  49867. scene.stopAnimation(this._effectiveTarget);
  49868. }
  49869. var wrapper = function () {
  49870. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49871. if (_this.onInterpolationDone) {
  49872. _this.onInterpolationDone();
  49873. }
  49874. };
  49875. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49876. };
  49877. InterpolateValueAction.prototype.serialize = function (parent) {
  49878. return _super.prototype._serialize.call(this, {
  49879. name: "InterpolateValueAction",
  49880. properties: [
  49881. BABYLON.Action._GetTargetProperty(this._target),
  49882. { name: "propertyPath", value: this.propertyPath },
  49883. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49884. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49885. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49886. ]
  49887. }, parent);
  49888. };
  49889. return InterpolateValueAction;
  49890. }(BABYLON.Action));
  49891. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49892. })(BABYLON || (BABYLON = {}));
  49893. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49894. "use strict";
  49895. var BABYLON;
  49896. (function (BABYLON) {
  49897. var SwitchBooleanAction = /** @class */ (function (_super) {
  49898. __extends(SwitchBooleanAction, _super);
  49899. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49900. var _this = _super.call(this, triggerOptions, condition) || this;
  49901. _this.propertyPath = propertyPath;
  49902. _this._target = _this._effectiveTarget = target;
  49903. return _this;
  49904. }
  49905. SwitchBooleanAction.prototype._prepare = function () {
  49906. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49907. this._property = this._getProperty(this.propertyPath);
  49908. };
  49909. SwitchBooleanAction.prototype.execute = function () {
  49910. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49911. };
  49912. SwitchBooleanAction.prototype.serialize = function (parent) {
  49913. return _super.prototype._serialize.call(this, {
  49914. name: "SwitchBooleanAction",
  49915. properties: [
  49916. BABYLON.Action._GetTargetProperty(this._target),
  49917. { name: "propertyPath", value: this.propertyPath }
  49918. ]
  49919. }, parent);
  49920. };
  49921. return SwitchBooleanAction;
  49922. }(BABYLON.Action));
  49923. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49924. var SetStateAction = /** @class */ (function (_super) {
  49925. __extends(SetStateAction, _super);
  49926. function SetStateAction(triggerOptions, target, value, condition) {
  49927. var _this = _super.call(this, triggerOptions, condition) || this;
  49928. _this.value = value;
  49929. _this._target = target;
  49930. return _this;
  49931. }
  49932. SetStateAction.prototype.execute = function () {
  49933. this._target.state = this.value;
  49934. };
  49935. SetStateAction.prototype.serialize = function (parent) {
  49936. return _super.prototype._serialize.call(this, {
  49937. name: "SetStateAction",
  49938. properties: [
  49939. BABYLON.Action._GetTargetProperty(this._target),
  49940. { name: "value", value: this.value }
  49941. ]
  49942. }, parent);
  49943. };
  49944. return SetStateAction;
  49945. }(BABYLON.Action));
  49946. BABYLON.SetStateAction = SetStateAction;
  49947. var SetValueAction = /** @class */ (function (_super) {
  49948. __extends(SetValueAction, _super);
  49949. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49950. var _this = _super.call(this, triggerOptions, condition) || this;
  49951. _this.propertyPath = propertyPath;
  49952. _this.value = value;
  49953. _this._target = _this._effectiveTarget = target;
  49954. return _this;
  49955. }
  49956. SetValueAction.prototype._prepare = function () {
  49957. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49958. this._property = this._getProperty(this.propertyPath);
  49959. };
  49960. SetValueAction.prototype.execute = function () {
  49961. this._effectiveTarget[this._property] = this.value;
  49962. if (this._target.markAsDirty) {
  49963. this._target.markAsDirty(this._property);
  49964. }
  49965. };
  49966. SetValueAction.prototype.serialize = function (parent) {
  49967. return _super.prototype._serialize.call(this, {
  49968. name: "SetValueAction",
  49969. properties: [
  49970. BABYLON.Action._GetTargetProperty(this._target),
  49971. { name: "propertyPath", value: this.propertyPath },
  49972. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49973. ]
  49974. }, parent);
  49975. };
  49976. return SetValueAction;
  49977. }(BABYLON.Action));
  49978. BABYLON.SetValueAction = SetValueAction;
  49979. var IncrementValueAction = /** @class */ (function (_super) {
  49980. __extends(IncrementValueAction, _super);
  49981. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49982. var _this = _super.call(this, triggerOptions, condition) || this;
  49983. _this.propertyPath = propertyPath;
  49984. _this.value = value;
  49985. _this._target = _this._effectiveTarget = target;
  49986. return _this;
  49987. }
  49988. IncrementValueAction.prototype._prepare = function () {
  49989. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49990. this._property = this._getProperty(this.propertyPath);
  49991. if (typeof this._effectiveTarget[this._property] !== "number") {
  49992. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49993. }
  49994. };
  49995. IncrementValueAction.prototype.execute = function () {
  49996. this._effectiveTarget[this._property] += this.value;
  49997. if (this._target.markAsDirty) {
  49998. this._target.markAsDirty(this._property);
  49999. }
  50000. };
  50001. IncrementValueAction.prototype.serialize = function (parent) {
  50002. return _super.prototype._serialize.call(this, {
  50003. name: "IncrementValueAction",
  50004. properties: [
  50005. BABYLON.Action._GetTargetProperty(this._target),
  50006. { name: "propertyPath", value: this.propertyPath },
  50007. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50008. ]
  50009. }, parent);
  50010. };
  50011. return IncrementValueAction;
  50012. }(BABYLON.Action));
  50013. BABYLON.IncrementValueAction = IncrementValueAction;
  50014. var PlayAnimationAction = /** @class */ (function (_super) {
  50015. __extends(PlayAnimationAction, _super);
  50016. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  50017. var _this = _super.call(this, triggerOptions, condition) || this;
  50018. _this.from = from;
  50019. _this.to = to;
  50020. _this.loop = loop;
  50021. _this._target = target;
  50022. return _this;
  50023. }
  50024. PlayAnimationAction.prototype._prepare = function () {
  50025. };
  50026. PlayAnimationAction.prototype.execute = function () {
  50027. var scene = this._actionManager.getScene();
  50028. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  50029. };
  50030. PlayAnimationAction.prototype.serialize = function (parent) {
  50031. return _super.prototype._serialize.call(this, {
  50032. name: "PlayAnimationAction",
  50033. properties: [
  50034. BABYLON.Action._GetTargetProperty(this._target),
  50035. { name: "from", value: String(this.from) },
  50036. { name: "to", value: String(this.to) },
  50037. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  50038. ]
  50039. }, parent);
  50040. };
  50041. return PlayAnimationAction;
  50042. }(BABYLON.Action));
  50043. BABYLON.PlayAnimationAction = PlayAnimationAction;
  50044. var StopAnimationAction = /** @class */ (function (_super) {
  50045. __extends(StopAnimationAction, _super);
  50046. function StopAnimationAction(triggerOptions, target, condition) {
  50047. var _this = _super.call(this, triggerOptions, condition) || this;
  50048. _this._target = target;
  50049. return _this;
  50050. }
  50051. StopAnimationAction.prototype._prepare = function () {
  50052. };
  50053. StopAnimationAction.prototype.execute = function () {
  50054. var scene = this._actionManager.getScene();
  50055. scene.stopAnimation(this._target);
  50056. };
  50057. StopAnimationAction.prototype.serialize = function (parent) {
  50058. return _super.prototype._serialize.call(this, {
  50059. name: "StopAnimationAction",
  50060. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  50061. }, parent);
  50062. };
  50063. return StopAnimationAction;
  50064. }(BABYLON.Action));
  50065. BABYLON.StopAnimationAction = StopAnimationAction;
  50066. var DoNothingAction = /** @class */ (function (_super) {
  50067. __extends(DoNothingAction, _super);
  50068. function DoNothingAction(triggerOptions, condition) {
  50069. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  50070. return _super.call(this, triggerOptions, condition) || this;
  50071. }
  50072. DoNothingAction.prototype.execute = function () {
  50073. };
  50074. DoNothingAction.prototype.serialize = function (parent) {
  50075. return _super.prototype._serialize.call(this, {
  50076. name: "DoNothingAction",
  50077. properties: []
  50078. }, parent);
  50079. };
  50080. return DoNothingAction;
  50081. }(BABYLON.Action));
  50082. BABYLON.DoNothingAction = DoNothingAction;
  50083. var CombineAction = /** @class */ (function (_super) {
  50084. __extends(CombineAction, _super);
  50085. function CombineAction(triggerOptions, children, condition) {
  50086. var _this = _super.call(this, triggerOptions, condition) || this;
  50087. _this.children = children;
  50088. return _this;
  50089. }
  50090. CombineAction.prototype._prepare = function () {
  50091. for (var index = 0; index < this.children.length; index++) {
  50092. this.children[index]._actionManager = this._actionManager;
  50093. this.children[index]._prepare();
  50094. }
  50095. };
  50096. CombineAction.prototype.execute = function (evt) {
  50097. for (var index = 0; index < this.children.length; index++) {
  50098. this.children[index].execute(evt);
  50099. }
  50100. };
  50101. CombineAction.prototype.serialize = function (parent) {
  50102. var serializationObject = _super.prototype._serialize.call(this, {
  50103. name: "CombineAction",
  50104. properties: [],
  50105. combine: []
  50106. }, parent);
  50107. for (var i = 0; i < this.children.length; i++) {
  50108. serializationObject.combine.push(this.children[i].serialize(null));
  50109. }
  50110. return serializationObject;
  50111. };
  50112. return CombineAction;
  50113. }(BABYLON.Action));
  50114. BABYLON.CombineAction = CombineAction;
  50115. var ExecuteCodeAction = /** @class */ (function (_super) {
  50116. __extends(ExecuteCodeAction, _super);
  50117. function ExecuteCodeAction(triggerOptions, func, condition) {
  50118. var _this = _super.call(this, triggerOptions, condition) || this;
  50119. _this.func = func;
  50120. return _this;
  50121. }
  50122. ExecuteCodeAction.prototype.execute = function (evt) {
  50123. this.func(evt);
  50124. };
  50125. return ExecuteCodeAction;
  50126. }(BABYLON.Action));
  50127. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50128. var SetParentAction = /** @class */ (function (_super) {
  50129. __extends(SetParentAction, _super);
  50130. function SetParentAction(triggerOptions, target, parent, condition) {
  50131. var _this = _super.call(this, triggerOptions, condition) || this;
  50132. _this._target = target;
  50133. _this._parent = parent;
  50134. return _this;
  50135. }
  50136. SetParentAction.prototype._prepare = function () {
  50137. };
  50138. SetParentAction.prototype.execute = function () {
  50139. if (this._target.parent === this._parent) {
  50140. return;
  50141. }
  50142. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50143. invertParentWorldMatrix.invert();
  50144. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50145. this._target.parent = this._parent;
  50146. };
  50147. SetParentAction.prototype.serialize = function (parent) {
  50148. return _super.prototype._serialize.call(this, {
  50149. name: "SetParentAction",
  50150. properties: [
  50151. BABYLON.Action._GetTargetProperty(this._target),
  50152. BABYLON.Action._GetTargetProperty(this._parent),
  50153. ]
  50154. }, parent);
  50155. };
  50156. return SetParentAction;
  50157. }(BABYLON.Action));
  50158. BABYLON.SetParentAction = SetParentAction;
  50159. var PlaySoundAction = /** @class */ (function (_super) {
  50160. __extends(PlaySoundAction, _super);
  50161. function PlaySoundAction(triggerOptions, sound, condition) {
  50162. var _this = _super.call(this, triggerOptions, condition) || this;
  50163. _this._sound = sound;
  50164. return _this;
  50165. }
  50166. PlaySoundAction.prototype._prepare = function () {
  50167. };
  50168. PlaySoundAction.prototype.execute = function () {
  50169. if (this._sound !== undefined)
  50170. this._sound.play();
  50171. };
  50172. PlaySoundAction.prototype.serialize = function (parent) {
  50173. return _super.prototype._serialize.call(this, {
  50174. name: "PlaySoundAction",
  50175. properties: [{ name: "sound", value: this._sound.name }]
  50176. }, parent);
  50177. };
  50178. return PlaySoundAction;
  50179. }(BABYLON.Action));
  50180. BABYLON.PlaySoundAction = PlaySoundAction;
  50181. var StopSoundAction = /** @class */ (function (_super) {
  50182. __extends(StopSoundAction, _super);
  50183. function StopSoundAction(triggerOptions, sound, condition) {
  50184. var _this = _super.call(this, triggerOptions, condition) || this;
  50185. _this._sound = sound;
  50186. return _this;
  50187. }
  50188. StopSoundAction.prototype._prepare = function () {
  50189. };
  50190. StopSoundAction.prototype.execute = function () {
  50191. if (this._sound !== undefined)
  50192. this._sound.stop();
  50193. };
  50194. StopSoundAction.prototype.serialize = function (parent) {
  50195. return _super.prototype._serialize.call(this, {
  50196. name: "StopSoundAction",
  50197. properties: [{ name: "sound", value: this._sound.name }]
  50198. }, parent);
  50199. };
  50200. return StopSoundAction;
  50201. }(BABYLON.Action));
  50202. BABYLON.StopSoundAction = StopSoundAction;
  50203. })(BABYLON || (BABYLON = {}));
  50204. //# sourceMappingURL=babylon.directActions.js.map
  50205. "use strict";
  50206. var BABYLON;
  50207. (function (BABYLON) {
  50208. var SpriteManager = /** @class */ (function () {
  50209. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50210. if (epsilon === void 0) { epsilon = 0.01; }
  50211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50212. this.name = name;
  50213. this.sprites = new Array();
  50214. this.renderingGroupId = 0;
  50215. this.layerMask = 0x0FFFFFFF;
  50216. this.fogEnabled = true;
  50217. this.isPickable = false;
  50218. /**
  50219. * An event triggered when the manager is disposed.
  50220. */
  50221. this.onDisposeObservable = new BABYLON.Observable();
  50222. this._vertexBuffers = {};
  50223. this._capacity = capacity;
  50224. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50225. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50226. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50227. if (cellSize.width && cellSize.height) {
  50228. this.cellWidth = cellSize.width;
  50229. this.cellHeight = cellSize.height;
  50230. }
  50231. else if (cellSize !== undefined) {
  50232. this.cellWidth = cellSize;
  50233. this.cellHeight = cellSize;
  50234. }
  50235. else {
  50236. return;
  50237. }
  50238. this._epsilon = epsilon;
  50239. this._scene = scene;
  50240. this._scene.spriteManagers.push(this);
  50241. var indices = [];
  50242. var index = 0;
  50243. for (var count = 0; count < capacity; count++) {
  50244. indices.push(index);
  50245. indices.push(index + 1);
  50246. indices.push(index + 2);
  50247. indices.push(index);
  50248. indices.push(index + 2);
  50249. indices.push(index + 3);
  50250. index += 4;
  50251. }
  50252. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50253. // VBO
  50254. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50255. this._vertexData = new Float32Array(capacity * 16 * 4);
  50256. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50257. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50258. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50259. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50260. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50261. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50262. this._vertexBuffers["options"] = options;
  50263. this._vertexBuffers["cellInfo"] = cellInfo;
  50264. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50265. // Effects
  50266. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50267. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50268. }
  50269. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50270. set: function (callback) {
  50271. if (this._onDisposeObserver) {
  50272. this.onDisposeObservable.remove(this._onDisposeObserver);
  50273. }
  50274. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50275. },
  50276. enumerable: true,
  50277. configurable: true
  50278. });
  50279. Object.defineProperty(SpriteManager.prototype, "texture", {
  50280. get: function () {
  50281. return this._spriteTexture;
  50282. },
  50283. set: function (value) {
  50284. this._spriteTexture = value;
  50285. },
  50286. enumerable: true,
  50287. configurable: true
  50288. });
  50289. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50290. var arrayOffset = index * 16;
  50291. if (offsetX === 0)
  50292. offsetX = this._epsilon;
  50293. else if (offsetX === 1)
  50294. offsetX = 1 - this._epsilon;
  50295. if (offsetY === 0)
  50296. offsetY = this._epsilon;
  50297. else if (offsetY === 1)
  50298. offsetY = 1 - this._epsilon;
  50299. this._vertexData[arrayOffset] = sprite.position.x;
  50300. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50301. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50302. this._vertexData[arrayOffset + 3] = sprite.angle;
  50303. this._vertexData[arrayOffset + 4] = sprite.width;
  50304. this._vertexData[arrayOffset + 5] = sprite.height;
  50305. this._vertexData[arrayOffset + 6] = offsetX;
  50306. this._vertexData[arrayOffset + 7] = offsetY;
  50307. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50308. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50309. var offset = (sprite.cellIndex / rowSize) >> 0;
  50310. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50311. this._vertexData[arrayOffset + 11] = offset;
  50312. // Color
  50313. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50314. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50315. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50316. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50317. };
  50318. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50319. var count = Math.min(this._capacity, this.sprites.length);
  50320. var min = BABYLON.Vector3.Zero();
  50321. var max = BABYLON.Vector3.Zero();
  50322. var distance = Number.MAX_VALUE;
  50323. var currentSprite = null;
  50324. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50325. var cameraView = camera.getViewMatrix();
  50326. for (var index = 0; index < count; index++) {
  50327. var sprite = this.sprites[index];
  50328. if (!sprite) {
  50329. continue;
  50330. }
  50331. if (predicate) {
  50332. if (!predicate(sprite)) {
  50333. continue;
  50334. }
  50335. }
  50336. else if (!sprite.isPickable) {
  50337. continue;
  50338. }
  50339. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50340. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50341. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50342. if (ray.intersectsBoxMinMax(min, max)) {
  50343. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50344. if (distance > currentDistance) {
  50345. distance = currentDistance;
  50346. currentSprite = sprite;
  50347. if (fastCheck) {
  50348. break;
  50349. }
  50350. }
  50351. }
  50352. }
  50353. if (currentSprite) {
  50354. var result = new BABYLON.PickingInfo();
  50355. result.hit = true;
  50356. result.pickedSprite = currentSprite;
  50357. result.distance = distance;
  50358. return result;
  50359. }
  50360. return null;
  50361. };
  50362. SpriteManager.prototype.render = function () {
  50363. // Check
  50364. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50365. return;
  50366. var engine = this._scene.getEngine();
  50367. var baseSize = this._spriteTexture.getBaseSize();
  50368. // Sprites
  50369. var deltaTime = engine.getDeltaTime();
  50370. var max = Math.min(this._capacity, this.sprites.length);
  50371. var rowSize = baseSize.width / this.cellWidth;
  50372. var offset = 0;
  50373. for (var index = 0; index < max; index++) {
  50374. var sprite = this.sprites[index];
  50375. if (!sprite) {
  50376. continue;
  50377. }
  50378. sprite._animate(deltaTime);
  50379. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50380. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50381. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50382. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50383. }
  50384. this._buffer.update(this._vertexData);
  50385. // Render
  50386. var effect = this._effectBase;
  50387. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50388. effect = this._effectFog;
  50389. }
  50390. engine.enableEffect(effect);
  50391. var viewMatrix = this._scene.getViewMatrix();
  50392. effect.setTexture("diffuseSampler", this._spriteTexture);
  50393. effect.setMatrix("view", viewMatrix);
  50394. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50395. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50396. // Fog
  50397. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50398. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50399. effect.setColor3("vFogColor", this._scene.fogColor);
  50400. }
  50401. // VBOs
  50402. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50403. // Draw order
  50404. engine.setDepthFunctionToLessOrEqual();
  50405. effect.setBool("alphaTest", true);
  50406. engine.setColorWrite(false);
  50407. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50408. engine.setColorWrite(true);
  50409. effect.setBool("alphaTest", false);
  50410. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50411. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50412. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50413. };
  50414. SpriteManager.prototype.dispose = function () {
  50415. if (this._buffer) {
  50416. this._buffer.dispose();
  50417. this._buffer = null;
  50418. }
  50419. if (this._indexBuffer) {
  50420. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50421. this._indexBuffer = null;
  50422. }
  50423. if (this._spriteTexture) {
  50424. this._spriteTexture.dispose();
  50425. this._spriteTexture = null;
  50426. }
  50427. // Remove from scene
  50428. var index = this._scene.spriteManagers.indexOf(this);
  50429. this._scene.spriteManagers.splice(index, 1);
  50430. // Callback
  50431. this.onDisposeObservable.notifyObservers(this);
  50432. this.onDisposeObservable.clear();
  50433. };
  50434. return SpriteManager;
  50435. }());
  50436. BABYLON.SpriteManager = SpriteManager;
  50437. })(BABYLON || (BABYLON = {}));
  50438. //# sourceMappingURL=babylon.spriteManager.js.map
  50439. "use strict";
  50440. var BABYLON;
  50441. (function (BABYLON) {
  50442. var Sprite = /** @class */ (function () {
  50443. function Sprite(name, manager) {
  50444. this.name = name;
  50445. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50446. this.width = 1.0;
  50447. this.height = 1.0;
  50448. this.angle = 0;
  50449. this.cellIndex = 0;
  50450. this.invertU = 0;
  50451. this.invertV = 0;
  50452. this.animations = new Array();
  50453. this.isPickable = false;
  50454. this._animationStarted = false;
  50455. this._loopAnimation = false;
  50456. this._fromIndex = 0;
  50457. this._toIndex = 0;
  50458. this._delay = 0;
  50459. this._direction = 1;
  50460. this._time = 0;
  50461. this._manager = manager;
  50462. this._manager.sprites.push(this);
  50463. this.position = BABYLON.Vector3.Zero();
  50464. }
  50465. Object.defineProperty(Sprite.prototype, "size", {
  50466. get: function () {
  50467. return this.width;
  50468. },
  50469. set: function (value) {
  50470. this.width = value;
  50471. this.height = value;
  50472. },
  50473. enumerable: true,
  50474. configurable: true
  50475. });
  50476. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50477. this._fromIndex = from;
  50478. this._toIndex = to;
  50479. this._loopAnimation = loop;
  50480. this._delay = delay;
  50481. this._animationStarted = true;
  50482. this._direction = from < to ? 1 : -1;
  50483. this.cellIndex = from;
  50484. this._time = 0;
  50485. this._onAnimationEnd = onAnimationEnd;
  50486. };
  50487. Sprite.prototype.stopAnimation = function () {
  50488. this._animationStarted = false;
  50489. };
  50490. Sprite.prototype._animate = function (deltaTime) {
  50491. if (!this._animationStarted)
  50492. return;
  50493. this._time += deltaTime;
  50494. if (this._time > this._delay) {
  50495. this._time = this._time % this._delay;
  50496. this.cellIndex += this._direction;
  50497. if (this.cellIndex > this._toIndex) {
  50498. if (this._loopAnimation) {
  50499. this.cellIndex = this._fromIndex;
  50500. }
  50501. else {
  50502. this.cellIndex = this._toIndex;
  50503. this._animationStarted = false;
  50504. if (this._onAnimationEnd) {
  50505. this._onAnimationEnd();
  50506. }
  50507. if (this.disposeWhenFinishedAnimating) {
  50508. this.dispose();
  50509. }
  50510. }
  50511. }
  50512. }
  50513. };
  50514. Sprite.prototype.dispose = function () {
  50515. for (var i = 0; i < this._manager.sprites.length; i++) {
  50516. if (this._manager.sprites[i] == this) {
  50517. this._manager.sprites.splice(i, 1);
  50518. }
  50519. }
  50520. };
  50521. return Sprite;
  50522. }());
  50523. BABYLON.Sprite = Sprite;
  50524. })(BABYLON || (BABYLON = {}));
  50525. //# sourceMappingURL=babylon.sprite.js.map
  50526. "use strict";
  50527. var BABYLON;
  50528. (function (BABYLON) {
  50529. var IntersectionInfo = /** @class */ (function () {
  50530. function IntersectionInfo(bu, bv, distance) {
  50531. this.bu = bu;
  50532. this.bv = bv;
  50533. this.distance = distance;
  50534. this.faceId = 0;
  50535. this.subMeshId = 0;
  50536. }
  50537. return IntersectionInfo;
  50538. }());
  50539. BABYLON.IntersectionInfo = IntersectionInfo;
  50540. var PickingInfo = /** @class */ (function () {
  50541. function PickingInfo() {
  50542. this.hit = false;
  50543. this.distance = 0;
  50544. this.pickedPoint = null;
  50545. this.pickedMesh = null;
  50546. this.bu = 0;
  50547. this.bv = 0;
  50548. this.faceId = -1;
  50549. this.subMeshId = 0;
  50550. this.pickedSprite = null;
  50551. }
  50552. // Methods
  50553. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50554. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50555. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50556. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50557. return null;
  50558. }
  50559. var indices = this.pickedMesh.getIndices();
  50560. if (!indices) {
  50561. return null;
  50562. }
  50563. var result;
  50564. if (useVerticesNormals) {
  50565. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50566. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50567. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50568. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50569. normal0 = normal0.scale(this.bu);
  50570. normal1 = normal1.scale(this.bv);
  50571. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50572. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50573. }
  50574. else {
  50575. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50576. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50577. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50578. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50579. var p1p2 = vertex1.subtract(vertex2);
  50580. var p3p2 = vertex3.subtract(vertex2);
  50581. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50582. }
  50583. if (useWorldCoordinates) {
  50584. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50585. }
  50586. return BABYLON.Vector3.Normalize(result);
  50587. };
  50588. PickingInfo.prototype.getTextureCoordinates = function () {
  50589. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50590. return null;
  50591. }
  50592. var indices = this.pickedMesh.getIndices();
  50593. if (!indices) {
  50594. return null;
  50595. }
  50596. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50597. if (!uvs) {
  50598. return null;
  50599. }
  50600. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50601. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50602. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50603. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50604. uv1 = uv1.scale(this.bu);
  50605. uv2 = uv2.scale(this.bv);
  50606. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50607. };
  50608. return PickingInfo;
  50609. }());
  50610. BABYLON.PickingInfo = PickingInfo;
  50611. })(BABYLON || (BABYLON = {}));
  50612. //# sourceMappingURL=babylon.pickingInfo.js.map
  50613. "use strict";
  50614. var BABYLON;
  50615. (function (BABYLON) {
  50616. var Ray = /** @class */ (function () {
  50617. function Ray(origin, direction, length) {
  50618. if (length === void 0) { length = Number.MAX_VALUE; }
  50619. this.origin = origin;
  50620. this.direction = direction;
  50621. this.length = length;
  50622. }
  50623. // Methods
  50624. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50625. var d = 0.0;
  50626. var maxValue = Number.MAX_VALUE;
  50627. var inv;
  50628. var min;
  50629. var max;
  50630. var temp;
  50631. if (Math.abs(this.direction.x) < 0.0000001) {
  50632. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50633. return false;
  50634. }
  50635. }
  50636. else {
  50637. inv = 1.0 / this.direction.x;
  50638. min = (minimum.x - this.origin.x) * inv;
  50639. max = (maximum.x - this.origin.x) * inv;
  50640. if (max === -Infinity) {
  50641. max = Infinity;
  50642. }
  50643. if (min > max) {
  50644. temp = min;
  50645. min = max;
  50646. max = temp;
  50647. }
  50648. d = Math.max(min, d);
  50649. maxValue = Math.min(max, maxValue);
  50650. if (d > maxValue) {
  50651. return false;
  50652. }
  50653. }
  50654. if (Math.abs(this.direction.y) < 0.0000001) {
  50655. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50656. return false;
  50657. }
  50658. }
  50659. else {
  50660. inv = 1.0 / this.direction.y;
  50661. min = (minimum.y - this.origin.y) * inv;
  50662. max = (maximum.y - this.origin.y) * inv;
  50663. if (max === -Infinity) {
  50664. max = Infinity;
  50665. }
  50666. if (min > max) {
  50667. temp = min;
  50668. min = max;
  50669. max = temp;
  50670. }
  50671. d = Math.max(min, d);
  50672. maxValue = Math.min(max, maxValue);
  50673. if (d > maxValue) {
  50674. return false;
  50675. }
  50676. }
  50677. if (Math.abs(this.direction.z) < 0.0000001) {
  50678. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50679. return false;
  50680. }
  50681. }
  50682. else {
  50683. inv = 1.0 / this.direction.z;
  50684. min = (minimum.z - this.origin.z) * inv;
  50685. max = (maximum.z - this.origin.z) * inv;
  50686. if (max === -Infinity) {
  50687. max = Infinity;
  50688. }
  50689. if (min > max) {
  50690. temp = min;
  50691. min = max;
  50692. max = temp;
  50693. }
  50694. d = Math.max(min, d);
  50695. maxValue = Math.min(max, maxValue);
  50696. if (d > maxValue) {
  50697. return false;
  50698. }
  50699. }
  50700. return true;
  50701. };
  50702. Ray.prototype.intersectsBox = function (box) {
  50703. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50704. };
  50705. Ray.prototype.intersectsSphere = function (sphere) {
  50706. var x = sphere.center.x - this.origin.x;
  50707. var y = sphere.center.y - this.origin.y;
  50708. var z = sphere.center.z - this.origin.z;
  50709. var pyth = (x * x) + (y * y) + (z * z);
  50710. var rr = sphere.radius * sphere.radius;
  50711. if (pyth <= rr) {
  50712. return true;
  50713. }
  50714. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50715. if (dot < 0.0) {
  50716. return false;
  50717. }
  50718. var temp = pyth - (dot * dot);
  50719. return temp <= rr;
  50720. };
  50721. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50722. if (!this._edge1) {
  50723. this._edge1 = BABYLON.Vector3.Zero();
  50724. this._edge2 = BABYLON.Vector3.Zero();
  50725. this._pvec = BABYLON.Vector3.Zero();
  50726. this._tvec = BABYLON.Vector3.Zero();
  50727. this._qvec = BABYLON.Vector3.Zero();
  50728. }
  50729. vertex1.subtractToRef(vertex0, this._edge1);
  50730. vertex2.subtractToRef(vertex0, this._edge2);
  50731. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50732. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50733. if (det === 0) {
  50734. return null;
  50735. }
  50736. var invdet = 1 / det;
  50737. this.origin.subtractToRef(vertex0, this._tvec);
  50738. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50739. if (bu < 0 || bu > 1.0) {
  50740. return null;
  50741. }
  50742. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50743. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50744. if (bv < 0 || bu + bv > 1.0) {
  50745. return null;
  50746. }
  50747. //check if the distance is longer than the predefined length.
  50748. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50749. if (distance > this.length) {
  50750. return null;
  50751. }
  50752. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50753. };
  50754. Ray.prototype.intersectsPlane = function (plane) {
  50755. var distance;
  50756. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50757. if (Math.abs(result1) < 9.99999997475243E-07) {
  50758. return null;
  50759. }
  50760. else {
  50761. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50762. distance = (-plane.d - result2) / result1;
  50763. if (distance < 0.0) {
  50764. if (distance < -9.99999997475243E-07) {
  50765. return null;
  50766. }
  50767. else {
  50768. return 0;
  50769. }
  50770. }
  50771. return distance;
  50772. }
  50773. };
  50774. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50775. var tm = BABYLON.Tmp.Matrix[0];
  50776. mesh.getWorldMatrix().invertToRef(tm);
  50777. if (this._tmpRay) {
  50778. Ray.TransformToRef(this, tm, this._tmpRay);
  50779. }
  50780. else {
  50781. this._tmpRay = Ray.Transform(this, tm);
  50782. }
  50783. return mesh.intersects(this._tmpRay, fastCheck);
  50784. };
  50785. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50786. if (results) {
  50787. results.length = 0;
  50788. }
  50789. else {
  50790. results = [];
  50791. }
  50792. for (var i = 0; i < meshes.length; i++) {
  50793. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50794. if (pickInfo.hit) {
  50795. results.push(pickInfo);
  50796. }
  50797. }
  50798. results.sort(this._comparePickingInfo);
  50799. return results;
  50800. };
  50801. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50802. if (pickingInfoA.distance < pickingInfoB.distance) {
  50803. return -1;
  50804. }
  50805. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50806. return 1;
  50807. }
  50808. else {
  50809. return 0;
  50810. }
  50811. };
  50812. /**
  50813. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50814. * @param sega the first point of the segment to test the intersection against
  50815. * @param segb the second point of the segment to test the intersection against
  50816. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50817. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50818. */
  50819. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50820. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50821. var u = segb.subtract(sega);
  50822. var v = rsegb.subtract(this.origin);
  50823. var w = sega.subtract(this.origin);
  50824. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50825. var b = BABYLON.Vector3.Dot(u, v);
  50826. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50827. var d = BABYLON.Vector3.Dot(u, w);
  50828. var e = BABYLON.Vector3.Dot(v, w);
  50829. var D = a * c - b * b; // always >= 0
  50830. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50831. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50832. // compute the line parameters of the two closest points
  50833. if (D < Ray.smallnum) {
  50834. sN = 0.0; // force using point P0 on segment S1
  50835. sD = 1.0; // to prevent possible division by 0.0 later
  50836. tN = e;
  50837. tD = c;
  50838. }
  50839. else {
  50840. sN = (b * e - c * d);
  50841. tN = (a * e - b * d);
  50842. if (sN < 0.0) {
  50843. sN = 0.0;
  50844. tN = e;
  50845. tD = c;
  50846. }
  50847. else if (sN > sD) {
  50848. sN = sD;
  50849. tN = e + b;
  50850. tD = c;
  50851. }
  50852. }
  50853. if (tN < 0.0) {
  50854. tN = 0.0;
  50855. // recompute sc for this edge
  50856. if (-d < 0.0) {
  50857. sN = 0.0;
  50858. }
  50859. else if (-d > a)
  50860. sN = sD;
  50861. else {
  50862. sN = -d;
  50863. sD = a;
  50864. }
  50865. }
  50866. else if (tN > tD) {
  50867. tN = tD;
  50868. // recompute sc for this edge
  50869. if ((-d + b) < 0.0) {
  50870. sN = 0;
  50871. }
  50872. else if ((-d + b) > a) {
  50873. sN = sD;
  50874. }
  50875. else {
  50876. sN = (-d + b);
  50877. sD = a;
  50878. }
  50879. }
  50880. // finally do the division to get sc and tc
  50881. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50882. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50883. // get the difference of the two closest points
  50884. var qtc = v.multiplyByFloats(tc, tc, tc);
  50885. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50886. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50887. if (isIntersected) {
  50888. return qtc.length();
  50889. }
  50890. return -1;
  50891. };
  50892. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50893. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50894. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50895. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50896. this.direction.normalize();
  50897. return this;
  50898. };
  50899. // Statics
  50900. Ray.Zero = function () {
  50901. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50902. };
  50903. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50904. var result = Ray.Zero();
  50905. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50906. };
  50907. /**
  50908. * 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
  50909. * transformed to the given world matrix.
  50910. * @param origin The origin point
  50911. * @param end The end point
  50912. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50913. */
  50914. Ray.CreateNewFromTo = function (origin, end, world) {
  50915. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50916. var direction = end.subtract(origin);
  50917. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50918. direction.normalize();
  50919. return Ray.Transform(new Ray(origin, direction, length), world);
  50920. };
  50921. Ray.Transform = function (ray, matrix) {
  50922. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50923. Ray.TransformToRef(ray, matrix, result);
  50924. return result;
  50925. };
  50926. Ray.TransformToRef = function (ray, matrix, result) {
  50927. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50928. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50929. result.length = ray.length;
  50930. var dir = result.direction;
  50931. var len = dir.length();
  50932. if (!(len === 0 || len === 1)) {
  50933. var num = 1.0 / len;
  50934. dir.x *= num;
  50935. dir.y *= num;
  50936. dir.z *= num;
  50937. result.length *= len;
  50938. }
  50939. };
  50940. Ray.smallnum = 0.00000001;
  50941. Ray.rayl = 10e8;
  50942. return Ray;
  50943. }());
  50944. BABYLON.Ray = Ray;
  50945. })(BABYLON || (BABYLON = {}));
  50946. //# sourceMappingURL=babylon.ray.js.map
  50947. "use strict";
  50948. var BABYLON;
  50949. (function (BABYLON) {
  50950. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50951. if (boxMin.x > sphereCenter.x + sphereRadius)
  50952. return false;
  50953. if (sphereCenter.x - sphereRadius > boxMax.x)
  50954. return false;
  50955. if (boxMin.y > sphereCenter.y + sphereRadius)
  50956. return false;
  50957. if (sphereCenter.y - sphereRadius > boxMax.y)
  50958. return false;
  50959. if (boxMin.z > sphereCenter.z + sphereRadius)
  50960. return false;
  50961. if (sphereCenter.z - sphereRadius > boxMax.z)
  50962. return false;
  50963. return true;
  50964. };
  50965. var getLowestRoot = (function () {
  50966. var result = { root: 0, found: false };
  50967. return function (a, b, c, maxR) {
  50968. result.root = 0;
  50969. result.found = false;
  50970. var determinant = b * b - 4.0 * a * c;
  50971. if (determinant < 0)
  50972. return result;
  50973. var sqrtD = Math.sqrt(determinant);
  50974. var r1 = (-b - sqrtD) / (2.0 * a);
  50975. var r2 = (-b + sqrtD) / (2.0 * a);
  50976. if (r1 > r2) {
  50977. var temp = r2;
  50978. r2 = r1;
  50979. r1 = temp;
  50980. }
  50981. if (r1 > 0 && r1 < maxR) {
  50982. result.root = r1;
  50983. result.found = true;
  50984. return result;
  50985. }
  50986. if (r2 > 0 && r2 < maxR) {
  50987. result.root = r2;
  50988. result.found = true;
  50989. return result;
  50990. }
  50991. return result;
  50992. };
  50993. })();
  50994. var Collider = /** @class */ (function () {
  50995. function Collider() {
  50996. this._collisionPoint = BABYLON.Vector3.Zero();
  50997. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50998. this._tempVector = BABYLON.Vector3.Zero();
  50999. this._tempVector2 = BABYLON.Vector3.Zero();
  51000. this._tempVector3 = BABYLON.Vector3.Zero();
  51001. this._tempVector4 = BABYLON.Vector3.Zero();
  51002. this._edge = BABYLON.Vector3.Zero();
  51003. this._baseToVertex = BABYLON.Vector3.Zero();
  51004. this._destinationPoint = BABYLON.Vector3.Zero();
  51005. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  51006. this._displacementVector = BABYLON.Vector3.Zero();
  51007. this._radius = BABYLON.Vector3.One();
  51008. this._retry = 0;
  51009. this._basePointWorld = BABYLON.Vector3.Zero();
  51010. this._velocityWorld = BABYLON.Vector3.Zero();
  51011. this._normalizedVelocity = BABYLON.Vector3.Zero();
  51012. this._collisionMask = -1;
  51013. }
  51014. Object.defineProperty(Collider.prototype, "collisionMask", {
  51015. get: function () {
  51016. return this._collisionMask;
  51017. },
  51018. set: function (mask) {
  51019. this._collisionMask = !isNaN(mask) ? mask : -1;
  51020. },
  51021. enumerable: true,
  51022. configurable: true
  51023. });
  51024. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  51025. /**
  51026. * Gets the plane normal used to compute the sliding response (in local space)
  51027. */
  51028. get: function () {
  51029. return this._slidePlaneNormal;
  51030. },
  51031. enumerable: true,
  51032. configurable: true
  51033. });
  51034. // Methods
  51035. Collider.prototype._initialize = function (source, dir, e) {
  51036. this._velocity = dir;
  51037. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  51038. this._basePoint = source;
  51039. source.multiplyToRef(this._radius, this._basePointWorld);
  51040. dir.multiplyToRef(this._radius, this._velocityWorld);
  51041. this._velocityWorldLength = this._velocityWorld.length();
  51042. this._epsilon = e;
  51043. this.collisionFound = false;
  51044. };
  51045. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  51046. pa.subtractToRef(point, this._tempVector);
  51047. pb.subtractToRef(point, this._tempVector2);
  51048. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  51049. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51050. if (d < 0)
  51051. return false;
  51052. pc.subtractToRef(point, this._tempVector3);
  51053. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  51054. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51055. if (d < 0)
  51056. return false;
  51057. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  51058. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51059. return d >= 0;
  51060. };
  51061. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  51062. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  51063. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  51064. if (distance > this._velocityWorldLength + max + sphereRadius) {
  51065. return false;
  51066. }
  51067. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  51068. return false;
  51069. return true;
  51070. };
  51071. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  51072. var t0;
  51073. var embeddedInPlane = false;
  51074. //defensive programming, actually not needed.
  51075. if (!trianglePlaneArray) {
  51076. trianglePlaneArray = [];
  51077. }
  51078. if (!trianglePlaneArray[faceIndex]) {
  51079. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  51080. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  51081. }
  51082. var trianglePlane = trianglePlaneArray[faceIndex];
  51083. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  51084. return;
  51085. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  51086. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51087. if (normalDotVelocity == 0) {
  51088. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51089. return;
  51090. embeddedInPlane = true;
  51091. t0 = 0;
  51092. }
  51093. else {
  51094. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51095. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51096. if (t0 > t1) {
  51097. var temp = t1;
  51098. t1 = t0;
  51099. t0 = temp;
  51100. }
  51101. if (t0 > 1.0 || t1 < 0.0)
  51102. return;
  51103. if (t0 < 0)
  51104. t0 = 0;
  51105. if (t0 > 1.0)
  51106. t0 = 1.0;
  51107. }
  51108. this._collisionPoint.copyFromFloats(0, 0, 0);
  51109. var found = false;
  51110. var t = 1.0;
  51111. if (!embeddedInPlane) {
  51112. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51113. this._velocity.scaleToRef(t0, this._tempVector);
  51114. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51115. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51116. found = true;
  51117. t = t0;
  51118. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51119. }
  51120. }
  51121. if (!found) {
  51122. var velocitySquaredLength = this._velocity.lengthSquared();
  51123. var a = velocitySquaredLength;
  51124. this._basePoint.subtractToRef(p1, this._tempVector);
  51125. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51126. var c = this._tempVector.lengthSquared() - 1.0;
  51127. var lowestRoot = getLowestRoot(a, b, c, t);
  51128. if (lowestRoot.found) {
  51129. t = lowestRoot.root;
  51130. found = true;
  51131. this._collisionPoint.copyFrom(p1);
  51132. }
  51133. this._basePoint.subtractToRef(p2, this._tempVector);
  51134. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51135. c = this._tempVector.lengthSquared() - 1.0;
  51136. lowestRoot = getLowestRoot(a, b, c, t);
  51137. if (lowestRoot.found) {
  51138. t = lowestRoot.root;
  51139. found = true;
  51140. this._collisionPoint.copyFrom(p2);
  51141. }
  51142. this._basePoint.subtractToRef(p3, this._tempVector);
  51143. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51144. c = this._tempVector.lengthSquared() - 1.0;
  51145. lowestRoot = getLowestRoot(a, b, c, t);
  51146. if (lowestRoot.found) {
  51147. t = lowestRoot.root;
  51148. found = true;
  51149. this._collisionPoint.copyFrom(p3);
  51150. }
  51151. p2.subtractToRef(p1, this._edge);
  51152. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51153. var edgeSquaredLength = this._edge.lengthSquared();
  51154. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51155. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51156. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51157. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51158. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51159. lowestRoot = getLowestRoot(a, b, c, t);
  51160. if (lowestRoot.found) {
  51161. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51162. if (f >= 0.0 && f <= 1.0) {
  51163. t = lowestRoot.root;
  51164. found = true;
  51165. this._edge.scaleInPlace(f);
  51166. p1.addToRef(this._edge, this._collisionPoint);
  51167. }
  51168. }
  51169. p3.subtractToRef(p2, this._edge);
  51170. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51171. edgeSquaredLength = this._edge.lengthSquared();
  51172. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51173. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51174. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51175. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51176. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51177. lowestRoot = getLowestRoot(a, b, c, t);
  51178. if (lowestRoot.found) {
  51179. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51180. if (f >= 0.0 && f <= 1.0) {
  51181. t = lowestRoot.root;
  51182. found = true;
  51183. this._edge.scaleInPlace(f);
  51184. p2.addToRef(this._edge, this._collisionPoint);
  51185. }
  51186. }
  51187. p1.subtractToRef(p3, this._edge);
  51188. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51189. edgeSquaredLength = this._edge.lengthSquared();
  51190. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51191. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51192. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51193. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51194. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51195. lowestRoot = getLowestRoot(a, b, c, t);
  51196. if (lowestRoot.found) {
  51197. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51198. if (f >= 0.0 && f <= 1.0) {
  51199. t = lowestRoot.root;
  51200. found = true;
  51201. this._edge.scaleInPlace(f);
  51202. p3.addToRef(this._edge, this._collisionPoint);
  51203. }
  51204. }
  51205. }
  51206. if (found) {
  51207. var distToCollision = t * this._velocity.length();
  51208. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51209. if (!this.intersectionPoint) {
  51210. this.intersectionPoint = this._collisionPoint.clone();
  51211. }
  51212. else {
  51213. this.intersectionPoint.copyFrom(this._collisionPoint);
  51214. }
  51215. this._nearestDistance = distToCollision;
  51216. this.collisionFound = true;
  51217. }
  51218. }
  51219. };
  51220. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51221. for (var i = indexStart; i < indexEnd; i += 3) {
  51222. var p1 = pts[indices[i] - decal];
  51223. var p2 = pts[indices[i + 1] - decal];
  51224. var p3 = pts[indices[i + 2] - decal];
  51225. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51226. }
  51227. };
  51228. Collider.prototype._getResponse = function (pos, vel) {
  51229. pos.addToRef(vel, this._destinationPoint);
  51230. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51231. this._basePoint.addToRef(vel, pos);
  51232. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51233. this._slidePlaneNormal.normalize();
  51234. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51235. pos.addInPlace(this._displacementVector);
  51236. this.intersectionPoint.addInPlace(this._displacementVector);
  51237. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51238. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51239. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51240. };
  51241. return Collider;
  51242. }());
  51243. BABYLON.Collider = Collider;
  51244. })(BABYLON || (BABYLON = {}));
  51245. //# sourceMappingURL=babylon.collider.js.map
  51246. "use strict";
  51247. var BABYLON;
  51248. (function (BABYLON) {
  51249. //WebWorker code will be inserted to this variable.
  51250. BABYLON.CollisionWorker = "";
  51251. var WorkerTaskType;
  51252. (function (WorkerTaskType) {
  51253. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51254. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51255. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51256. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51257. var WorkerReplyType;
  51258. (function (WorkerReplyType) {
  51259. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51260. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51261. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51262. var CollisionCoordinatorWorker = /** @class */ (function () {
  51263. function CollisionCoordinatorWorker() {
  51264. var _this = this;
  51265. this._scaledPosition = BABYLON.Vector3.Zero();
  51266. this._scaledVelocity = BABYLON.Vector3.Zero();
  51267. this.onMeshUpdated = function (transformNode) {
  51268. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51269. };
  51270. this.onGeometryUpdated = function (geometry) {
  51271. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51272. };
  51273. this._afterRender = function () {
  51274. if (!_this._init)
  51275. return;
  51276. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51277. return;
  51278. }
  51279. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51280. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51281. if (_this._runningUpdated > 4) {
  51282. return;
  51283. }
  51284. ++_this._runningUpdated;
  51285. var payload = {
  51286. updatedMeshes: _this._addUpdateMeshesList,
  51287. updatedGeometries: _this._addUpdateGeometriesList,
  51288. removedGeometries: _this._toRemoveGeometryArray,
  51289. removedMeshes: _this._toRemoveMeshesArray
  51290. };
  51291. var message = {
  51292. payload: payload,
  51293. taskType: WorkerTaskType.UPDATE
  51294. };
  51295. var serializable = [];
  51296. for (var id in payload.updatedGeometries) {
  51297. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51298. //prepare transferables
  51299. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51300. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51301. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51302. }
  51303. }
  51304. _this._worker.postMessage(message, serializable);
  51305. _this._addUpdateMeshesList = {};
  51306. _this._addUpdateGeometriesList = {};
  51307. _this._toRemoveGeometryArray = [];
  51308. _this._toRemoveMeshesArray = [];
  51309. };
  51310. this._onMessageFromWorker = function (e) {
  51311. var returnData = e.data;
  51312. if (returnData.error != WorkerReplyType.SUCCESS) {
  51313. //TODO what errors can be returned from the worker?
  51314. BABYLON.Tools.Warn("error returned from worker!");
  51315. return;
  51316. }
  51317. switch (returnData.taskType) {
  51318. case WorkerTaskType.INIT:
  51319. _this._init = true;
  51320. //Update the worked with ALL of the scene's current state
  51321. _this._scene.meshes.forEach(function (mesh) {
  51322. _this.onMeshAdded(mesh);
  51323. });
  51324. _this._scene.getGeometries().forEach(function (geometry) {
  51325. _this.onGeometryAdded(geometry);
  51326. });
  51327. break;
  51328. case WorkerTaskType.UPDATE:
  51329. _this._runningUpdated--;
  51330. break;
  51331. case WorkerTaskType.COLLIDE:
  51332. var returnPayload = returnData.payload;
  51333. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51334. return;
  51335. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51336. if (callback) {
  51337. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51338. if (mesh) {
  51339. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51340. }
  51341. }
  51342. //cleanup
  51343. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51344. break;
  51345. }
  51346. };
  51347. this._collisionsCallbackArray = [];
  51348. this._init = false;
  51349. this._runningUpdated = 0;
  51350. this._addUpdateMeshesList = {};
  51351. this._addUpdateGeometriesList = {};
  51352. this._toRemoveGeometryArray = [];
  51353. this._toRemoveMeshesArray = [];
  51354. }
  51355. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51356. if (!this._init)
  51357. return;
  51358. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51359. return;
  51360. position.divideToRef(collider._radius, this._scaledPosition);
  51361. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51362. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51363. var payload = {
  51364. collider: {
  51365. position: this._scaledPosition.asArray(),
  51366. velocity: this._scaledVelocity.asArray(),
  51367. radius: collider._radius.asArray()
  51368. },
  51369. collisionId: collisionIndex,
  51370. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51371. maximumRetry: maximumRetry
  51372. };
  51373. var message = {
  51374. payload: payload,
  51375. taskType: WorkerTaskType.COLLIDE
  51376. };
  51377. this._worker.postMessage(message);
  51378. };
  51379. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51380. this._scene = scene;
  51381. this._scene.registerAfterRender(this._afterRender);
  51382. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51383. this._worker = new Worker(workerUrl);
  51384. this._worker.onmessage = this._onMessageFromWorker;
  51385. var message = {
  51386. payload: {},
  51387. taskType: WorkerTaskType.INIT
  51388. };
  51389. this._worker.postMessage(message);
  51390. };
  51391. CollisionCoordinatorWorker.prototype.destroy = function () {
  51392. this._scene.unregisterAfterRender(this._afterRender);
  51393. this._worker.terminate();
  51394. };
  51395. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51396. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51397. this.onMeshUpdated(mesh);
  51398. };
  51399. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51400. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51401. };
  51402. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51403. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51404. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51405. this.onGeometryUpdated(geometry);
  51406. };
  51407. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51408. this._toRemoveGeometryArray.push(geometry.id);
  51409. };
  51410. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51411. var submeshes = [];
  51412. if (mesh.subMeshes) {
  51413. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51414. var boundingInfo = sm.getBoundingInfo();
  51415. return {
  51416. position: idx,
  51417. verticesStart: sm.verticesStart,
  51418. verticesCount: sm.verticesCount,
  51419. indexStart: sm.indexStart,
  51420. indexCount: sm.indexCount,
  51421. hasMaterial: !!sm.getMaterial(),
  51422. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51423. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51424. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51425. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51426. };
  51427. });
  51428. }
  51429. var geometryId = null;
  51430. if (mesh instanceof BABYLON.Mesh) {
  51431. var geometry = mesh.geometry;
  51432. geometryId = geometry ? geometry.id : null;
  51433. }
  51434. else if (mesh instanceof BABYLON.InstancedMesh) {
  51435. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51436. geometryId = geometry ? geometry.id : null;
  51437. }
  51438. var boundingInfo = mesh.getBoundingInfo();
  51439. return {
  51440. uniqueId: mesh.uniqueId,
  51441. id: mesh.id,
  51442. name: mesh.name,
  51443. geometryId: geometryId,
  51444. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51445. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51446. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51447. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51448. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51449. subMeshes: submeshes,
  51450. checkCollisions: mesh.checkCollisions
  51451. };
  51452. };
  51453. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51454. return {
  51455. id: geometry.id,
  51456. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51457. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51458. indices: new Uint32Array(geometry.getIndices() || []),
  51459. };
  51460. };
  51461. return CollisionCoordinatorWorker;
  51462. }());
  51463. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51464. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51465. function CollisionCoordinatorLegacy() {
  51466. this._scaledPosition = BABYLON.Vector3.Zero();
  51467. this._scaledVelocity = BABYLON.Vector3.Zero();
  51468. this._finalPosition = BABYLON.Vector3.Zero();
  51469. }
  51470. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51471. position.divideToRef(collider._radius, this._scaledPosition);
  51472. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51473. collider.collidedMesh = null;
  51474. collider._retry = 0;
  51475. collider._initialVelocity = this._scaledVelocity;
  51476. collider._initialPosition = this._scaledPosition;
  51477. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51478. this._finalPosition.multiplyInPlace(collider._radius);
  51479. //run the callback
  51480. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51481. };
  51482. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51483. this._scene = scene;
  51484. };
  51485. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51486. //Legacy need no destruction method.
  51487. };
  51488. //No update in legacy mode
  51489. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51490. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51491. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51492. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51493. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51494. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51495. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51496. if (excludedMesh === void 0) { excludedMesh = null; }
  51497. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51498. if (collider._retry >= maximumRetry) {
  51499. finalPosition.copyFrom(position);
  51500. return;
  51501. }
  51502. // Check if this is a mesh else camera or -1
  51503. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51504. collider._initialize(position, velocity, closeDistance);
  51505. // Check all meshes
  51506. for (var index = 0; index < this._scene.meshes.length; index++) {
  51507. var mesh = this._scene.meshes[index];
  51508. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51509. mesh._checkCollision(collider);
  51510. }
  51511. }
  51512. if (!collider.collisionFound) {
  51513. position.addToRef(velocity, finalPosition);
  51514. return;
  51515. }
  51516. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51517. collider._getResponse(position, velocity);
  51518. }
  51519. if (velocity.length() <= closeDistance) {
  51520. finalPosition.copyFrom(position);
  51521. return;
  51522. }
  51523. collider._retry++;
  51524. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51525. };
  51526. return CollisionCoordinatorLegacy;
  51527. }());
  51528. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51529. })(BABYLON || (BABYLON = {}));
  51530. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51531. "use strict";
  51532. var BABYLON;
  51533. (function (BABYLON) {
  51534. /**
  51535. * A particle represents one of the element emitted by a particle system.
  51536. * This is mainly define by its coordinates, direction, velocity and age.
  51537. */
  51538. var Particle = /** @class */ (function () {
  51539. /**
  51540. * Creates a new instance Particle
  51541. * @param particleSystem the particle system the particle belongs to
  51542. */
  51543. function Particle(
  51544. /**
  51545. * particleSystem the particle system the particle belongs to.
  51546. */
  51547. particleSystem) {
  51548. this.particleSystem = particleSystem;
  51549. /**
  51550. * The world position of the particle in the scene.
  51551. */
  51552. this.position = BABYLON.Vector3.Zero();
  51553. /**
  51554. * The world direction of the particle in the scene.
  51555. */
  51556. this.direction = BABYLON.Vector3.Zero();
  51557. /**
  51558. * The color of the particle.
  51559. */
  51560. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51561. /**
  51562. * The color change of the particle per step.
  51563. */
  51564. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51565. /**
  51566. * Defines how long will the life of the particle be.
  51567. */
  51568. this.lifeTime = 1.0;
  51569. /**
  51570. * The current age of the particle.
  51571. */
  51572. this.age = 0;
  51573. /**
  51574. * The current size of the particle.
  51575. */
  51576. this.size = 0;
  51577. /**
  51578. * The current angle of the particle.
  51579. */
  51580. this.angle = 0;
  51581. /**
  51582. * Defines how fast is the angle changing.
  51583. */
  51584. this.angularSpeed = 0;
  51585. /**
  51586. * Defines the cell index used by the particle to be rendered from a sprite.
  51587. */
  51588. this.cellIndex = 0;
  51589. this._currentFrameCounter = 0;
  51590. if (!this.particleSystem.isAnimationSheetEnabled) {
  51591. return;
  51592. }
  51593. this.updateCellInfoFromSystem();
  51594. }
  51595. Particle.prototype.updateCellInfoFromSystem = function () {
  51596. this.cellIndex = this.particleSystem.startSpriteCellID;
  51597. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51598. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51599. }
  51600. else {
  51601. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51602. }
  51603. };
  51604. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51605. // (ageOffset / scaledUpdateSpeed) / available cells
  51606. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51607. this._currentFrameCounter += scaledUpdateSpeed;
  51608. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51609. this._currentFrameCounter = 0;
  51610. this.cellIndex++;
  51611. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51612. this.cellIndex = this.particleSystem.endSpriteCellID;
  51613. }
  51614. }
  51615. };
  51616. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51617. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51618. this.cellIndex++;
  51619. this._currentFrameCounter = 0;
  51620. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51621. if (this.particleSystem.spriteCellLoop) {
  51622. this.cellIndex = this.particleSystem.startSpriteCellID;
  51623. }
  51624. else {
  51625. this.cellIndex = this.particleSystem.endSpriteCellID;
  51626. }
  51627. }
  51628. }
  51629. else {
  51630. this._currentFrameCounter++;
  51631. }
  51632. };
  51633. /**
  51634. * Copy the properties of particle to another one.
  51635. * @param other the particle to copy the information to.
  51636. */
  51637. Particle.prototype.copyTo = function (other) {
  51638. other.position.copyFrom(this.position);
  51639. other.direction.copyFrom(this.direction);
  51640. other.color.copyFrom(this.color);
  51641. other.colorStep.copyFrom(this.colorStep);
  51642. other.lifeTime = this.lifeTime;
  51643. other.age = this.age;
  51644. other.size = this.size;
  51645. other.angle = this.angle;
  51646. other.angularSpeed = this.angularSpeed;
  51647. other.particleSystem = this.particleSystem;
  51648. other.cellIndex = this.cellIndex;
  51649. };
  51650. return Particle;
  51651. }());
  51652. BABYLON.Particle = Particle;
  51653. })(BABYLON || (BABYLON = {}));
  51654. //# sourceMappingURL=babylon.particle.js.map
  51655. "use strict";
  51656. var BABYLON;
  51657. (function (BABYLON) {
  51658. /**
  51659. * This represents a particle system in Babylon.
  51660. * 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.
  51661. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51662. * @example https://doc.babylonjs.com/babylon101/particles
  51663. */
  51664. var ParticleSystem = /** @class */ (function () {
  51665. /**
  51666. * Instantiates a particle system.
  51667. * 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.
  51668. * @param name The name of the particle system
  51669. * @param capacity The max number of particles alive at the same time
  51670. * @param scene The scene the particle system belongs to
  51671. * @param customEffect a custom effect used to change the way particles are rendered by default
  51672. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51673. * @param epsilon Offset used to render the particles
  51674. */
  51675. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51676. if (customEffect === void 0) { customEffect = null; }
  51677. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51678. if (epsilon === void 0) { epsilon = 0.01; }
  51679. var _this = this;
  51680. /**
  51681. * List of animations used by the particle system.
  51682. */
  51683. this.animations = [];
  51684. /**
  51685. * The rendering group used by the Particle system to chose when to render.
  51686. */
  51687. this.renderingGroupId = 0;
  51688. /**
  51689. * The emitter represents the Mesh or position we are attaching the particle system to.
  51690. */
  51691. this.emitter = null;
  51692. /**
  51693. * The maximum number of particles to emit per frame
  51694. */
  51695. this.emitRate = 10;
  51696. /**
  51697. * If you want to launch only a few particles at once, that can be done, as well.
  51698. */
  51699. this.manualEmitCount = -1;
  51700. /**
  51701. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51702. */
  51703. this.updateSpeed = 0.01;
  51704. /**
  51705. * The amount of time the particle system is running (depends of the overall update speed).
  51706. */
  51707. this.targetStopDuration = 0;
  51708. /**
  51709. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51710. */
  51711. this.disposeOnStop = false;
  51712. /**
  51713. * Minimum power of emitting particles.
  51714. */
  51715. this.minEmitPower = 1;
  51716. /**
  51717. * Maximum power of emitting particles.
  51718. */
  51719. this.maxEmitPower = 1;
  51720. /**
  51721. * Minimum life time of emitting particles.
  51722. */
  51723. this.minLifeTime = 1;
  51724. /**
  51725. * Maximum life time of emitting particles.
  51726. */
  51727. this.maxLifeTime = 1;
  51728. /**
  51729. * Minimum Size of emitting particles.
  51730. */
  51731. this.minSize = 1;
  51732. /**
  51733. * Maximum Size of emitting particles.
  51734. */
  51735. this.maxSize = 1;
  51736. /**
  51737. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51738. */
  51739. this.minAngularSpeed = 0;
  51740. /**
  51741. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51742. */
  51743. this.maxAngularSpeed = 0;
  51744. /**
  51745. * The layer mask we are rendering the particles through.
  51746. */
  51747. this.layerMask = 0x0FFFFFFF;
  51748. /**
  51749. * This can help using your own shader to render the particle system.
  51750. * The according effect will be created
  51751. */
  51752. this.customShader = null;
  51753. /**
  51754. * By default particle system starts as soon as they are created. This prevents the
  51755. * automatic start to happen and let you decide when to start emitting particles.
  51756. */
  51757. this.preventAutoStart = false;
  51758. /**
  51759. * Callback triggered when the particle animation is ending.
  51760. */
  51761. this.onAnimationEnd = null;
  51762. /**
  51763. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51764. */
  51765. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51766. /**
  51767. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51768. * to override the particles.
  51769. */
  51770. this.forceDepthWrite = false;
  51771. /**
  51772. * You can use gravity if you want to give an orientation to your particles.
  51773. */
  51774. this.gravity = BABYLON.Vector3.Zero();
  51775. /**
  51776. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51777. */
  51778. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51779. /**
  51780. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51781. */
  51782. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51783. /**
  51784. * Color the particle will have at the end of its lifetime.
  51785. */
  51786. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51787. /**
  51788. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51789. */
  51790. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51791. /**
  51792. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51793. */
  51794. this.spriteCellLoop = true;
  51795. /**
  51796. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51797. */
  51798. this.spriteCellChangeSpeed = 0;
  51799. /**
  51800. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51801. */
  51802. this.startSpriteCellID = 0;
  51803. /**
  51804. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51805. */
  51806. this.endSpriteCellID = 0;
  51807. /**
  51808. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51809. */
  51810. this.spriteCellWidth = 0;
  51811. /**
  51812. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51813. */
  51814. this.spriteCellHeight = 0;
  51815. /**
  51816. * An event triggered when the system is disposed.
  51817. */
  51818. this.onDisposeObservable = new BABYLON.Observable();
  51819. this._particles = new Array();
  51820. this._stockParticles = new Array();
  51821. this._newPartsExcess = 0;
  51822. this._vertexBuffers = {};
  51823. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51824. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51825. this._scaledDirection = BABYLON.Vector3.Zero();
  51826. this._scaledGravity = BABYLON.Vector3.Zero();
  51827. this._currentRenderId = -1;
  51828. this._started = false;
  51829. this._stopped = false;
  51830. this._actualFrame = 0;
  51831. this._vertexBufferSize = 11;
  51832. // start of sub system methods
  51833. /**
  51834. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51835. * Its lifetime will start back at 0.
  51836. */
  51837. this.recycleParticle = function (particle) {
  51838. var lastParticle = _this._particles.pop();
  51839. if (lastParticle !== particle) {
  51840. lastParticle.copyTo(particle);
  51841. }
  51842. _this._stockParticles.push(lastParticle);
  51843. };
  51844. this._createParticle = function () {
  51845. var particle;
  51846. if (_this._stockParticles.length !== 0) {
  51847. particle = _this._stockParticles.pop();
  51848. particle.age = 0;
  51849. particle.cellIndex = _this.startSpriteCellID;
  51850. }
  51851. else {
  51852. particle = new BABYLON.Particle(_this);
  51853. }
  51854. return particle;
  51855. };
  51856. this._emitFromParticle = function (particle) {
  51857. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51858. return;
  51859. }
  51860. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51861. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51862. subSystem._rootParticleSystem = _this;
  51863. _this.activeSubSystems.push(subSystem);
  51864. subSystem.start();
  51865. };
  51866. this._appendParticleVertexes = null;
  51867. this.id = name;
  51868. this.name = name;
  51869. this._capacity = capacity;
  51870. this._epsilon = epsilon;
  51871. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51872. if (isAnimationSheetEnabled) {
  51873. this._vertexBufferSize = 12;
  51874. }
  51875. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51876. this._customEffect = customEffect;
  51877. scene.particleSystems.push(this);
  51878. this._createIndexBuffer();
  51879. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51880. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51881. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51882. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51883. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51884. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51885. if (this._isAnimationSheetEnabled) {
  51886. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51887. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51888. }
  51889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51890. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51891. this._vertexBuffers["options"] = options;
  51892. // Default emitter type
  51893. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51894. this.updateFunction = function (particles) {
  51895. for (var index = 0; index < particles.length; index++) {
  51896. var particle = particles[index];
  51897. particle.age += _this._scaledUpdateSpeed;
  51898. if (particle.age >= particle.lifeTime) {
  51899. _this._emitFromParticle(particle);
  51900. _this.recycleParticle(particle);
  51901. index--;
  51902. continue;
  51903. }
  51904. else {
  51905. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51906. particle.color.addInPlace(_this._scaledColorStep);
  51907. if (particle.color.a < 0)
  51908. particle.color.a = 0;
  51909. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51910. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51911. particle.position.addInPlace(_this._scaledDirection);
  51912. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51913. particle.direction.addInPlace(_this._scaledGravity);
  51914. if (_this._isAnimationSheetEnabled) {
  51915. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51916. }
  51917. }
  51918. }
  51919. };
  51920. }
  51921. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51922. /**
  51923. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51924. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51925. */
  51926. get: function () {
  51927. if (this.particleEmitterType.direction1) {
  51928. return this.particleEmitterType.direction1;
  51929. }
  51930. return BABYLON.Vector3.Zero();
  51931. },
  51932. set: function (value) {
  51933. if (this.particleEmitterType.direction1) {
  51934. this.particleEmitterType.direction1 = value;
  51935. }
  51936. },
  51937. enumerable: true,
  51938. configurable: true
  51939. });
  51940. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51941. /**
  51942. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51943. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51944. */
  51945. get: function () {
  51946. if (this.particleEmitterType.direction2) {
  51947. return this.particleEmitterType.direction2;
  51948. }
  51949. return BABYLON.Vector3.Zero();
  51950. },
  51951. set: function (value) {
  51952. if (this.particleEmitterType.direction2) {
  51953. this.particleEmitterType.direction2 = value;
  51954. }
  51955. },
  51956. enumerable: true,
  51957. configurable: true
  51958. });
  51959. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51960. /**
  51961. * 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.
  51962. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51963. */
  51964. get: function () {
  51965. if (this.particleEmitterType.minEmitBox) {
  51966. return this.particleEmitterType.minEmitBox;
  51967. }
  51968. return BABYLON.Vector3.Zero();
  51969. },
  51970. set: function (value) {
  51971. if (this.particleEmitterType.minEmitBox) {
  51972. this.particleEmitterType.minEmitBox = value;
  51973. }
  51974. },
  51975. enumerable: true,
  51976. configurable: true
  51977. });
  51978. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51979. /**
  51980. * 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.
  51981. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51982. */
  51983. get: function () {
  51984. if (this.particleEmitterType.maxEmitBox) {
  51985. return this.particleEmitterType.maxEmitBox;
  51986. }
  51987. return BABYLON.Vector3.Zero();
  51988. },
  51989. set: function (value) {
  51990. if (this.particleEmitterType.maxEmitBox) {
  51991. this.particleEmitterType.maxEmitBox = value;
  51992. }
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51998. /**
  51999. * Sets a callback that will be triggered when the system is disposed.
  52000. */
  52001. set: function (callback) {
  52002. if (this._onDisposeObserver) {
  52003. this.onDisposeObservable.remove(this._onDisposeObserver);
  52004. }
  52005. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52006. },
  52007. enumerable: true,
  52008. configurable: true
  52009. });
  52010. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  52011. /**
  52012. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  52013. */
  52014. get: function () {
  52015. return this._isAnimationSheetEnabled;
  52016. },
  52017. enumerable: true,
  52018. configurable: true
  52019. });
  52020. Object.defineProperty(ParticleSystem.prototype, "particles", {
  52021. //end of Sub-emitter
  52022. /**
  52023. * Gets the current list of active particles
  52024. */
  52025. get: function () {
  52026. return this._particles;
  52027. },
  52028. enumerable: true,
  52029. configurable: true
  52030. });
  52031. /**
  52032. * Returns the string "ParticleSystem"
  52033. * @returns a string containing the class name
  52034. */
  52035. ParticleSystem.prototype.getClassName = function () {
  52036. return "ParticleSystem";
  52037. };
  52038. ParticleSystem.prototype._createIndexBuffer = function () {
  52039. var indices = [];
  52040. var index = 0;
  52041. for (var count = 0; count < this._capacity; count++) {
  52042. indices.push(index);
  52043. indices.push(index + 1);
  52044. indices.push(index + 2);
  52045. indices.push(index);
  52046. indices.push(index + 2);
  52047. indices.push(index + 3);
  52048. index += 4;
  52049. }
  52050. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  52051. };
  52052. /**
  52053. * Gets the maximum number of particles active at the same time.
  52054. * @returns The max number of active particles.
  52055. */
  52056. ParticleSystem.prototype.getCapacity = function () {
  52057. return this._capacity;
  52058. };
  52059. /**
  52060. * Gets Wether there are still active particles in the system.
  52061. * @returns True if it is alive, otherwise false.
  52062. */
  52063. ParticleSystem.prototype.isAlive = function () {
  52064. return this._alive;
  52065. };
  52066. /**
  52067. * Gets Wether the system has been started.
  52068. * @returns True if it has been started, otherwise false.
  52069. */
  52070. ParticleSystem.prototype.isStarted = function () {
  52071. return this._started;
  52072. };
  52073. /**
  52074. * Starts the particle system and begins to emit.
  52075. */
  52076. ParticleSystem.prototype.start = function () {
  52077. this._started = true;
  52078. this._stopped = false;
  52079. this._actualFrame = 0;
  52080. if (this.subEmitters && this.subEmitters.length != 0) {
  52081. this.activeSubSystems = new Array();
  52082. }
  52083. };
  52084. /**
  52085. * Stops the particle system.
  52086. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  52087. */
  52088. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52089. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52090. this._stopped = true;
  52091. if (stopSubEmitters) {
  52092. this._stopSubEmitters();
  52093. }
  52094. };
  52095. // animation sheet
  52096. /**
  52097. * Remove all active particles
  52098. */
  52099. ParticleSystem.prototype.reset = function () {
  52100. this._stockParticles = [];
  52101. this._particles = [];
  52102. };
  52103. /**
  52104. * @ignore (for internal use only)
  52105. */
  52106. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52107. var offset = index * this._vertexBufferSize;
  52108. this._vertexData[offset] = particle.position.x;
  52109. this._vertexData[offset + 1] = particle.position.y;
  52110. this._vertexData[offset + 2] = particle.position.z;
  52111. this._vertexData[offset + 3] = particle.color.r;
  52112. this._vertexData[offset + 4] = particle.color.g;
  52113. this._vertexData[offset + 5] = particle.color.b;
  52114. this._vertexData[offset + 6] = particle.color.a;
  52115. this._vertexData[offset + 7] = particle.angle;
  52116. this._vertexData[offset + 8] = particle.size;
  52117. this._vertexData[offset + 9] = offsetX;
  52118. this._vertexData[offset + 10] = offsetY;
  52119. };
  52120. /**
  52121. * @ignore (for internal use only)
  52122. */
  52123. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52124. if (offsetX === 0)
  52125. offsetX = this._epsilon;
  52126. else if (offsetX === 1)
  52127. offsetX = 1 - this._epsilon;
  52128. if (offsetY === 0)
  52129. offsetY = this._epsilon;
  52130. else if (offsetY === 1)
  52131. offsetY = 1 - this._epsilon;
  52132. var offset = index * this._vertexBufferSize;
  52133. this._vertexData[offset] = particle.position.x;
  52134. this._vertexData[offset + 1] = particle.position.y;
  52135. this._vertexData[offset + 2] = particle.position.z;
  52136. this._vertexData[offset + 3] = particle.color.r;
  52137. this._vertexData[offset + 4] = particle.color.g;
  52138. this._vertexData[offset + 5] = particle.color.b;
  52139. this._vertexData[offset + 6] = particle.color.a;
  52140. this._vertexData[offset + 7] = particle.angle;
  52141. this._vertexData[offset + 8] = particle.size;
  52142. this._vertexData[offset + 9] = offsetX;
  52143. this._vertexData[offset + 10] = offsetY;
  52144. this._vertexData[offset + 11] = particle.cellIndex;
  52145. };
  52146. ParticleSystem.prototype._stopSubEmitters = function () {
  52147. if (!this.activeSubSystems) {
  52148. return;
  52149. }
  52150. this.activeSubSystems.forEach(function (subSystem) {
  52151. subSystem.stop(true);
  52152. });
  52153. this.activeSubSystems = new Array();
  52154. };
  52155. ParticleSystem.prototype._removeFromRoot = function () {
  52156. if (!this._rootParticleSystem) {
  52157. return;
  52158. }
  52159. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52160. if (index !== -1) {
  52161. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52162. }
  52163. };
  52164. // end of sub system methods
  52165. ParticleSystem.prototype._update = function (newParticles) {
  52166. // Update current
  52167. this._alive = this._particles.length > 0;
  52168. this.updateFunction(this._particles);
  52169. // Add new ones
  52170. var worldMatrix;
  52171. if (this.emitter.position) {
  52172. var emitterMesh = this.emitter;
  52173. worldMatrix = emitterMesh.getWorldMatrix();
  52174. }
  52175. else {
  52176. var emitterPosition = this.emitter;
  52177. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52178. }
  52179. var particle;
  52180. for (var index = 0; index < newParticles; index++) {
  52181. if (this._particles.length === this._capacity) {
  52182. break;
  52183. }
  52184. particle = this._createParticle();
  52185. this._particles.push(particle);
  52186. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52187. if (this.startPositionFunction) {
  52188. this.startPositionFunction(worldMatrix, particle.position, particle);
  52189. }
  52190. else {
  52191. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52192. }
  52193. if (this.startDirectionFunction) {
  52194. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52195. }
  52196. else {
  52197. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52198. }
  52199. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52200. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52201. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52202. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52203. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52204. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52205. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52206. }
  52207. };
  52208. ParticleSystem.prototype._getEffect = function () {
  52209. if (this._customEffect) {
  52210. return this._customEffect;
  52211. }
  52212. ;
  52213. var defines = [];
  52214. if (this._scene.clipPlane) {
  52215. defines.push("#define CLIPPLANE");
  52216. }
  52217. if (this._isAnimationSheetEnabled) {
  52218. defines.push("#define ANIMATESHEET");
  52219. }
  52220. // Effect
  52221. var join = defines.join("\n");
  52222. if (this._cachedDefines !== join) {
  52223. this._cachedDefines = join;
  52224. var attributesNamesOrOptions;
  52225. var effectCreationOption;
  52226. if (this._isAnimationSheetEnabled) {
  52227. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52228. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52229. }
  52230. else {
  52231. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52232. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52233. }
  52234. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52235. }
  52236. return this._effect;
  52237. };
  52238. /**
  52239. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52240. */
  52241. ParticleSystem.prototype.animate = function () {
  52242. if (!this._started)
  52243. return;
  52244. var effect = this._getEffect();
  52245. // Check
  52246. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52247. return;
  52248. if (this._currentRenderId === this._scene.getRenderId()) {
  52249. return;
  52250. }
  52251. this._currentRenderId = this._scene.getRenderId();
  52252. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52253. // determine the number of particles we need to create
  52254. var newParticles;
  52255. if (this.manualEmitCount > -1) {
  52256. newParticles = this.manualEmitCount;
  52257. this._newPartsExcess = 0;
  52258. this.manualEmitCount = 0;
  52259. }
  52260. else {
  52261. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52262. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52263. }
  52264. if (this._newPartsExcess > 1.0) {
  52265. newParticles += this._newPartsExcess >> 0;
  52266. this._newPartsExcess -= this._newPartsExcess >> 0;
  52267. }
  52268. this._alive = false;
  52269. if (!this._stopped) {
  52270. this._actualFrame += this._scaledUpdateSpeed;
  52271. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52272. this.stop();
  52273. }
  52274. else {
  52275. newParticles = 0;
  52276. }
  52277. this._update(newParticles);
  52278. // Stopped?
  52279. if (this._stopped) {
  52280. if (!this._alive) {
  52281. this._started = false;
  52282. if (this.onAnimationEnd) {
  52283. this.onAnimationEnd();
  52284. }
  52285. if (this.disposeOnStop) {
  52286. this._scene._toBeDisposed.push(this);
  52287. }
  52288. }
  52289. }
  52290. // Animation sheet
  52291. if (this._isAnimationSheetEnabled) {
  52292. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52293. }
  52294. else {
  52295. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52296. }
  52297. // Update VBO
  52298. var offset = 0;
  52299. for (var index = 0; index < this._particles.length; index++) {
  52300. var particle = this._particles[index];
  52301. this._appendParticleVertexes(offset, particle);
  52302. offset += 4;
  52303. }
  52304. if (this._vertexBuffer) {
  52305. this._vertexBuffer.update(this._vertexData);
  52306. }
  52307. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52308. this.stop();
  52309. }
  52310. };
  52311. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52312. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52313. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52314. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52315. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52316. };
  52317. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52318. this._appendParticleVertex(offset++, particle, 0, 0);
  52319. this._appendParticleVertex(offset++, particle, 1, 0);
  52320. this._appendParticleVertex(offset++, particle, 1, 1);
  52321. this._appendParticleVertex(offset++, particle, 0, 1);
  52322. };
  52323. /**
  52324. * Rebuilds the particle system.
  52325. */
  52326. ParticleSystem.prototype.rebuild = function () {
  52327. this._createIndexBuffer();
  52328. if (this._vertexBuffer) {
  52329. this._vertexBuffer._rebuild();
  52330. }
  52331. };
  52332. /**
  52333. * Is this system ready to be used/rendered
  52334. * @return true if the system is ready
  52335. */
  52336. ParticleSystem.prototype.isReady = function () {
  52337. var effect = this._getEffect();
  52338. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52339. return false;
  52340. }
  52341. return true;
  52342. };
  52343. /**
  52344. * Renders the particle system in its current state.
  52345. * @returns the current number of particles
  52346. */
  52347. ParticleSystem.prototype.render = function () {
  52348. var effect = this._getEffect();
  52349. // Check
  52350. if (!this.isReady() || !this._particles.length) {
  52351. return 0;
  52352. }
  52353. var engine = this._scene.getEngine();
  52354. // Render
  52355. engine.enableEffect(effect);
  52356. engine.setState(false);
  52357. var viewMatrix = this._scene.getViewMatrix();
  52358. effect.setTexture("diffuseSampler", this.particleTexture);
  52359. effect.setMatrix("view", viewMatrix);
  52360. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52361. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52362. var baseSize = this.particleTexture.getBaseSize();
  52363. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52364. }
  52365. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52366. if (this._scene.clipPlane) {
  52367. var clipPlane = this._scene.clipPlane;
  52368. var invView = viewMatrix.clone();
  52369. invView.invert();
  52370. effect.setMatrix("invView", invView);
  52371. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52372. }
  52373. // VBOs
  52374. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52375. // Draw order
  52376. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52377. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52378. }
  52379. else {
  52380. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52381. }
  52382. if (this.forceDepthWrite) {
  52383. engine.setDepthWrite(true);
  52384. }
  52385. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52386. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52387. return this._particles.length;
  52388. };
  52389. /**
  52390. * Disposes the particle system and free the associated resources
  52391. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52392. */
  52393. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52394. if (disposeTexture === void 0) { disposeTexture = true; }
  52395. if (this._vertexBuffer) {
  52396. this._vertexBuffer.dispose();
  52397. this._vertexBuffer = null;
  52398. }
  52399. if (this._indexBuffer) {
  52400. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52401. this._indexBuffer = null;
  52402. }
  52403. if (disposeTexture && this.particleTexture) {
  52404. this.particleTexture.dispose();
  52405. this.particleTexture = null;
  52406. }
  52407. this._removeFromRoot();
  52408. // Remove from scene
  52409. var index = this._scene.particleSystems.indexOf(this);
  52410. if (index > -1) {
  52411. this._scene.particleSystems.splice(index, 1);
  52412. }
  52413. // Callback
  52414. this.onDisposeObservable.notifyObservers(this);
  52415. this.onDisposeObservable.clear();
  52416. };
  52417. /**
  52418. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52419. * @param radius The radius of the sphere to emit from
  52420. * @returns the emitter
  52421. */
  52422. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52423. if (radius === void 0) { radius = 1; }
  52424. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52425. this.particleEmitterType = particleEmitter;
  52426. return particleEmitter;
  52427. };
  52428. /**
  52429. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52430. * @param radius The radius of the sphere to emit from
  52431. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52432. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52433. * @returns the emitter
  52434. */
  52435. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52436. if (radius === void 0) { radius = 1; }
  52437. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52438. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52439. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52440. this.particleEmitterType = particleEmitter;
  52441. return particleEmitter;
  52442. };
  52443. /**
  52444. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52445. * @param radius The radius of the cone to emit from
  52446. * @param angle The base angle of the cone
  52447. * @returns the emitter
  52448. */
  52449. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52450. if (radius === void 0) { radius = 1; }
  52451. if (angle === void 0) { angle = Math.PI / 4; }
  52452. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52453. this.particleEmitterType = particleEmitter;
  52454. return particleEmitter;
  52455. };
  52456. // 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.
  52457. /**
  52458. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52459. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52460. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52461. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52462. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52463. * @returns the emitter
  52464. */
  52465. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52466. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52467. this.particleEmitterType = particleEmitter;
  52468. this.direction1 = direction1;
  52469. this.direction2 = direction2;
  52470. this.minEmitBox = minEmitBox;
  52471. this.maxEmitBox = maxEmitBox;
  52472. return particleEmitter;
  52473. };
  52474. // Clone
  52475. /**
  52476. * Clones the particle system.
  52477. * @param name The name of the cloned object
  52478. * @param newEmitter The new emitter to use
  52479. * @returns the cloned particle system
  52480. */
  52481. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52482. var custom = null;
  52483. var program = null;
  52484. if (this.customShader != null) {
  52485. program = this.customShader;
  52486. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52487. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52488. }
  52489. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52490. result.customShader = program;
  52491. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52492. if (newEmitter === undefined) {
  52493. newEmitter = this.emitter;
  52494. }
  52495. result.emitter = newEmitter;
  52496. if (this.particleTexture) {
  52497. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52498. }
  52499. if (!this.preventAutoStart) {
  52500. result.start();
  52501. }
  52502. return result;
  52503. };
  52504. /**
  52505. * Serializes the particle system to a JSON object.
  52506. * @returns the JSON object
  52507. */
  52508. ParticleSystem.prototype.serialize = function () {
  52509. var serializationObject = {};
  52510. serializationObject.name = this.name;
  52511. serializationObject.id = this.id;
  52512. // Emitter
  52513. if (this.emitter.position) {
  52514. var emitterMesh = this.emitter;
  52515. serializationObject.emitterId = emitterMesh.id;
  52516. }
  52517. else {
  52518. var emitterPosition = this.emitter;
  52519. serializationObject.emitter = emitterPosition.asArray();
  52520. }
  52521. serializationObject.capacity = this.getCapacity();
  52522. if (this.particleTexture) {
  52523. serializationObject.textureName = this.particleTexture.name;
  52524. }
  52525. // Animations
  52526. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52527. // Particle system
  52528. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52529. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52530. serializationObject.minSize = this.minSize;
  52531. serializationObject.maxSize = this.maxSize;
  52532. serializationObject.minEmitPower = this.minEmitPower;
  52533. serializationObject.maxEmitPower = this.maxEmitPower;
  52534. serializationObject.minLifeTime = this.minLifeTime;
  52535. serializationObject.maxLifeTime = this.maxLifeTime;
  52536. serializationObject.emitRate = this.emitRate;
  52537. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52538. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52539. serializationObject.gravity = this.gravity.asArray();
  52540. serializationObject.direction1 = this.direction1.asArray();
  52541. serializationObject.direction2 = this.direction2.asArray();
  52542. serializationObject.color1 = this.color1.asArray();
  52543. serializationObject.color2 = this.color2.asArray();
  52544. serializationObject.colorDead = this.colorDead.asArray();
  52545. serializationObject.updateSpeed = this.updateSpeed;
  52546. serializationObject.targetStopDuration = this.targetStopDuration;
  52547. serializationObject.textureMask = this.textureMask.asArray();
  52548. serializationObject.blendMode = this.blendMode;
  52549. serializationObject.customShader = this.customShader;
  52550. serializationObject.preventAutoStart = this.preventAutoStart;
  52551. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52552. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52553. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52554. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52555. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52556. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52557. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52558. // Emitter
  52559. if (this.particleEmitterType) {
  52560. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52561. }
  52562. return serializationObject;
  52563. };
  52564. /**
  52565. * Parses a JSON object to create a particle system.
  52566. * @param parsedParticleSystem The JSON object to parse
  52567. * @param scene The scene to create the particle system in
  52568. * @param rootUrl The root url to use to load external dependencies like texture
  52569. * @returns the Parsed particle system
  52570. */
  52571. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52572. var name = parsedParticleSystem.name;
  52573. var custom = null;
  52574. var program = null;
  52575. if (parsedParticleSystem.customShader) {
  52576. program = parsedParticleSystem.customShader;
  52577. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52578. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52579. }
  52580. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52581. particleSystem.customShader = program;
  52582. if (parsedParticleSystem.id) {
  52583. particleSystem.id = parsedParticleSystem.id;
  52584. }
  52585. // Auto start
  52586. if (parsedParticleSystem.preventAutoStart) {
  52587. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52588. }
  52589. // Texture
  52590. if (parsedParticleSystem.textureName) {
  52591. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52592. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52593. }
  52594. // Emitter
  52595. if (parsedParticleSystem.emitterId) {
  52596. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52597. }
  52598. else {
  52599. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52600. }
  52601. // Animations
  52602. if (parsedParticleSystem.animations) {
  52603. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52604. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52605. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52606. }
  52607. }
  52608. if (parsedParticleSystem.autoAnimate) {
  52609. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52610. }
  52611. // Particle system
  52612. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52613. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52614. particleSystem.minSize = parsedParticleSystem.minSize;
  52615. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52616. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52617. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52618. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52619. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52620. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52621. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52622. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52623. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52624. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52625. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52626. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52627. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52628. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52629. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52630. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52631. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52632. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52633. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52634. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52635. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52636. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52637. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52638. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52639. if (!particleSystem.preventAutoStart) {
  52640. particleSystem.start();
  52641. }
  52642. return particleSystem;
  52643. };
  52644. /**
  52645. * Source color is added to the destination color without alpha affecting the result.
  52646. */
  52647. ParticleSystem.BLENDMODE_ONEONE = 0;
  52648. /**
  52649. * Blend current color and particle color using particle’s alpha.
  52650. */
  52651. ParticleSystem.BLENDMODE_STANDARD = 1;
  52652. return ParticleSystem;
  52653. }());
  52654. BABYLON.ParticleSystem = ParticleSystem;
  52655. })(BABYLON || (BABYLON = {}));
  52656. //# sourceMappingURL=babylon.particleSystem.js.map
  52657. "use strict";
  52658. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52659. "use strict";
  52660. var BABYLON;
  52661. (function (BABYLON) {
  52662. /**
  52663. * Particle emitter emitting particles from the inside of a box.
  52664. * It emits the particles randomly between 2 given directions.
  52665. */
  52666. var BoxParticleEmitter = /** @class */ (function () {
  52667. /**
  52668. * Creates a new instance BoxParticleEmitter
  52669. */
  52670. function BoxParticleEmitter() {
  52671. /**
  52672. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52673. */
  52674. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52675. /**
  52676. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52677. */
  52678. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52679. /**
  52680. * 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.
  52681. */
  52682. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52683. /**
  52684. * 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.
  52685. */
  52686. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52687. }
  52688. /**
  52689. * Called by the particle System when the direction is computed for the created particle.
  52690. * @param emitPower is the power of the particle (speed)
  52691. * @param worldMatrix is the world matrix of the particle system
  52692. * @param directionToUpdate is the direction vector to update with the result
  52693. * @param particle is the particle we are computed the direction for
  52694. */
  52695. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52696. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52697. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52698. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52699. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52700. };
  52701. /**
  52702. * Called by the particle System when the position is computed for the created particle.
  52703. * @param worldMatrix is the world matrix of the particle system
  52704. * @param positionToUpdate is the position vector to update with the result
  52705. * @param particle is the particle we are computed the position for
  52706. */
  52707. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52708. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52709. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52710. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52711. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52712. };
  52713. /**
  52714. * Clones the current emitter and returns a copy of it
  52715. * @returns the new emitter
  52716. */
  52717. BoxParticleEmitter.prototype.clone = function () {
  52718. var newOne = new BoxParticleEmitter();
  52719. BABYLON.Tools.DeepCopy(this, newOne);
  52720. return newOne;
  52721. };
  52722. /**
  52723. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52724. * @param effect defines the update shader
  52725. */
  52726. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52727. effect.setVector3("direction1", this.direction1);
  52728. effect.setVector3("direction2", this.direction2);
  52729. effect.setVector3("minEmitBox", this.minEmitBox);
  52730. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52731. };
  52732. /**
  52733. * Returns a string to use to update the GPU particles update shader
  52734. * @returns a string containng the defines string
  52735. */
  52736. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52737. return "#define BOXEMITTER";
  52738. };
  52739. /**
  52740. * Returns the string "BoxEmitter"
  52741. * @returns a string containing the class name
  52742. */
  52743. BoxParticleEmitter.prototype.getClassName = function () {
  52744. return "BoxEmitter";
  52745. };
  52746. /**
  52747. * Serializes the particle system to a JSON object.
  52748. * @returns the JSON object
  52749. */
  52750. BoxParticleEmitter.prototype.serialize = function () {
  52751. var serializationObject = {};
  52752. serializationObject.type = this.getClassName();
  52753. serializationObject.direction1 = this.direction1.asArray();
  52754. ;
  52755. serializationObject.direction2 = this.direction2.asArray();
  52756. ;
  52757. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52758. ;
  52759. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52760. ;
  52761. return serializationObject;
  52762. };
  52763. /**
  52764. * Parse properties from a JSON object
  52765. * @param serializationObject defines the JSON object
  52766. */
  52767. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52768. this.direction1.copyFrom(serializationObject.direction1);
  52769. this.direction2.copyFrom(serializationObject.direction2);
  52770. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52771. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52772. };
  52773. return BoxParticleEmitter;
  52774. }());
  52775. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52776. })(BABYLON || (BABYLON = {}));
  52777. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52778. "use strict";
  52779. var BABYLON;
  52780. (function (BABYLON) {
  52781. /**
  52782. * Particle emitter emitting particles from the inside of a cone.
  52783. * It emits the particles alongside the cone volume from the base to the particle.
  52784. * The emission direction might be randomized.
  52785. */
  52786. var ConeParticleEmitter = /** @class */ (function () {
  52787. /**
  52788. * Creates a new instance ConeParticleEmitter
  52789. * @param radius the radius of the emission cone (1 by default)
  52790. * @param angles the cone base angle (PI by default)
  52791. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52792. */
  52793. function ConeParticleEmitter(radius,
  52794. /**
  52795. * The radius of the emission cone.
  52796. */
  52797. angle,
  52798. /**
  52799. * The cone base angle.
  52800. */
  52801. directionRandomizer) {
  52802. if (radius === void 0) { radius = 1; }
  52803. if (angle === void 0) { angle = Math.PI; }
  52804. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52805. this.angle = angle;
  52806. this.directionRandomizer = directionRandomizer;
  52807. this.radius = radius;
  52808. }
  52809. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52810. /**
  52811. * Gets the radius of the emission cone.
  52812. */
  52813. get: function () {
  52814. return this._radius;
  52815. },
  52816. /**
  52817. * Sets the radius of the emission cone.
  52818. */
  52819. set: function (value) {
  52820. this._radius = value;
  52821. if (this.angle !== 0) {
  52822. this._height = value / Math.tan(this.angle / 2);
  52823. }
  52824. else {
  52825. this._height = 1;
  52826. }
  52827. },
  52828. enumerable: true,
  52829. configurable: true
  52830. });
  52831. /**
  52832. * Called by the particle System when the direction is computed for the created particle.
  52833. * @param emitPower is the power of the particle (speed)
  52834. * @param worldMatrix is the world matrix of the particle system
  52835. * @param directionToUpdate is the direction vector to update with the result
  52836. * @param particle is the particle we are computed the direction for
  52837. */
  52838. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52839. if (this.angle === 0) {
  52840. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52841. }
  52842. else {
  52843. // measure the direction Vector from the emitter to the particle.
  52844. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52845. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52846. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52847. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52848. direction.x += randX;
  52849. direction.y += randY;
  52850. direction.z += randZ;
  52851. direction.normalize();
  52852. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52853. }
  52854. };
  52855. /**
  52856. * Called by the particle System when the position is computed for the created particle.
  52857. * @param worldMatrix is the world matrix of the particle system
  52858. * @param positionToUpdate is the position vector to update with the result
  52859. * @param particle is the particle we are computed the position for
  52860. */
  52861. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52862. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52863. var h = BABYLON.Scalar.RandomRange(0, 1);
  52864. // Better distribution in a cone at normal angles.
  52865. h = 1 - h * h;
  52866. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52867. radius = radius * h;
  52868. var randX = radius * Math.sin(s);
  52869. var randZ = radius * Math.cos(s);
  52870. var randY = h * this._height;
  52871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52872. };
  52873. /**
  52874. * Clones the current emitter and returns a copy of it
  52875. * @returns the new emitter
  52876. */
  52877. ConeParticleEmitter.prototype.clone = function () {
  52878. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52879. BABYLON.Tools.DeepCopy(this, newOne);
  52880. return newOne;
  52881. };
  52882. /**
  52883. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52884. * @param effect defines the update shader
  52885. */
  52886. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52887. effect.setFloat("radius", this.radius);
  52888. effect.setFloat("angle", this.angle);
  52889. effect.setFloat("height", this._height);
  52890. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52891. };
  52892. /**
  52893. * Returns a string to use to update the GPU particles update shader
  52894. * @returns a string containng the defines string
  52895. */
  52896. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52897. return "#define CONEEMITTER";
  52898. };
  52899. /**
  52900. * Returns the string "BoxEmitter"
  52901. * @returns a string containing the class name
  52902. */
  52903. ConeParticleEmitter.prototype.getClassName = function () {
  52904. return "ConeEmitter";
  52905. };
  52906. /**
  52907. * Serializes the particle system to a JSON object.
  52908. * @returns the JSON object
  52909. */
  52910. ConeParticleEmitter.prototype.serialize = function () {
  52911. var serializationObject = {};
  52912. serializationObject.type = this.getClassName();
  52913. serializationObject.radius = this.radius;
  52914. serializationObject.angle = this.angle;
  52915. serializationObject.directionRandomizer = this.directionRandomizer;
  52916. return serializationObject;
  52917. };
  52918. /**
  52919. * Parse properties from a JSON object
  52920. * @param serializationObject defines the JSON object
  52921. */
  52922. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52923. this.radius = serializationObject.radius;
  52924. this.angle = serializationObject.angle;
  52925. this.directionRandomizer = serializationObject.directionRandomizer;
  52926. };
  52927. return ConeParticleEmitter;
  52928. }());
  52929. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52930. })(BABYLON || (BABYLON = {}));
  52931. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52932. "use strict";
  52933. var BABYLON;
  52934. (function (BABYLON) {
  52935. /**
  52936. * Particle emitter emitting particles from the inside of a sphere.
  52937. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52938. */
  52939. var SphereParticleEmitter = /** @class */ (function () {
  52940. /**
  52941. * Creates a new instance SphereParticleEmitter
  52942. * @param radius the radius of the emission sphere (1 by default)
  52943. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52944. */
  52945. function SphereParticleEmitter(
  52946. /**
  52947. * The radius of the emission sphere.
  52948. */
  52949. radius,
  52950. /**
  52951. * How much to randomize the particle direction [0-1].
  52952. */
  52953. directionRandomizer) {
  52954. if (radius === void 0) { radius = 1; }
  52955. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52956. this.radius = radius;
  52957. this.directionRandomizer = directionRandomizer;
  52958. }
  52959. /**
  52960. * Called by the particle System when the direction is computed for the created particle.
  52961. * @param emitPower is the power of the particle (speed)
  52962. * @param worldMatrix is the world matrix of the particle system
  52963. * @param directionToUpdate is the direction vector to update with the result
  52964. * @param particle is the particle we are computed the direction for
  52965. */
  52966. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52967. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52968. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52969. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52970. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52971. direction.x += randX;
  52972. direction.y += randY;
  52973. direction.z += randZ;
  52974. direction.normalize();
  52975. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52976. };
  52977. /**
  52978. * Called by the particle System when the position is computed for the created particle.
  52979. * @param worldMatrix is the world matrix of the particle system
  52980. * @param positionToUpdate is the position vector to update with the result
  52981. * @param particle is the particle we are computed the position for
  52982. */
  52983. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52984. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52985. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52986. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52987. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52988. var randY = randRadius * Math.cos(theta);
  52989. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52990. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52991. };
  52992. /**
  52993. * Clones the current emitter and returns a copy of it
  52994. * @returns the new emitter
  52995. */
  52996. SphereParticleEmitter.prototype.clone = function () {
  52997. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52998. BABYLON.Tools.DeepCopy(this, newOne);
  52999. return newOne;
  53000. };
  53001. /**
  53002. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53003. * @param effect defines the update shader
  53004. */
  53005. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  53006. effect.setFloat("radius", this.radius);
  53007. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53008. };
  53009. /**
  53010. * Returns a string to use to update the GPU particles update shader
  53011. * @returns a string containng the defines string
  53012. */
  53013. SphereParticleEmitter.prototype.getEffectDefines = function () {
  53014. return "#define SPHEREEMITTER";
  53015. };
  53016. /**
  53017. * Returns the string "SphereParticleEmitter"
  53018. * @returns a string containing the class name
  53019. */
  53020. SphereParticleEmitter.prototype.getClassName = function () {
  53021. return "SphereParticleEmitter";
  53022. };
  53023. /**
  53024. * Serializes the particle system to a JSON object.
  53025. * @returns the JSON object
  53026. */
  53027. SphereParticleEmitter.prototype.serialize = function () {
  53028. var serializationObject = {};
  53029. serializationObject.type = this.getClassName();
  53030. serializationObject.radius = this.radius;
  53031. serializationObject.directionRandomizer = this.directionRandomizer;
  53032. return serializationObject;
  53033. };
  53034. /**
  53035. * Parse properties from a JSON object
  53036. * @param serializationObject defines the JSON object
  53037. */
  53038. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  53039. this.radius = serializationObject.radius;
  53040. this.directionRandomizer = serializationObject.directionRandomizer;
  53041. };
  53042. return SphereParticleEmitter;
  53043. }());
  53044. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  53045. /**
  53046. * Particle emitter emitting particles from the inside of a sphere.
  53047. * It emits the particles randomly between two vectors.
  53048. */
  53049. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  53050. __extends(SphereDirectedParticleEmitter, _super);
  53051. /**
  53052. * Creates a new instance SphereDirectedParticleEmitter
  53053. * @param radius the radius of the emission sphere (1 by default)
  53054. * @param direction1 the min limit of the emission direction (up vector by default)
  53055. * @param direction2 the max limit of the emission direction (up vector by default)
  53056. */
  53057. function SphereDirectedParticleEmitter(radius,
  53058. /**
  53059. * The min limit of the emission direction.
  53060. */
  53061. direction1,
  53062. /**
  53063. * The max limit of the emission direction.
  53064. */
  53065. direction2) {
  53066. if (radius === void 0) { radius = 1; }
  53067. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  53068. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  53069. var _this = _super.call(this, radius) || this;
  53070. _this.direction1 = direction1;
  53071. _this.direction2 = direction2;
  53072. return _this;
  53073. }
  53074. /**
  53075. * Called by the particle System when the direction is computed for the created particle.
  53076. * @param emitPower is the power of the particle (speed)
  53077. * @param worldMatrix is the world matrix of the particle system
  53078. * @param directionToUpdate is the direction vector to update with the result
  53079. * @param particle is the particle we are computed the direction for
  53080. */
  53081. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53082. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53083. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53084. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53085. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53086. };
  53087. /**
  53088. * Clones the current emitter and returns a copy of it
  53089. * @returns the new emitter
  53090. */
  53091. SphereDirectedParticleEmitter.prototype.clone = function () {
  53092. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53093. BABYLON.Tools.DeepCopy(this, newOne);
  53094. return newOne;
  53095. };
  53096. /**
  53097. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53098. * @param effect defines the update shader
  53099. */
  53100. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53101. effect.setFloat("radius", this.radius);
  53102. effect.setVector3("direction1", this.direction1);
  53103. effect.setVector3("direction2", this.direction2);
  53104. };
  53105. /**
  53106. * Returns a string to use to update the GPU particles update shader
  53107. * @returns a string containng the defines string
  53108. */
  53109. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53110. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53111. };
  53112. /**
  53113. * Returns the string "SphereDirectedParticleEmitter"
  53114. * @returns a string containing the class name
  53115. */
  53116. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53117. return "SphereDirectedParticleEmitter";
  53118. };
  53119. /**
  53120. * Serializes the particle system to a JSON object.
  53121. * @returns the JSON object
  53122. */
  53123. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53124. var serializationObject = _super.prototype.serialize.call(this);
  53125. ;
  53126. serializationObject.direction1 = this.direction1.asArray();
  53127. ;
  53128. serializationObject.direction2 = this.direction2.asArray();
  53129. ;
  53130. return serializationObject;
  53131. };
  53132. /**
  53133. * Parse properties from a JSON object
  53134. * @param serializationObject defines the JSON object
  53135. */
  53136. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53137. _super.prototype.parse.call(this, serializationObject);
  53138. this.direction1.copyFrom(serializationObject.direction1);
  53139. this.direction2.copyFrom(serializationObject.direction2);
  53140. };
  53141. return SphereDirectedParticleEmitter;
  53142. }(SphereParticleEmitter));
  53143. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53144. })(BABYLON || (BABYLON = {}));
  53145. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53146. "use strict";
  53147. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53148. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53149. s = arguments[i];
  53150. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53151. t[p] = s[p];
  53152. }
  53153. return t;
  53154. };
  53155. var BABYLON;
  53156. (function (BABYLON) {
  53157. /**
  53158. * This represents a GPU particle system in Babylon
  53159. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53160. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53161. */
  53162. var GPUParticleSystem = /** @class */ (function () {
  53163. /**
  53164. * Instantiates a GPU particle system.
  53165. * 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.
  53166. * @param name The name of the particle system
  53167. * @param capacity The max number of particles alive at the same time
  53168. * @param scene The scene the particle system belongs to
  53169. */
  53170. function GPUParticleSystem(name, options, scene) {
  53171. /**
  53172. * The emitter represents the Mesh or position we are attaching the particle system to.
  53173. */
  53174. this.emitter = null;
  53175. /**
  53176. * The rendering group used by the Particle system to chose when to render.
  53177. */
  53178. this.renderingGroupId = 0;
  53179. /**
  53180. * The layer mask we are rendering the particles through.
  53181. */
  53182. this.layerMask = 0x0FFFFFFF;
  53183. this._targetIndex = 0;
  53184. this._currentRenderId = -1;
  53185. this._started = false;
  53186. this._stopped = false;
  53187. this._timeDelta = 0;
  53188. this._attributesStrideSize = 14;
  53189. this._actualFrame = 0;
  53190. /**
  53191. * List of animations used by the particle system.
  53192. */
  53193. this.animations = [];
  53194. /**
  53195. * An event triggered when the system is disposed.
  53196. */
  53197. this.onDisposeObservable = new BABYLON.Observable();
  53198. /**
  53199. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53200. */
  53201. this.updateSpeed = 0.01;
  53202. /**
  53203. * The amount of time the particle system is running (depends of the overall update speed).
  53204. */
  53205. this.targetStopDuration = 0;
  53206. /**
  53207. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53208. */
  53209. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53210. /**
  53211. * Minimum life time of emitting particles.
  53212. */
  53213. this.minLifeTime = 1;
  53214. /**
  53215. * Maximum life time of emitting particles.
  53216. */
  53217. this.maxLifeTime = 1;
  53218. /**
  53219. * Minimum Size of emitting particles.
  53220. */
  53221. this.minSize = 1;
  53222. /**
  53223. * Maximum Size of emitting particles.
  53224. */
  53225. this.maxSize = 1;
  53226. /**
  53227. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53228. */
  53229. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53230. /**
  53231. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53232. */
  53233. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53234. /**
  53235. * Color the particle will have at the end of its lifetime.
  53236. */
  53237. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53238. /**
  53239. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53240. */
  53241. this.emitRate = 100;
  53242. /**
  53243. * You can use gravity if you want to give an orientation to your particles.
  53244. */
  53245. this.gravity = BABYLON.Vector3.Zero();
  53246. /**
  53247. * Minimum power of emitting particles.
  53248. */
  53249. this.minEmitPower = 1;
  53250. /**
  53251. * Maximum power of emitting particles.
  53252. */
  53253. this.maxEmitPower = 1;
  53254. /**
  53255. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53256. * to override the particles.
  53257. */
  53258. this.forceDepthWrite = false;
  53259. this.id = name;
  53260. this.name = name;
  53261. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53262. this._engine = this._scene.getEngine();
  53263. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53264. this._capacity = fullOptions.capacity;
  53265. this._activeCount = fullOptions.capacity;
  53266. this._currentActiveCount = 0;
  53267. this._scene.particleSystems.push(this);
  53268. this._updateEffectOptions = {
  53269. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53270. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53271. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53272. uniformBuffersNames: [],
  53273. samplers: ["randomSampler"],
  53274. defines: "",
  53275. fallbacks: null,
  53276. onCompiled: null,
  53277. onError: null,
  53278. indexParameters: null,
  53279. maxSimultaneousLights: 0,
  53280. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53281. };
  53282. // Random data
  53283. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53284. var d = [];
  53285. for (var i = 0; i < maxTextureSize; ++i) {
  53286. d.push(Math.random());
  53287. d.push(Math.random());
  53288. d.push(Math.random());
  53289. d.push(Math.random());
  53290. }
  53291. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53292. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53293. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53294. this._randomTextureSize = maxTextureSize;
  53295. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53296. }
  53297. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53298. /**
  53299. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53300. */
  53301. get: function () {
  53302. if (!BABYLON.Engine.LastCreatedEngine) {
  53303. return false;
  53304. }
  53305. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53306. },
  53307. enumerable: true,
  53308. configurable: true
  53309. });
  53310. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53311. /**
  53312. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53313. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53314. */
  53315. get: function () {
  53316. if (this.particleEmitterType.direction1) {
  53317. return this.particleEmitterType.direction1;
  53318. }
  53319. return BABYLON.Vector3.Zero();
  53320. },
  53321. set: function (value) {
  53322. if (this.particleEmitterType.direction1) {
  53323. this.particleEmitterType.direction1 = value;
  53324. }
  53325. },
  53326. enumerable: true,
  53327. configurable: true
  53328. });
  53329. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53330. /**
  53331. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53332. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53333. */
  53334. get: function () {
  53335. if (this.particleEmitterType.direction2) {
  53336. return this.particleEmitterType.direction2;
  53337. }
  53338. return BABYLON.Vector3.Zero();
  53339. },
  53340. set: function (value) {
  53341. if (this.particleEmitterType.direction2) {
  53342. this.particleEmitterType.direction2 = value;
  53343. }
  53344. },
  53345. enumerable: true,
  53346. configurable: true
  53347. });
  53348. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53349. /**
  53350. * 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.
  53351. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53352. */
  53353. get: function () {
  53354. if (this.particleEmitterType.minEmitBox) {
  53355. return this.particleEmitterType.minEmitBox;
  53356. }
  53357. return BABYLON.Vector3.Zero();
  53358. },
  53359. set: function (value) {
  53360. if (this.particleEmitterType.minEmitBox) {
  53361. this.particleEmitterType.minEmitBox = value;
  53362. }
  53363. },
  53364. enumerable: true,
  53365. configurable: true
  53366. });
  53367. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53368. /**
  53369. * 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.
  53370. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53371. */
  53372. get: function () {
  53373. if (this.particleEmitterType.maxEmitBox) {
  53374. return this.particleEmitterType.maxEmitBox;
  53375. }
  53376. return BABYLON.Vector3.Zero();
  53377. },
  53378. set: function (value) {
  53379. if (this.particleEmitterType.maxEmitBox) {
  53380. this.particleEmitterType.maxEmitBox = value;
  53381. }
  53382. },
  53383. enumerable: true,
  53384. configurable: true
  53385. });
  53386. /**
  53387. * Gets the maximum number of particles active at the same time.
  53388. * @returns The max number of active particles.
  53389. */
  53390. GPUParticleSystem.prototype.getCapacity = function () {
  53391. return this._capacity;
  53392. };
  53393. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53394. /**
  53395. * Gets or set the number of active particles
  53396. */
  53397. get: function () {
  53398. return this._activeCount;
  53399. },
  53400. set: function (value) {
  53401. this._activeCount = Math.min(value, this._capacity);
  53402. },
  53403. enumerable: true,
  53404. configurable: true
  53405. });
  53406. /**
  53407. * Is this system ready to be used/rendered
  53408. * @return true if the system is ready
  53409. */
  53410. GPUParticleSystem.prototype.isReady = function () {
  53411. if (!this._updateEffect) {
  53412. this._recreateUpdateEffect();
  53413. this._recreateRenderEffect();
  53414. return false;
  53415. }
  53416. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53417. return false;
  53418. }
  53419. return true;
  53420. };
  53421. /**
  53422. * Gets Wether the system has been started.
  53423. * @returns True if it has been started, otherwise false.
  53424. */
  53425. GPUParticleSystem.prototype.isStarted = function () {
  53426. return this._started;
  53427. };
  53428. /**
  53429. * Starts the particle system and begins to emit.
  53430. */
  53431. GPUParticleSystem.prototype.start = function () {
  53432. this._started = true;
  53433. this._stopped = false;
  53434. };
  53435. /**
  53436. * Stops the particle system.
  53437. */
  53438. GPUParticleSystem.prototype.stop = function () {
  53439. this._stopped = true;
  53440. };
  53441. /**
  53442. * Remove all active particles
  53443. */
  53444. GPUParticleSystem.prototype.reset = function () {
  53445. this._releaseBuffers();
  53446. this._releaseVAOs();
  53447. this._currentActiveCount = 0;
  53448. this._targetIndex = 0;
  53449. };
  53450. /**
  53451. * Returns the string "GPUParticleSystem"
  53452. * @returns a string containing the class name
  53453. */
  53454. GPUParticleSystem.prototype.getClassName = function () {
  53455. return "GPUParticleSystem";
  53456. };
  53457. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53458. var updateVertexBuffers = {};
  53459. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53460. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53461. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53462. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53463. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53464. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53465. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53466. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53467. this._engine.bindArrayBuffer(null);
  53468. return vao;
  53469. };
  53470. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53471. var renderVertexBuffers = {};
  53472. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53473. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53474. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53475. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53476. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53477. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53478. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53479. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53480. this._engine.bindArrayBuffer(null);
  53481. return vao;
  53482. };
  53483. GPUParticleSystem.prototype._initialize = function (force) {
  53484. if (force === void 0) { force = false; }
  53485. if (this._buffer0 && !force) {
  53486. return;
  53487. }
  53488. var engine = this._scene.getEngine();
  53489. var data = new Array();
  53490. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53491. // position
  53492. data.push(0.0);
  53493. data.push(0.0);
  53494. data.push(0.0);
  53495. // Age and life
  53496. data.push(0.0); // create the particle as a dead one to create a new one at start
  53497. data.push(0.0);
  53498. // Seed
  53499. data.push(Math.random());
  53500. // Size
  53501. data.push(0.0);
  53502. // color
  53503. data.push(0.0);
  53504. data.push(0.0);
  53505. data.push(0.0);
  53506. data.push(0.0);
  53507. // direction
  53508. data.push(0.0);
  53509. data.push(0.0);
  53510. data.push(0.0);
  53511. }
  53512. // Sprite data
  53513. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53514. -0.5, 0.5, 0, 1,
  53515. -0.5, -0.5, 0, 0,
  53516. 0.5, -0.5, 1, 0]);
  53517. // Buffers
  53518. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53519. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53520. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53521. // Update VAO
  53522. this._updateVAO = [];
  53523. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53524. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53525. // Render VAO
  53526. this._renderVAO = [];
  53527. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53528. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53529. // Links
  53530. this._sourceBuffer = this._buffer0;
  53531. this._targetBuffer = this._buffer1;
  53532. };
  53533. /** @ignore */
  53534. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53535. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53536. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53537. return;
  53538. }
  53539. this._updateEffectOptions.defines = defines;
  53540. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53541. };
  53542. /** @ignore */
  53543. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53544. var defines = "";
  53545. if (this._scene.clipPlane) {
  53546. defines = "\n#define CLIPPLANE";
  53547. }
  53548. if (this._renderEffect && this._renderEffect.defines === defines) {
  53549. return;
  53550. }
  53551. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53552. };
  53553. /**
  53554. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53555. */
  53556. GPUParticleSystem.prototype.animate = function () {
  53557. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53558. this._actualFrame += this._timeDelta;
  53559. if (!this._stopped) {
  53560. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53561. this.stop();
  53562. }
  53563. }
  53564. };
  53565. /**
  53566. * Renders the particle system in its current state.
  53567. * @returns the current number of particles
  53568. */
  53569. GPUParticleSystem.prototype.render = function () {
  53570. if (!this._started) {
  53571. return 0;
  53572. }
  53573. this._recreateUpdateEffect();
  53574. this._recreateRenderEffect();
  53575. if (!this.isReady()) {
  53576. return 0;
  53577. }
  53578. if (this._currentRenderId === this._scene.getRenderId()) {
  53579. return 0;
  53580. }
  53581. this._currentRenderId = this._scene.getRenderId();
  53582. // Get everything ready to render
  53583. this._initialize();
  53584. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53585. // Enable update effect
  53586. this._engine.enableEffect(this._updateEffect);
  53587. this._engine.setState(false);
  53588. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53589. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53590. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53591. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53592. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53593. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53594. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53595. this._updateEffect.setDirectColor4("color1", this.color1);
  53596. this._updateEffect.setDirectColor4("color2", this.color2);
  53597. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53598. this._updateEffect.setVector3("gravity", this.gravity);
  53599. if (this.particleEmitterType) {
  53600. this.particleEmitterType.applyToShader(this._updateEffect);
  53601. }
  53602. var emitterWM;
  53603. if (this.emitter.position) {
  53604. var emitterMesh = this.emitter;
  53605. emitterWM = emitterMesh.getWorldMatrix();
  53606. }
  53607. else {
  53608. var emitterPosition = this.emitter;
  53609. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53610. }
  53611. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53612. // Bind source VAO
  53613. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53614. // Update
  53615. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53616. this._engine.setRasterizerState(false);
  53617. this._engine.beginTransformFeedback();
  53618. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53619. this._engine.endTransformFeedback();
  53620. this._engine.setRasterizerState(true);
  53621. this._engine.bindTransformFeedbackBuffer(null);
  53622. // Enable render effect
  53623. this._engine.enableEffect(this._renderEffect);
  53624. var viewMatrix = this._scene.getViewMatrix();
  53625. this._renderEffect.setMatrix("view", viewMatrix);
  53626. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53627. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53628. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53629. if (this._scene.clipPlane) {
  53630. var clipPlane = this._scene.clipPlane;
  53631. var invView = viewMatrix.clone();
  53632. invView.invert();
  53633. this._renderEffect.setMatrix("invView", invView);
  53634. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53635. }
  53636. // Draw order
  53637. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53638. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53639. }
  53640. else {
  53641. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53642. }
  53643. if (this.forceDepthWrite) {
  53644. this._engine.setDepthWrite(true);
  53645. }
  53646. // Bind source VAO
  53647. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53648. // Render
  53649. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53650. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53651. // Switch VAOs
  53652. this._targetIndex++;
  53653. if (this._targetIndex === 2) {
  53654. this._targetIndex = 0;
  53655. }
  53656. // Switch buffers
  53657. var tmpBuffer = this._sourceBuffer;
  53658. this._sourceBuffer = this._targetBuffer;
  53659. this._targetBuffer = tmpBuffer;
  53660. return this._currentActiveCount;
  53661. };
  53662. /**
  53663. * Rebuilds the particle system
  53664. */
  53665. GPUParticleSystem.prototype.rebuild = function () {
  53666. this._initialize(true);
  53667. };
  53668. GPUParticleSystem.prototype._releaseBuffers = function () {
  53669. if (this._buffer0) {
  53670. this._buffer0.dispose();
  53671. this._buffer0 = null;
  53672. }
  53673. if (this._buffer1) {
  53674. this._buffer1.dispose();
  53675. this._buffer1 = null;
  53676. }
  53677. if (this._spriteBuffer) {
  53678. this._spriteBuffer.dispose();
  53679. this._spriteBuffer = null;
  53680. }
  53681. };
  53682. GPUParticleSystem.prototype._releaseVAOs = function () {
  53683. if (!this._updateVAO) {
  53684. return;
  53685. }
  53686. for (var index = 0; index < this._updateVAO.length; index++) {
  53687. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53688. }
  53689. this._updateVAO = [];
  53690. for (var index = 0; index < this._renderVAO.length; index++) {
  53691. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53692. }
  53693. this._renderVAO = [];
  53694. };
  53695. /**
  53696. * Disposes the particle system and free the associated resources
  53697. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53698. */
  53699. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53700. if (disposeTexture === void 0) { disposeTexture = true; }
  53701. var index = this._scene.particleSystems.indexOf(this);
  53702. if (index > -1) {
  53703. this._scene.particleSystems.splice(index, 1);
  53704. }
  53705. this._releaseBuffers();
  53706. this._releaseVAOs();
  53707. if (this._randomTexture) {
  53708. this._randomTexture.dispose();
  53709. this._randomTexture = null;
  53710. }
  53711. if (disposeTexture && this.particleTexture) {
  53712. this.particleTexture.dispose();
  53713. this.particleTexture = null;
  53714. }
  53715. // Callback
  53716. this.onDisposeObservable.notifyObservers(this);
  53717. this.onDisposeObservable.clear();
  53718. };
  53719. /**
  53720. * Clones the particle system.
  53721. * @param name The name of the cloned object
  53722. * @param newEmitter The new emitter to use
  53723. * @returns the cloned particle system
  53724. */
  53725. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53726. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53727. BABYLON.Tools.DeepCopy(this, result);
  53728. if (newEmitter === undefined) {
  53729. newEmitter = this.emitter;
  53730. }
  53731. result.emitter = newEmitter;
  53732. if (this.particleTexture) {
  53733. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53734. }
  53735. return result;
  53736. };
  53737. /**
  53738. * Serializes the particle system to a JSON object.
  53739. * @returns the JSON object
  53740. */
  53741. GPUParticleSystem.prototype.serialize = function () {
  53742. var serializationObject = {};
  53743. serializationObject.name = this.name;
  53744. serializationObject.id = this.id;
  53745. // Emitter
  53746. if (this.emitter.position) {
  53747. var emitterMesh = this.emitter;
  53748. serializationObject.emitterId = emitterMesh.id;
  53749. }
  53750. else {
  53751. var emitterPosition = this.emitter;
  53752. serializationObject.emitter = emitterPosition.asArray();
  53753. }
  53754. serializationObject.capacity = this.getCapacity();
  53755. if (this.particleTexture) {
  53756. serializationObject.textureName = this.particleTexture.name;
  53757. }
  53758. // Animations
  53759. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53760. // Particle system
  53761. serializationObject.activeParticleCount = this.activeParticleCount;
  53762. serializationObject.randomTextureSize = this._randomTextureSize;
  53763. serializationObject.minSize = this.minSize;
  53764. serializationObject.maxSize = this.maxSize;
  53765. serializationObject.minEmitPower = this.minEmitPower;
  53766. serializationObject.maxEmitPower = this.maxEmitPower;
  53767. serializationObject.minLifeTime = this.minLifeTime;
  53768. serializationObject.maxLifeTime = this.maxLifeTime;
  53769. serializationObject.emitRate = this.emitRate;
  53770. serializationObject.gravity = this.gravity.asArray();
  53771. serializationObject.color1 = this.color1.asArray();
  53772. serializationObject.color2 = this.color2.asArray();
  53773. serializationObject.colorDead = this.colorDead.asArray();
  53774. serializationObject.updateSpeed = this.updateSpeed;
  53775. serializationObject.targetStopDuration = this.targetStopDuration;
  53776. serializationObject.blendMode = this.blendMode;
  53777. // Emitter
  53778. if (this.particleEmitterType) {
  53779. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53780. }
  53781. return serializationObject;
  53782. };
  53783. /**
  53784. * Parses a JSON object to create a GPU particle system.
  53785. * @param parsedParticleSystem The JSON object to parse
  53786. * @param scene The scene to create the particle system in
  53787. * @param rootUrl The root url to use to load external dependencies like texture
  53788. * @returns the parsed GPU particle system
  53789. */
  53790. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53791. var name = parsedParticleSystem.name;
  53792. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53793. if (parsedParticleSystem.id) {
  53794. particleSystem.id = parsedParticleSystem.id;
  53795. }
  53796. // Texture
  53797. if (parsedParticleSystem.textureName) {
  53798. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53799. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53800. }
  53801. // Emitter
  53802. if (parsedParticleSystem.emitterId) {
  53803. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53804. }
  53805. else {
  53806. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53807. }
  53808. // Animations
  53809. if (parsedParticleSystem.animations) {
  53810. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53811. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53812. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53813. }
  53814. }
  53815. // Particle system
  53816. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53817. particleSystem.minSize = parsedParticleSystem.minSize;
  53818. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53819. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53820. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53821. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53822. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53823. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53824. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53825. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53826. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53827. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53828. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53829. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53830. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53831. // Emitter
  53832. if (parsedParticleSystem.particleEmitterType) {
  53833. var emitterType = void 0;
  53834. switch (parsedParticleSystem.particleEmitterType.type) {
  53835. case "SphereEmitter":
  53836. emitterType = new BABYLON.SphereParticleEmitter();
  53837. break;
  53838. case "SphereDirectedParticleEmitter":
  53839. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53840. break;
  53841. case "ConeEmitter":
  53842. emitterType = new BABYLON.ConeParticleEmitter();
  53843. break;
  53844. case "BoxEmitter":
  53845. default:
  53846. emitterType = new BABYLON.BoxParticleEmitter();
  53847. break;
  53848. }
  53849. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53850. particleSystem.particleEmitterType = emitterType;
  53851. }
  53852. return particleSystem;
  53853. };
  53854. return GPUParticleSystem;
  53855. }());
  53856. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53857. })(BABYLON || (BABYLON = {}));
  53858. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53859. "use strict";
  53860. var BABYLON;
  53861. (function (BABYLON) {
  53862. /**
  53863. * Represents one particle of a solid particle system.
  53864. */
  53865. var SolidParticle = /** @class */ (function () {
  53866. /**
  53867. * Creates a Solid Particle object.
  53868. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53869. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53870. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53871. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53872. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53873. * @param shapeId (integer) is the model shape identifier in the SPS.
  53874. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53875. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53876. */
  53877. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53878. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53879. /**
  53880. * particle global index
  53881. */
  53882. this.idx = 0;
  53883. /**
  53884. * The color of the particle
  53885. */
  53886. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53887. /**
  53888. * The world space position of the particle.
  53889. */
  53890. this.position = BABYLON.Vector3.Zero();
  53891. /**
  53892. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53893. */
  53894. this.rotation = BABYLON.Vector3.Zero();
  53895. /**
  53896. * The scaling of the particle.
  53897. */
  53898. this.scaling = BABYLON.Vector3.One();
  53899. /**
  53900. * The uvs of the particle.
  53901. */
  53902. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53903. /**
  53904. * The current speed of the particle.
  53905. */
  53906. this.velocity = BABYLON.Vector3.Zero();
  53907. /**
  53908. * The pivot point in the particle local space.
  53909. */
  53910. this.pivot = BABYLON.Vector3.Zero();
  53911. /**
  53912. * Must the particle be translated from its pivot point in its local space ?
  53913. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53914. * Default : false
  53915. */
  53916. this.translateFromPivot = false;
  53917. /**
  53918. * Is the particle active or not ?
  53919. */
  53920. this.alive = true;
  53921. /**
  53922. * Is the particle visible or not ?
  53923. */
  53924. this.isVisible = true;
  53925. /**
  53926. * Index of this particle in the global "positions" array (Internal use)
  53927. */
  53928. this._pos = 0;
  53929. /**
  53930. * Index of this particle in the global "indices" array (Internal use)
  53931. */
  53932. this._ind = 0;
  53933. /**
  53934. * ModelShape id of this particle
  53935. */
  53936. this.shapeId = 0;
  53937. /**
  53938. * Index of the particle in its shape id (Internal use)
  53939. */
  53940. this.idxInShape = 0;
  53941. /**
  53942. * Still set as invisible in order to skip useless computations (Internal use)
  53943. */
  53944. this._stillInvisible = false;
  53945. /**
  53946. * Last computed particle rotation matrix
  53947. */
  53948. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53949. /**
  53950. * Parent particle Id, if any.
  53951. * Default null.
  53952. */
  53953. this.parentId = null;
  53954. /**
  53955. * Internal global position in the SPS.
  53956. */
  53957. this._globalPosition = BABYLON.Vector3.Zero();
  53958. this.idx = particleIndex;
  53959. this._pos = positionIndex;
  53960. this._ind = indiceIndex;
  53961. this._model = model;
  53962. this.shapeId = shapeId;
  53963. this.idxInShape = idxInShape;
  53964. this._sps = sps;
  53965. if (modelBoundingInfo) {
  53966. this._modelBoundingInfo = modelBoundingInfo;
  53967. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53968. }
  53969. }
  53970. Object.defineProperty(SolidParticle.prototype, "scale", {
  53971. /**
  53972. * Legacy support, changed scale to scaling
  53973. */
  53974. get: function () {
  53975. return this.scaling;
  53976. },
  53977. /**
  53978. * Legacy support, changed scale to scaling
  53979. */
  53980. set: function (scale) {
  53981. this.scaling = scale;
  53982. },
  53983. enumerable: true,
  53984. configurable: true
  53985. });
  53986. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53987. /**
  53988. * Legacy support, changed quaternion to rotationQuaternion
  53989. */
  53990. get: function () {
  53991. return this.rotationQuaternion;
  53992. },
  53993. /**
  53994. * Legacy support, changed quaternion to rotationQuaternion
  53995. */
  53996. set: function (q) {
  53997. this.rotationQuaternion = q;
  53998. },
  53999. enumerable: true,
  54000. configurable: true
  54001. });
  54002. /**
  54003. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54004. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54005. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  54006. * @returns true if it intersects
  54007. */
  54008. SolidParticle.prototype.intersectsMesh = function (target) {
  54009. if (!this._boundingInfo || !target._boundingInfo) {
  54010. return false;
  54011. }
  54012. if (this._sps._bSphereOnly) {
  54013. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54014. }
  54015. return this._boundingInfo.intersects(target._boundingInfo, false);
  54016. };
  54017. return SolidParticle;
  54018. }());
  54019. BABYLON.SolidParticle = SolidParticle;
  54020. /**
  54021. * Represents the shape of the model used by one particle of a solid particle system.
  54022. * SPS internal tool, don't use it manually.
  54023. */
  54024. var ModelShape = /** @class */ (function () {
  54025. /**
  54026. * 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.
  54027. * SPS internal tool, don't use it manually.
  54028. * @ignore
  54029. */
  54030. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  54031. /**
  54032. * length of the shape in the model indices array (internal use)
  54033. */
  54034. this._indicesLength = 0;
  54035. this.shapeID = id;
  54036. this._shape = shape;
  54037. this._indicesLength = indicesLength;
  54038. this._shapeUV = shapeUV;
  54039. this._positionFunction = posFunction;
  54040. this._vertexFunction = vtxFunction;
  54041. }
  54042. return ModelShape;
  54043. }());
  54044. BABYLON.ModelShape = ModelShape;
  54045. /**
  54046. * Represents a Depth Sorted Particle in the solid particle system.
  54047. */
  54048. var DepthSortedParticle = /** @class */ (function () {
  54049. function DepthSortedParticle() {
  54050. /**
  54051. * Index of the particle in the "indices" array
  54052. */
  54053. this.ind = 0;
  54054. /**
  54055. * Length of the particle shape in the "indices" array
  54056. */
  54057. this.indicesLength = 0;
  54058. /**
  54059. * Squared distance from the particle to the camera
  54060. */
  54061. this.sqDistance = 0.0;
  54062. }
  54063. return DepthSortedParticle;
  54064. }());
  54065. BABYLON.DepthSortedParticle = DepthSortedParticle;
  54066. })(BABYLON || (BABYLON = {}));
  54067. //# sourceMappingURL=babylon.solidParticle.js.map
  54068. "use strict";
  54069. var BABYLON;
  54070. (function (BABYLON) {
  54071. /**
  54072. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  54073. *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.
  54074. * The SPS is also a particle system. It provides some methods to manage the particles.
  54075. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  54076. *
  54077. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54078. */
  54079. var SolidParticleSystem = /** @class */ (function () {
  54080. /**
  54081. * Creates a SPS (Solid Particle System) object.
  54082. * @param name (String) is the SPS name, this will be the underlying mesh name.
  54083. * @param scene (Scene) is the scene in which the SPS is added.
  54084. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54085. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54086. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54087. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54088. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54089. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54090. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54091. */
  54092. function SolidParticleSystem(name, scene, options) {
  54093. /**
  54094. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54095. * Example : var p = SPS.particles[i];
  54096. */
  54097. this.particles = new Array();
  54098. /**
  54099. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54100. */
  54101. this.nbParticles = 0;
  54102. /**
  54103. * If the particles must ever face the camera (default false). Useful for planar particles.
  54104. */
  54105. this.billboard = false;
  54106. /**
  54107. * Recompute normals when adding a shape
  54108. */
  54109. this.recomputeNormals = true;
  54110. /**
  54111. * This a counter ofr your own usage. It's not set by any SPS functions.
  54112. */
  54113. this.counter = 0;
  54114. /**
  54115. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54116. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54117. */
  54118. this.vars = {};
  54119. /**
  54120. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54121. */
  54122. this._bSphereOnly = false;
  54123. /**
  54124. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54125. */
  54126. this._bSphereRadiusFactor = 1.0;
  54127. this._positions = new Array();
  54128. this._indices = new Array();
  54129. this._normals = new Array();
  54130. this._colors = new Array();
  54131. this._uvs = new Array();
  54132. this._index = 0; // indices index
  54133. this._updatable = true;
  54134. this._pickable = false;
  54135. this._isVisibilityBoxLocked = false;
  54136. this._alwaysVisible = false;
  54137. this._depthSort = false;
  54138. this._shapeCounter = 0;
  54139. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54140. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54141. this._computeParticleColor = true;
  54142. this._computeParticleTexture = true;
  54143. this._computeParticleRotation = true;
  54144. this._computeParticleVertex = false;
  54145. this._computeBoundingBox = false;
  54146. this._depthSortParticles = true;
  54147. this._cam_axisZ = BABYLON.Vector3.Zero();
  54148. this._cam_axisY = BABYLON.Vector3.Zero();
  54149. this._cam_axisX = BABYLON.Vector3.Zero();
  54150. this._axisZ = BABYLON.Axis.Z;
  54151. this._camDir = BABYLON.Vector3.Zero();
  54152. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54153. this._rotMatrix = new BABYLON.Matrix();
  54154. this._invertMatrix = new BABYLON.Matrix();
  54155. this._rotated = BABYLON.Vector3.Zero();
  54156. this._quaternion = new BABYLON.Quaternion();
  54157. this._vertex = BABYLON.Vector3.Zero();
  54158. this._normal = BABYLON.Vector3.Zero();
  54159. this._yaw = 0.0;
  54160. this._pitch = 0.0;
  54161. this._roll = 0.0;
  54162. this._halfroll = 0.0;
  54163. this._halfpitch = 0.0;
  54164. this._halfyaw = 0.0;
  54165. this._sinRoll = 0.0;
  54166. this._cosRoll = 0.0;
  54167. this._sinPitch = 0.0;
  54168. this._cosPitch = 0.0;
  54169. this._sinYaw = 0.0;
  54170. this._cosYaw = 0.0;
  54171. this._mustUnrotateFixedNormals = false;
  54172. this._minimum = BABYLON.Vector3.Zero();
  54173. this._maximum = BABYLON.Vector3.Zero();
  54174. this._minBbox = BABYLON.Vector3.Zero();
  54175. this._maxBbox = BABYLON.Vector3.Zero();
  54176. this._particlesIntersect = false;
  54177. this._depthSortFunction = function (p1, p2) {
  54178. return (p2.sqDistance - p1.sqDistance);
  54179. };
  54180. this._needs32Bits = false;
  54181. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54182. this._scaledPivot = BABYLON.Vector3.Zero();
  54183. this._particleHasParent = false;
  54184. this.name = name;
  54185. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54186. this._camera = scene.activeCamera;
  54187. this._pickable = options ? options.isPickable : false;
  54188. this._depthSort = options ? options.enableDepthSort : false;
  54189. this._particlesIntersect = options ? options.particleIntersection : false;
  54190. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54191. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54192. if (options && options.updatable) {
  54193. this._updatable = options.updatable;
  54194. }
  54195. else {
  54196. this._updatable = true;
  54197. }
  54198. if (this._pickable) {
  54199. this.pickedParticles = [];
  54200. }
  54201. if (this._depthSort) {
  54202. this.depthSortedParticles = [];
  54203. }
  54204. }
  54205. /**
  54206. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54207. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54208. * @returns the created mesh
  54209. */
  54210. SolidParticleSystem.prototype.buildMesh = function () {
  54211. if (this.nbParticles === 0) {
  54212. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54213. this.addShape(triangle, 1);
  54214. triangle.dispose();
  54215. }
  54216. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54217. this._positions32 = new Float32Array(this._positions);
  54218. this._uvs32 = new Float32Array(this._uvs);
  54219. this._colors32 = new Float32Array(this._colors);
  54220. if (this.recomputeNormals) {
  54221. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54222. }
  54223. this._normals32 = new Float32Array(this._normals);
  54224. this._fixedNormal32 = new Float32Array(this._normals);
  54225. if (this._mustUnrotateFixedNormals) {
  54226. this._unrotateFixedNormals();
  54227. }
  54228. var vertexData = new BABYLON.VertexData();
  54229. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54230. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54231. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54232. if (this._uvs32) {
  54233. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54234. ;
  54235. }
  54236. if (this._colors32) {
  54237. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54238. }
  54239. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54240. vertexData.applyToMesh(mesh, this._updatable);
  54241. this.mesh = mesh;
  54242. this.mesh.isPickable = this._pickable;
  54243. // free memory
  54244. if (!this._depthSort) {
  54245. this._indices = null;
  54246. }
  54247. this._positions = null;
  54248. this._normals = null;
  54249. this._uvs = null;
  54250. this._colors = null;
  54251. if (!this._updatable) {
  54252. this.particles.length = 0;
  54253. }
  54254. return mesh;
  54255. };
  54256. /**
  54257. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54258. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54259. * Thus the particles generated from `digest()` have their property `position` set yet.
  54260. * @param mesh ( Mesh ) is the mesh to be digested
  54261. * @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
  54262. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54263. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54264. * @returns the current SPS
  54265. */
  54266. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54267. var size = (options && options.facetNb) || 1;
  54268. var number = (options && options.number) || 0;
  54269. var delta = (options && options.delta) || 0;
  54270. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54271. var meshInd = mesh.getIndices();
  54272. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54273. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54274. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54275. var f = 0; // facet counter
  54276. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54277. // compute size from number
  54278. if (number) {
  54279. number = (number > totalFacets) ? totalFacets : number;
  54280. size = Math.round(totalFacets / number);
  54281. delta = 0;
  54282. }
  54283. else {
  54284. size = (size > totalFacets) ? totalFacets : size;
  54285. }
  54286. var facetPos = []; // submesh positions
  54287. var facetInd = []; // submesh indices
  54288. var facetUV = []; // submesh UV
  54289. var facetCol = []; // submesh colors
  54290. var barycenter = BABYLON.Vector3.Zero();
  54291. var sizeO = size;
  54292. while (f < totalFacets) {
  54293. size = sizeO + Math.floor((1 + delta) * Math.random());
  54294. if (f > totalFacets - size) {
  54295. size = totalFacets - f;
  54296. }
  54297. // reset temp arrays
  54298. facetPos.length = 0;
  54299. facetInd.length = 0;
  54300. facetUV.length = 0;
  54301. facetCol.length = 0;
  54302. // iterate over "size" facets
  54303. var fi = 0;
  54304. for (var j = f * 3; j < (f + size) * 3; j++) {
  54305. facetInd.push(fi);
  54306. var i = meshInd[j];
  54307. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54308. if (meshUV) {
  54309. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54310. }
  54311. if (meshCol) {
  54312. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54313. }
  54314. fi++;
  54315. }
  54316. // create a model shape for each single particle
  54317. var idx = this.nbParticles;
  54318. var shape = this._posToShape(facetPos);
  54319. var shapeUV = this._uvsToShapeUV(facetUV);
  54320. // compute the barycenter of the shape
  54321. var v;
  54322. for (v = 0; v < shape.length; v++) {
  54323. barycenter.addInPlace(shape[v]);
  54324. }
  54325. barycenter.scaleInPlace(1 / shape.length);
  54326. // shift the shape from its barycenter to the origin
  54327. for (v = 0; v < shape.length; v++) {
  54328. shape[v].subtractInPlace(barycenter);
  54329. }
  54330. var bInfo;
  54331. if (this._particlesIntersect) {
  54332. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54333. }
  54334. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54335. // add the particle in the SPS
  54336. var currentPos = this._positions.length;
  54337. var currentInd = this._indices.length;
  54338. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54339. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54340. // initialize the particle position
  54341. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54342. this._index += shape.length;
  54343. idx++;
  54344. this.nbParticles++;
  54345. this._shapeCounter++;
  54346. f += size;
  54347. }
  54348. return this;
  54349. };
  54350. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54351. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54352. var index = 0;
  54353. var idx = 0;
  54354. for (var p = 0; p < this.particles.length; p++) {
  54355. this._particle = this.particles[p];
  54356. this._shape = this._particle._model._shape;
  54357. if (this._particle.rotationQuaternion) {
  54358. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54359. }
  54360. else {
  54361. this._yaw = this._particle.rotation.y;
  54362. this._pitch = this._particle.rotation.x;
  54363. this._roll = this._particle.rotation.z;
  54364. this._quaternionRotationYPR();
  54365. }
  54366. this._quaternionToRotationMatrix();
  54367. this._rotMatrix.invertToRef(this._invertMatrix);
  54368. for (var pt = 0; pt < this._shape.length; pt++) {
  54369. idx = index + pt * 3;
  54370. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54371. this._fixedNormal32[idx] = this._normal.x;
  54372. this._fixedNormal32[idx + 1] = this._normal.y;
  54373. this._fixedNormal32[idx + 2] = this._normal.z;
  54374. }
  54375. index = idx + 3;
  54376. }
  54377. };
  54378. //reset copy
  54379. SolidParticleSystem.prototype._resetCopy = function () {
  54380. this._copy.position.x = 0;
  54381. this._copy.position.y = 0;
  54382. this._copy.position.z = 0;
  54383. this._copy.rotation.x = 0;
  54384. this._copy.rotation.y = 0;
  54385. this._copy.rotation.z = 0;
  54386. this._copy.rotationQuaternion = null;
  54387. this._copy.scaling.x = 1.0;
  54388. this._copy.scaling.y = 1.0;
  54389. this._copy.scaling.z = 1.0;
  54390. this._copy.uvs.x = 0;
  54391. this._copy.uvs.y = 0;
  54392. this._copy.uvs.z = 1.0;
  54393. this._copy.uvs.w = 1.0;
  54394. this._copy.color = null;
  54395. this._copy.translateFromPivot = false;
  54396. };
  54397. // _meshBuilder : inserts the shape model in the global SPS mesh
  54398. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54399. var i;
  54400. var u = 0;
  54401. var c = 0;
  54402. var n = 0;
  54403. this._resetCopy();
  54404. if (options && options.positionFunction) {
  54405. options.positionFunction(this._copy, idx, idxInShape);
  54406. this._mustUnrotateFixedNormals = true;
  54407. }
  54408. if (this._copy.rotationQuaternion) {
  54409. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54410. }
  54411. else {
  54412. this._yaw = this._copy.rotation.y;
  54413. this._pitch = this._copy.rotation.x;
  54414. this._roll = this._copy.rotation.z;
  54415. this._quaternionRotationYPR();
  54416. }
  54417. this._quaternionToRotationMatrix();
  54418. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54419. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54420. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54421. if (this._copy.translateFromPivot) {
  54422. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54423. }
  54424. else {
  54425. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54426. }
  54427. for (i = 0; i < shape.length; i++) {
  54428. this._vertex.x = shape[i].x;
  54429. this._vertex.y = shape[i].y;
  54430. this._vertex.z = shape[i].z;
  54431. if (options && options.vertexFunction) {
  54432. options.vertexFunction(this._copy, this._vertex, i);
  54433. }
  54434. this._vertex.x *= this._copy.scaling.x;
  54435. this._vertex.y *= this._copy.scaling.y;
  54436. this._vertex.z *= this._copy.scaling.z;
  54437. this._vertex.x -= this._scaledPivot.x;
  54438. this._vertex.y -= this._scaledPivot.y;
  54439. this._vertex.z -= this._scaledPivot.z;
  54440. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54441. this._rotated.addInPlace(this._pivotBackTranslation);
  54442. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54443. if (meshUV) {
  54444. 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);
  54445. u += 2;
  54446. }
  54447. if (this._copy.color) {
  54448. this._color = this._copy.color;
  54449. }
  54450. else if (meshCol && meshCol[c] !== undefined) {
  54451. this._color.r = meshCol[c];
  54452. this._color.g = meshCol[c + 1];
  54453. this._color.b = meshCol[c + 2];
  54454. this._color.a = meshCol[c + 3];
  54455. }
  54456. else {
  54457. this._color.r = 1.0;
  54458. this._color.g = 1.0;
  54459. this._color.b = 1.0;
  54460. this._color.a = 1.0;
  54461. }
  54462. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54463. c += 4;
  54464. if (!this.recomputeNormals && meshNor) {
  54465. this._normal.x = meshNor[n];
  54466. this._normal.y = meshNor[n + 1];
  54467. this._normal.z = meshNor[n + 2];
  54468. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54469. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54470. n += 3;
  54471. }
  54472. }
  54473. for (i = 0; i < meshInd.length; i++) {
  54474. var current_ind = p + meshInd[i];
  54475. indices.push(current_ind);
  54476. if (current_ind > 65535) {
  54477. this._needs32Bits = true;
  54478. }
  54479. }
  54480. if (this._pickable) {
  54481. var nbfaces = meshInd.length / 3;
  54482. for (i = 0; i < nbfaces; i++) {
  54483. this.pickedParticles.push({ idx: idx, faceId: i });
  54484. }
  54485. }
  54486. if (this._depthSort) {
  54487. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54488. }
  54489. return this._copy;
  54490. };
  54491. // returns a shape array from positions array
  54492. SolidParticleSystem.prototype._posToShape = function (positions) {
  54493. var shape = [];
  54494. for (var i = 0; i < positions.length; i += 3) {
  54495. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54496. }
  54497. return shape;
  54498. };
  54499. // returns a shapeUV array from a Vector4 uvs
  54500. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54501. var shapeUV = [];
  54502. if (uvs) {
  54503. for (var i = 0; i < uvs.length; i++)
  54504. shapeUV.push(uvs[i]);
  54505. }
  54506. return shapeUV;
  54507. };
  54508. // adds a new particle object in the particles array
  54509. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54510. if (bInfo === void 0) { bInfo = null; }
  54511. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54512. this.particles.push(sp);
  54513. return sp;
  54514. };
  54515. /**
  54516. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54517. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54518. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54519. * @param nb (positive integer) the number of particles to be created from this model
  54520. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54521. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54522. * @returns the number of shapes in the system
  54523. */
  54524. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54525. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54526. var meshInd = mesh.getIndices();
  54527. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54528. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54529. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54530. var bbInfo;
  54531. if (this._particlesIntersect) {
  54532. bbInfo = mesh.getBoundingInfo();
  54533. }
  54534. var shape = this._posToShape(meshPos);
  54535. var shapeUV = this._uvsToShapeUV(meshUV);
  54536. var posfunc = options ? options.positionFunction : null;
  54537. var vtxfunc = options ? options.vertexFunction : null;
  54538. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54539. // particles
  54540. var sp;
  54541. var currentCopy;
  54542. var idx = this.nbParticles;
  54543. for (var i = 0; i < nb; i++) {
  54544. var currentPos = this._positions.length;
  54545. var currentInd = this._indices.length;
  54546. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54547. if (this._updatable) {
  54548. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54549. sp.position.copyFrom(currentCopy.position);
  54550. sp.rotation.copyFrom(currentCopy.rotation);
  54551. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54552. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54553. }
  54554. if (currentCopy.color && sp.color) {
  54555. sp.color.copyFrom(currentCopy.color);
  54556. }
  54557. sp.scaling.copyFrom(currentCopy.scaling);
  54558. sp.uvs.copyFrom(currentCopy.uvs);
  54559. }
  54560. this._index += shape.length;
  54561. idx++;
  54562. }
  54563. this.nbParticles += nb;
  54564. this._shapeCounter++;
  54565. return this._shapeCounter - 1;
  54566. };
  54567. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54568. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54569. this._resetCopy();
  54570. if (particle._model._positionFunction) {
  54571. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54572. }
  54573. if (this._copy.rotationQuaternion) {
  54574. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54575. }
  54576. else {
  54577. this._yaw = this._copy.rotation.y;
  54578. this._pitch = this._copy.rotation.x;
  54579. this._roll = this._copy.rotation.z;
  54580. this._quaternionRotationYPR();
  54581. }
  54582. this._quaternionToRotationMatrix();
  54583. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54584. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54585. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54586. if (this._copy.translateFromPivot) {
  54587. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54588. }
  54589. else {
  54590. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54591. }
  54592. this._shape = particle._model._shape;
  54593. for (var pt = 0; pt < this._shape.length; pt++) {
  54594. this._vertex.x = this._shape[pt].x;
  54595. this._vertex.y = this._shape[pt].y;
  54596. this._vertex.z = this._shape[pt].z;
  54597. if (particle._model._vertexFunction) {
  54598. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54599. }
  54600. this._vertex.x *= this._copy.scaling.x;
  54601. this._vertex.y *= this._copy.scaling.y;
  54602. this._vertex.z *= this._copy.scaling.z;
  54603. this._vertex.x -= this._scaledPivot.x;
  54604. this._vertex.y -= this._scaledPivot.y;
  54605. this._vertex.z -= this._scaledPivot.z;
  54606. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54607. this._rotated.addInPlace(this._pivotBackTranslation);
  54608. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54609. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54610. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54611. }
  54612. particle.position.x = 0.0;
  54613. particle.position.y = 0.0;
  54614. particle.position.z = 0.0;
  54615. particle.rotation.x = 0.0;
  54616. particle.rotation.y = 0.0;
  54617. particle.rotation.z = 0.0;
  54618. particle.rotationQuaternion = null;
  54619. particle.scaling.x = 1.0;
  54620. particle.scaling.y = 1.0;
  54621. particle.scaling.z = 1.0;
  54622. particle.uvs.x = 0.0;
  54623. particle.uvs.y = 0.0;
  54624. particle.uvs.z = 1.0;
  54625. particle.uvs.w = 1.0;
  54626. particle.pivot.x = 0.0;
  54627. particle.pivot.y = 0.0;
  54628. particle.pivot.z = 0.0;
  54629. particle.translateFromPivot = false;
  54630. particle.parentId = null;
  54631. };
  54632. /**
  54633. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54634. * @returns the SPS.
  54635. */
  54636. SolidParticleSystem.prototype.rebuildMesh = function () {
  54637. for (var p = 0; p < this.particles.length; p++) {
  54638. this._rebuildParticle(this.particles[p]);
  54639. }
  54640. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54641. return this;
  54642. };
  54643. /**
  54644. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54645. * This method calls `updateParticle()` for each particle of the SPS.
  54646. * For an animated SPS, it is usually called within the render loop.
  54647. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54648. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54649. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54650. * @returns the SPS.
  54651. */
  54652. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54653. if (start === void 0) { start = 0; }
  54654. if (end === void 0) { end = this.nbParticles - 1; }
  54655. if (update === void 0) { update = true; }
  54656. if (!this._updatable) {
  54657. return this;
  54658. }
  54659. // custom beforeUpdate
  54660. this.beforeUpdateParticles(start, end, update);
  54661. this._cam_axisX.x = 1.0;
  54662. this._cam_axisX.y = 0.0;
  54663. this._cam_axisX.z = 0.0;
  54664. this._cam_axisY.x = 0.0;
  54665. this._cam_axisY.y = 1.0;
  54666. this._cam_axisY.z = 0.0;
  54667. this._cam_axisZ.x = 0.0;
  54668. this._cam_axisZ.y = 0.0;
  54669. this._cam_axisZ.z = 1.0;
  54670. // cases when the World Matrix is to be computed first
  54671. if (this.billboard || this._depthSort) {
  54672. this.mesh.computeWorldMatrix(true);
  54673. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54674. }
  54675. // if the particles will always face the camera
  54676. if (this.billboard) {
  54677. // compute the camera position and un-rotate it by the current mesh rotation
  54678. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54679. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54680. this._cam_axisZ.normalize();
  54681. // same for camera up vector extracted from the cam view matrix
  54682. var view = this._camera.getViewMatrix(true);
  54683. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54684. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54685. this._cam_axisY.normalize();
  54686. this._cam_axisX.normalize();
  54687. }
  54688. // if depthSort, compute the camera global position in the mesh local system
  54689. if (this._depthSort) {
  54690. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54691. }
  54692. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54693. var idx = 0; // current position index in the global array positions32
  54694. var index = 0; // position start index in the global array positions32 of the current particle
  54695. var colidx = 0; // current color index in the global array colors32
  54696. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54697. var uvidx = 0; // current uv index in the global array uvs32
  54698. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54699. var pt = 0; // current index in the particle model shape
  54700. if (this.mesh.isFacetDataEnabled) {
  54701. this._computeBoundingBox = true;
  54702. }
  54703. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54704. if (this._computeBoundingBox) {
  54705. if (start == 0 && end == this.nbParticles - 1) {
  54706. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54707. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54708. }
  54709. else {
  54710. if (this.mesh._boundingInfo) {
  54711. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54712. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54713. }
  54714. }
  54715. }
  54716. // particle loop
  54717. index = this.particles[start]._pos;
  54718. var vpos = (index / 3) | 0;
  54719. colorIndex = vpos * 4;
  54720. uvIndex = vpos * 2;
  54721. for (var p = start; p <= end; p++) {
  54722. this._particle = this.particles[p];
  54723. this._shape = this._particle._model._shape;
  54724. this._shapeUV = this._particle._model._shapeUV;
  54725. // call to custom user function to update the particle properties
  54726. this.updateParticle(this._particle);
  54727. // camera-particle distance for depth sorting
  54728. if (this._depthSort && this._depthSortParticles) {
  54729. var dsp = this.depthSortedParticles[p];
  54730. dsp.ind = this._particle._ind;
  54731. dsp.indicesLength = this._particle._model._indicesLength;
  54732. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54733. }
  54734. // skip the computations for inactive or already invisible particles
  54735. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54736. // increment indexes for the next particle
  54737. pt = this._shape.length;
  54738. index += pt * 3;
  54739. colorIndex += pt * 4;
  54740. uvIndex += pt * 2;
  54741. continue;
  54742. }
  54743. if (this._particle.isVisible) {
  54744. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54745. this._particleHasParent = (this._particle.parentId !== null);
  54746. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54747. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54748. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54749. // particle rotation matrix
  54750. if (this.billboard) {
  54751. this._particle.rotation.x = 0.0;
  54752. this._particle.rotation.y = 0.0;
  54753. }
  54754. if (this._computeParticleRotation || this.billboard) {
  54755. if (this._particle.rotationQuaternion) {
  54756. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54757. }
  54758. else {
  54759. this._yaw = this._particle.rotation.y;
  54760. this._pitch = this._particle.rotation.x;
  54761. this._roll = this._particle.rotation.z;
  54762. this._quaternionRotationYPR();
  54763. }
  54764. this._quaternionToRotationMatrix();
  54765. }
  54766. if (this._particleHasParent) {
  54767. this._parent = this.particles[this._particle.parentId];
  54768. 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];
  54769. 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];
  54770. 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];
  54771. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54772. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54773. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54774. if (this._computeParticleRotation || this.billboard) {
  54775. 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];
  54776. 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];
  54777. 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];
  54778. 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];
  54779. 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];
  54780. 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];
  54781. 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];
  54782. 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];
  54783. 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];
  54784. }
  54785. }
  54786. else {
  54787. this._particle._globalPosition.x = this._particle.position.x;
  54788. this._particle._globalPosition.y = this._particle.position.y;
  54789. this._particle._globalPosition.z = this._particle.position.z;
  54790. if (this._computeParticleRotation || this.billboard) {
  54791. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54792. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54793. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54794. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54795. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54796. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54797. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54798. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54799. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54800. }
  54801. }
  54802. if (this._particle.translateFromPivot) {
  54803. this._pivotBackTranslation.x = 0.0;
  54804. this._pivotBackTranslation.y = 0.0;
  54805. this._pivotBackTranslation.z = 0.0;
  54806. }
  54807. else {
  54808. this._pivotBackTranslation.x = this._scaledPivot.x;
  54809. this._pivotBackTranslation.y = this._scaledPivot.y;
  54810. this._pivotBackTranslation.z = this._scaledPivot.z;
  54811. }
  54812. // particle vertex loop
  54813. for (pt = 0; pt < this._shape.length; pt++) {
  54814. idx = index + pt * 3;
  54815. colidx = colorIndex + pt * 4;
  54816. uvidx = uvIndex + pt * 2;
  54817. this._vertex.x = this._shape[pt].x;
  54818. this._vertex.y = this._shape[pt].y;
  54819. this._vertex.z = this._shape[pt].z;
  54820. if (this._computeParticleVertex) {
  54821. this.updateParticleVertex(this._particle, this._vertex, pt);
  54822. }
  54823. // positions
  54824. this._vertex.x *= this._particle.scaling.x;
  54825. this._vertex.y *= this._particle.scaling.y;
  54826. this._vertex.z *= this._particle.scaling.z;
  54827. this._vertex.x -= this._scaledPivot.x;
  54828. this._vertex.y -= this._scaledPivot.y;
  54829. this._vertex.z -= this._scaledPivot.z;
  54830. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54831. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54832. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54833. this._rotated.x += this._pivotBackTranslation.x;
  54834. this._rotated.y += this._pivotBackTranslation.y;
  54835. this._rotated.z += this._pivotBackTranslation.z;
  54836. 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;
  54837. 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;
  54838. 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;
  54839. if (this._computeBoundingBox) {
  54840. if (this._positions32[idx] < this._minimum.x) {
  54841. this._minimum.x = this._positions32[idx];
  54842. }
  54843. if (this._positions32[idx] > this._maximum.x) {
  54844. this._maximum.x = this._positions32[idx];
  54845. }
  54846. if (this._positions32[idx + 1] < this._minimum.y) {
  54847. this._minimum.y = this._positions32[idx + 1];
  54848. }
  54849. if (this._positions32[idx + 1] > this._maximum.y) {
  54850. this._maximum.y = this._positions32[idx + 1];
  54851. }
  54852. if (this._positions32[idx + 2] < this._minimum.z) {
  54853. this._minimum.z = this._positions32[idx + 2];
  54854. }
  54855. if (this._positions32[idx + 2] > this._maximum.z) {
  54856. this._maximum.z = this._positions32[idx + 2];
  54857. }
  54858. }
  54859. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54860. if (!this._computeParticleVertex) {
  54861. this._normal.x = this._fixedNormal32[idx];
  54862. this._normal.y = this._fixedNormal32[idx + 1];
  54863. this._normal.z = this._fixedNormal32[idx + 2];
  54864. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54865. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54866. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54867. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54868. 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;
  54869. 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;
  54870. }
  54871. if (this._computeParticleColor && this._particle.color) {
  54872. this._colors32[colidx] = this._particle.color.r;
  54873. this._colors32[colidx + 1] = this._particle.color.g;
  54874. this._colors32[colidx + 2] = this._particle.color.b;
  54875. this._colors32[colidx + 3] = this._particle.color.a;
  54876. }
  54877. if (this._computeParticleTexture) {
  54878. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54879. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54880. }
  54881. }
  54882. }
  54883. else {
  54884. this._particle._stillInvisible = true; // mark the particle as invisible
  54885. for (pt = 0; pt < this._shape.length; pt++) {
  54886. idx = index + pt * 3;
  54887. colidx = colorIndex + pt * 4;
  54888. uvidx = uvIndex + pt * 2;
  54889. this._positions32[idx] = 0.0;
  54890. this._positions32[idx + 1] = 0.0;
  54891. this._positions32[idx + 2] = 0.0;
  54892. this._normals32[idx] = 0.0;
  54893. this._normals32[idx + 1] = 0.0;
  54894. this._normals32[idx + 2] = 0.0;
  54895. if (this._computeParticleColor && this._particle.color) {
  54896. this._colors32[colidx] = this._particle.color.r;
  54897. this._colors32[colidx + 1] = this._particle.color.g;
  54898. this._colors32[colidx + 2] = this._particle.color.b;
  54899. this._colors32[colidx + 3] = this._particle.color.a;
  54900. }
  54901. if (this._computeParticleTexture) {
  54902. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54903. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54904. }
  54905. }
  54906. }
  54907. // if the particle intersections must be computed : update the bbInfo
  54908. if (this._particlesIntersect) {
  54909. var bInfo = this._particle._boundingInfo;
  54910. var bBox = bInfo.boundingBox;
  54911. var bSphere = bInfo.boundingSphere;
  54912. if (!this._bSphereOnly) {
  54913. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54914. for (var b = 0; b < bBox.vectors.length; b++) {
  54915. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54916. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54917. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54918. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54919. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54920. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54921. 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;
  54922. 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;
  54923. 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;
  54924. }
  54925. bBox._update(this.mesh._worldMatrix);
  54926. }
  54927. // place and scale the particle bouding sphere in the SPS local system, then update it
  54928. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54929. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54930. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54931. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54932. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54933. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54934. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54935. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54936. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54937. 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));
  54938. bSphere._update(this.mesh._worldMatrix);
  54939. }
  54940. // increment indexes for the next particle
  54941. index = idx + 3;
  54942. colorIndex = colidx + 4;
  54943. uvIndex = uvidx + 2;
  54944. }
  54945. // if the VBO must be updated
  54946. if (update) {
  54947. if (this._computeParticleColor) {
  54948. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54949. }
  54950. if (this._computeParticleTexture) {
  54951. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54952. }
  54953. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54954. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54955. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54956. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54957. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54958. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54959. for (var i = 0; i < this._normals32.length; i++) {
  54960. this._fixedNormal32[i] = this._normals32[i];
  54961. }
  54962. }
  54963. if (!this.mesh.areNormalsFrozen) {
  54964. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54965. }
  54966. }
  54967. if (this._depthSort && this._depthSortParticles) {
  54968. this.depthSortedParticles.sort(this._depthSortFunction);
  54969. var dspl = this.depthSortedParticles.length;
  54970. var sorted = 0;
  54971. var lind = 0;
  54972. var sind = 0;
  54973. var sid = 0;
  54974. for (sorted = 0; sorted < dspl; sorted++) {
  54975. lind = this.depthSortedParticles[sorted].indicesLength;
  54976. sind = this.depthSortedParticles[sorted].ind;
  54977. for (var i = 0; i < lind; i++) {
  54978. this._indices32[sid] = this._indices[sind + i];
  54979. sid++;
  54980. }
  54981. }
  54982. this.mesh.updateIndices(this._indices32);
  54983. }
  54984. }
  54985. if (this._computeBoundingBox) {
  54986. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54987. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54988. }
  54989. this.afterUpdateParticles(start, end, update);
  54990. return this;
  54991. };
  54992. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54993. this._halfroll = this._roll * 0.5;
  54994. this._halfpitch = this._pitch * 0.5;
  54995. this._halfyaw = this._yaw * 0.5;
  54996. this._sinRoll = Math.sin(this._halfroll);
  54997. this._cosRoll = Math.cos(this._halfroll);
  54998. this._sinPitch = Math.sin(this._halfpitch);
  54999. this._cosPitch = Math.cos(this._halfpitch);
  55000. this._sinYaw = Math.sin(this._halfyaw);
  55001. this._cosYaw = Math.cos(this._halfyaw);
  55002. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  55003. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  55004. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  55005. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  55006. };
  55007. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55008. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55009. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55010. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55011. this._rotMatrix.m[3] = 0;
  55012. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55013. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55014. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55015. this._rotMatrix.m[7] = 0;
  55016. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55017. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55018. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55019. this._rotMatrix.m[11] = 0;
  55020. this._rotMatrix.m[12] = 0;
  55021. this._rotMatrix.m[13] = 0;
  55022. this._rotMatrix.m[14] = 0;
  55023. this._rotMatrix.m[15] = 1.0;
  55024. };
  55025. /**
  55026. * Disposes the SPS.
  55027. */
  55028. SolidParticleSystem.prototype.dispose = function () {
  55029. this.mesh.dispose();
  55030. this.vars = null;
  55031. // drop references to internal big arrays for the GC
  55032. this._positions = null;
  55033. this._indices = null;
  55034. this._normals = null;
  55035. this._uvs = null;
  55036. this._colors = null;
  55037. this._indices32 = null;
  55038. this._positions32 = null;
  55039. this._normals32 = null;
  55040. this._fixedNormal32 = null;
  55041. this._uvs32 = null;
  55042. this._colors32 = null;
  55043. this.pickedParticles = null;
  55044. };
  55045. /**
  55046. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55047. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55048. * @returns the SPS.
  55049. */
  55050. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55051. if (!this._isVisibilityBoxLocked) {
  55052. this.mesh.refreshBoundingInfo();
  55053. }
  55054. return this;
  55055. };
  55056. /**
  55057. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55058. * @param size the size (float) of the visibility box
  55059. * note : this doesn't lock the SPS mesh bounding box.
  55060. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55061. */
  55062. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55063. var vis = size / 2;
  55064. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55065. };
  55066. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55067. /**
  55068. * Gets whether the SPS as always visible or not
  55069. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55070. */
  55071. get: function () {
  55072. return this._alwaysVisible;
  55073. },
  55074. /**
  55075. * Sets the SPS as always visible or not
  55076. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55077. */
  55078. set: function (val) {
  55079. this._alwaysVisible = val;
  55080. this.mesh.alwaysSelectAsActiveMesh = val;
  55081. },
  55082. enumerable: true,
  55083. configurable: true
  55084. });
  55085. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55086. /**
  55087. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55088. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55089. */
  55090. get: function () {
  55091. return this._isVisibilityBoxLocked;
  55092. },
  55093. /**
  55094. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55095. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55096. */
  55097. set: function (val) {
  55098. this._isVisibilityBoxLocked = val;
  55099. var boundingInfo = this.mesh.getBoundingInfo();
  55100. boundingInfo.isLocked = val;
  55101. },
  55102. enumerable: true,
  55103. configurable: true
  55104. });
  55105. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55106. /**
  55107. * Gets if `setParticles()` computes the particle rotations or not.
  55108. * Default value : true. The SPS is faster when it's set to false.
  55109. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55110. */
  55111. get: function () {
  55112. return this._computeParticleRotation;
  55113. },
  55114. /**
  55115. * Tells to `setParticles()` to compute the particle rotations or not.
  55116. * Default value : true. The SPS is faster when it's set to false.
  55117. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55118. */
  55119. set: function (val) {
  55120. this._computeParticleRotation = val;
  55121. },
  55122. enumerable: true,
  55123. configurable: true
  55124. });
  55125. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55126. /**
  55127. * Gets if `setParticles()` computes the particle colors or not.
  55128. * Default value : true. The SPS is faster when it's set to false.
  55129. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55130. */
  55131. get: function () {
  55132. return this._computeParticleColor;
  55133. },
  55134. /**
  55135. * Tells to `setParticles()` to compute the particle colors or not.
  55136. * Default value : true. The SPS is faster when it's set to false.
  55137. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55138. */
  55139. set: function (val) {
  55140. this._computeParticleColor = val;
  55141. },
  55142. enumerable: true,
  55143. configurable: true
  55144. });
  55145. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55146. /**
  55147. * Gets if `setParticles()` computes the particle textures or not.
  55148. * Default value : true. The SPS is faster when it's set to false.
  55149. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55150. */
  55151. get: function () {
  55152. return this._computeParticleTexture;
  55153. },
  55154. set: function (val) {
  55155. this._computeParticleTexture = val;
  55156. },
  55157. enumerable: true,
  55158. configurable: true
  55159. });
  55160. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55161. /**
  55162. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55163. * Default value : false. The SPS is faster when it's set to false.
  55164. * Note : the particle custom vertex positions aren't stored values.
  55165. */
  55166. get: function () {
  55167. return this._computeParticleVertex;
  55168. },
  55169. /**
  55170. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55171. * Default value : false. The SPS is faster when it's set to false.
  55172. * Note : the particle custom vertex positions aren't stored values.
  55173. */
  55174. set: function (val) {
  55175. this._computeParticleVertex = val;
  55176. },
  55177. enumerable: true,
  55178. configurable: true
  55179. });
  55180. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55181. /**
  55182. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55183. */
  55184. get: function () {
  55185. return this._computeBoundingBox;
  55186. },
  55187. /**
  55188. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55189. */
  55190. set: function (val) {
  55191. this._computeBoundingBox = val;
  55192. },
  55193. enumerable: true,
  55194. configurable: true
  55195. });
  55196. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55197. /**
  55198. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55199. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55200. * Default : `true`
  55201. */
  55202. get: function () {
  55203. return this._depthSortParticles;
  55204. },
  55205. /**
  55206. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55207. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55208. * Default : `true`
  55209. */
  55210. set: function (val) {
  55211. this._depthSortParticles = val;
  55212. },
  55213. enumerable: true,
  55214. configurable: true
  55215. });
  55216. // =======================================================================
  55217. // Particle behavior logic
  55218. // these following methods may be overwritten by the user to fit his needs
  55219. /**
  55220. * This function does nothing. It may be overwritten to set all the particle first values.
  55221. * The SPS doesn't call this function, you may have to call it by your own.
  55222. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55223. */
  55224. SolidParticleSystem.prototype.initParticles = function () {
  55225. };
  55226. /**
  55227. * This function does nothing. It may be overwritten to recycle a particle.
  55228. * The SPS doesn't call this function, you may have to call it by your own.
  55229. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55230. * @param particle The particle to recycle
  55231. * @returns the recycled particle
  55232. */
  55233. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55234. return particle;
  55235. };
  55236. /**
  55237. * Updates a particle : this function should be overwritten by the user.
  55238. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55239. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55240. * @example : just set a particle position or velocity and recycle conditions
  55241. * @param particle The particle to update
  55242. * @returns the updated particle
  55243. */
  55244. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55245. return particle;
  55246. };
  55247. /**
  55248. * Updates a vertex of a particle : it can be overwritten by the user.
  55249. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55250. * @param particle the current particle
  55251. * @param vertex the current index of the current particle
  55252. * @param pt the index of the current vertex in the particle shape
  55253. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55254. * @example : just set a vertex particle position
  55255. * @returns the updated vertex
  55256. */
  55257. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55258. return vertex;
  55259. };
  55260. /**
  55261. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55262. * This does nothing and may be overwritten by the user.
  55263. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55264. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55265. * @param update the boolean update value actually passed to setParticles()
  55266. */
  55267. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55268. };
  55269. /**
  55270. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55271. * This will be passed three parameters.
  55272. * This does nothing and may be overwritten by the user.
  55273. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55274. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55275. * @param update the boolean update value actually passed to setParticles()
  55276. */
  55277. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55278. };
  55279. return SolidParticleSystem;
  55280. }());
  55281. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55282. })(BABYLON || (BABYLON = {}));
  55283. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55284. "use strict";
  55285. var BABYLON;
  55286. (function (BABYLON) {
  55287. var ShaderMaterial = /** @class */ (function (_super) {
  55288. __extends(ShaderMaterial, _super);
  55289. function ShaderMaterial(name, scene, shaderPath, options) {
  55290. var _this = _super.call(this, name, scene) || this;
  55291. _this._textures = {};
  55292. _this._textureArrays = {};
  55293. _this._floats = {};
  55294. _this._ints = {};
  55295. _this._floatsArrays = {};
  55296. _this._colors3 = {};
  55297. _this._colors3Arrays = {};
  55298. _this._colors4 = {};
  55299. _this._vectors2 = {};
  55300. _this._vectors3 = {};
  55301. _this._vectors4 = {};
  55302. _this._matrices = {};
  55303. _this._matrices3x3 = {};
  55304. _this._matrices2x2 = {};
  55305. _this._vectors2Arrays = {};
  55306. _this._vectors3Arrays = {};
  55307. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55308. _this._shaderPath = shaderPath;
  55309. options.needAlphaBlending = options.needAlphaBlending || false;
  55310. options.needAlphaTesting = options.needAlphaTesting || false;
  55311. options.attributes = options.attributes || ["position", "normal", "uv"];
  55312. options.uniforms = options.uniforms || ["worldViewProjection"];
  55313. options.uniformBuffers = options.uniformBuffers || [];
  55314. options.samplers = options.samplers || [];
  55315. options.defines = options.defines || [];
  55316. _this._options = options;
  55317. return _this;
  55318. }
  55319. ShaderMaterial.prototype.getClassName = function () {
  55320. return "ShaderMaterial";
  55321. };
  55322. ShaderMaterial.prototype.needAlphaBlending = function () {
  55323. return this._options.needAlphaBlending;
  55324. };
  55325. ShaderMaterial.prototype.needAlphaTesting = function () {
  55326. return this._options.needAlphaTesting;
  55327. };
  55328. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55329. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55330. this._options.uniforms.push(uniformName);
  55331. }
  55332. };
  55333. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55334. if (this._options.samplers.indexOf(name) === -1) {
  55335. this._options.samplers.push(name);
  55336. }
  55337. this._textures[name] = texture;
  55338. return this;
  55339. };
  55340. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55341. if (this._options.samplers.indexOf(name) === -1) {
  55342. this._options.samplers.push(name);
  55343. }
  55344. this._checkUniform(name);
  55345. this._textureArrays[name] = textures;
  55346. return this;
  55347. };
  55348. ShaderMaterial.prototype.setFloat = function (name, value) {
  55349. this._checkUniform(name);
  55350. this._floats[name] = value;
  55351. return this;
  55352. };
  55353. ShaderMaterial.prototype.setInt = function (name, value) {
  55354. this._checkUniform(name);
  55355. this._ints[name] = value;
  55356. return this;
  55357. };
  55358. ShaderMaterial.prototype.setFloats = function (name, value) {
  55359. this._checkUniform(name);
  55360. this._floatsArrays[name] = value;
  55361. return this;
  55362. };
  55363. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55364. this._checkUniform(name);
  55365. this._colors3[name] = value;
  55366. return this;
  55367. };
  55368. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55369. this._checkUniform(name);
  55370. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55371. color.toArray(arr, arr.length);
  55372. return arr;
  55373. }, []);
  55374. return this;
  55375. };
  55376. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55377. this._checkUniform(name);
  55378. this._colors4[name] = value;
  55379. return this;
  55380. };
  55381. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55382. this._checkUniform(name);
  55383. this._vectors2[name] = value;
  55384. return this;
  55385. };
  55386. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55387. this._checkUniform(name);
  55388. this._vectors3[name] = value;
  55389. return this;
  55390. };
  55391. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55392. this._checkUniform(name);
  55393. this._vectors4[name] = value;
  55394. return this;
  55395. };
  55396. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55397. this._checkUniform(name);
  55398. this._matrices[name] = value;
  55399. return this;
  55400. };
  55401. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55402. this._checkUniform(name);
  55403. this._matrices3x3[name] = value;
  55404. return this;
  55405. };
  55406. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55407. this._checkUniform(name);
  55408. this._matrices2x2[name] = value;
  55409. return this;
  55410. };
  55411. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55412. this._checkUniform(name);
  55413. this._vectors2Arrays[name] = value;
  55414. return this;
  55415. };
  55416. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55417. this._checkUniform(name);
  55418. this._vectors3Arrays[name] = value;
  55419. return this;
  55420. };
  55421. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55422. if (!mesh) {
  55423. return true;
  55424. }
  55425. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55426. return false;
  55427. }
  55428. return false;
  55429. };
  55430. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55431. var scene = this.getScene();
  55432. var engine = scene.getEngine();
  55433. if (!this.checkReadyOnEveryCall) {
  55434. if (this._renderId === scene.getRenderId()) {
  55435. if (this._checkCache(scene, mesh, useInstances)) {
  55436. return true;
  55437. }
  55438. }
  55439. }
  55440. // Instances
  55441. var defines = [];
  55442. var attribs = [];
  55443. var fallbacks = new BABYLON.EffectFallbacks();
  55444. if (useInstances) {
  55445. defines.push("#define INSTANCES");
  55446. }
  55447. for (var index = 0; index < this._options.defines.length; index++) {
  55448. defines.push(this._options.defines[index]);
  55449. }
  55450. for (var index = 0; index < this._options.attributes.length; index++) {
  55451. attribs.push(this._options.attributes[index]);
  55452. }
  55453. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55454. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55455. defines.push("#define VERTEXCOLOR");
  55456. }
  55457. // Bones
  55458. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55459. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55460. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55461. if (mesh.numBoneInfluencers > 4) {
  55462. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55463. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55464. }
  55465. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55466. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55467. fallbacks.addCPUSkinningFallback(0, mesh);
  55468. if (this._options.uniforms.indexOf("mBones") === -1) {
  55469. this._options.uniforms.push("mBones");
  55470. }
  55471. }
  55472. else {
  55473. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55474. }
  55475. // Textures
  55476. for (var name in this._textures) {
  55477. if (!this._textures[name].isReady()) {
  55478. return false;
  55479. }
  55480. }
  55481. // Alpha test
  55482. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55483. defines.push("#define ALPHATEST");
  55484. }
  55485. var previousEffect = this._effect;
  55486. var join = defines.join("\n");
  55487. this._effect = engine.createEffect(this._shaderPath, {
  55488. attributes: attribs,
  55489. uniformsNames: this._options.uniforms,
  55490. uniformBuffersNames: this._options.uniformBuffers,
  55491. samplers: this._options.samplers,
  55492. defines: join,
  55493. fallbacks: fallbacks,
  55494. onCompiled: this.onCompiled,
  55495. onError: this.onError
  55496. }, engine);
  55497. if (!this._effect.isReady()) {
  55498. return false;
  55499. }
  55500. if (previousEffect !== this._effect) {
  55501. scene.resetCachedMaterial();
  55502. }
  55503. this._renderId = scene.getRenderId();
  55504. return true;
  55505. };
  55506. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55507. var scene = this.getScene();
  55508. if (!this._effect) {
  55509. return;
  55510. }
  55511. if (this._options.uniforms.indexOf("world") !== -1) {
  55512. this._effect.setMatrix("world", world);
  55513. }
  55514. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55515. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55516. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55517. }
  55518. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55519. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55520. }
  55521. };
  55522. ShaderMaterial.prototype.bind = function (world, mesh) {
  55523. // Std values
  55524. this.bindOnlyWorldMatrix(world);
  55525. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55526. if (this._options.uniforms.indexOf("view") !== -1) {
  55527. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55528. }
  55529. if (this._options.uniforms.indexOf("projection") !== -1) {
  55530. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55531. }
  55532. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55533. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55534. }
  55535. // Bones
  55536. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55537. var name;
  55538. // Texture
  55539. for (name in this._textures) {
  55540. this._effect.setTexture(name, this._textures[name]);
  55541. }
  55542. // Texture arrays
  55543. for (name in this._textureArrays) {
  55544. this._effect.setTextureArray(name, this._textureArrays[name]);
  55545. }
  55546. // Int
  55547. for (name in this._ints) {
  55548. this._effect.setInt(name, this._ints[name]);
  55549. }
  55550. // Float
  55551. for (name in this._floats) {
  55552. this._effect.setFloat(name, this._floats[name]);
  55553. }
  55554. // Floats
  55555. for (name in this._floatsArrays) {
  55556. this._effect.setArray(name, this._floatsArrays[name]);
  55557. }
  55558. // Color3
  55559. for (name in this._colors3) {
  55560. this._effect.setColor3(name, this._colors3[name]);
  55561. }
  55562. for (name in this._colors3Arrays) {
  55563. this._effect.setArray3(name, this._colors3Arrays[name]);
  55564. }
  55565. // Color4
  55566. for (name in this._colors4) {
  55567. var color = this._colors4[name];
  55568. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55569. }
  55570. // Vector2
  55571. for (name in this._vectors2) {
  55572. this._effect.setVector2(name, this._vectors2[name]);
  55573. }
  55574. // Vector3
  55575. for (name in this._vectors3) {
  55576. this._effect.setVector3(name, this._vectors3[name]);
  55577. }
  55578. // Vector4
  55579. for (name in this._vectors4) {
  55580. this._effect.setVector4(name, this._vectors4[name]);
  55581. }
  55582. // Matrix
  55583. for (name in this._matrices) {
  55584. this._effect.setMatrix(name, this._matrices[name]);
  55585. }
  55586. // Matrix 3x3
  55587. for (name in this._matrices3x3) {
  55588. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55589. }
  55590. // Matrix 2x2
  55591. for (name in this._matrices2x2) {
  55592. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55593. }
  55594. // Vector2Array
  55595. for (name in this._vectors2Arrays) {
  55596. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55597. }
  55598. // Vector3Array
  55599. for (name in this._vectors3Arrays) {
  55600. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55601. }
  55602. }
  55603. this._afterBind(mesh);
  55604. };
  55605. ShaderMaterial.prototype.getActiveTextures = function () {
  55606. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55607. for (var name in this._textures) {
  55608. activeTextures.push(this._textures[name]);
  55609. }
  55610. for (var name in this._textureArrays) {
  55611. var array = this._textureArrays[name];
  55612. for (var index = 0; index < array.length; index++) {
  55613. activeTextures.push(array[index]);
  55614. }
  55615. }
  55616. return activeTextures;
  55617. };
  55618. ShaderMaterial.prototype.hasTexture = function (texture) {
  55619. if (_super.prototype.hasTexture.call(this, texture)) {
  55620. return true;
  55621. }
  55622. for (var name in this._textures) {
  55623. if (this._textures[name] === texture) {
  55624. return true;
  55625. }
  55626. }
  55627. for (var name in this._textureArrays) {
  55628. var array = this._textureArrays[name];
  55629. for (var index = 0; index < array.length; index++) {
  55630. if (array[index] === texture) {
  55631. return true;
  55632. }
  55633. }
  55634. }
  55635. return false;
  55636. };
  55637. ShaderMaterial.prototype.clone = function (name) {
  55638. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55639. return newShaderMaterial;
  55640. };
  55641. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55642. if (forceDisposeTextures) {
  55643. var name;
  55644. for (name in this._textures) {
  55645. this._textures[name].dispose();
  55646. }
  55647. for (name in this._textureArrays) {
  55648. var array = this._textureArrays[name];
  55649. for (var index = 0; index < array.length; index++) {
  55650. array[index].dispose();
  55651. }
  55652. }
  55653. }
  55654. this._textures = {};
  55655. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55656. };
  55657. ShaderMaterial.prototype.serialize = function () {
  55658. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55659. serializationObject.customType = "BABYLON.ShaderMaterial";
  55660. serializationObject.options = this._options;
  55661. serializationObject.shaderPath = this._shaderPath;
  55662. var name;
  55663. // Texture
  55664. serializationObject.textures = {};
  55665. for (name in this._textures) {
  55666. serializationObject.textures[name] = this._textures[name].serialize();
  55667. }
  55668. // Texture arrays
  55669. serializationObject.textureArrays = {};
  55670. for (name in this._textureArrays) {
  55671. serializationObject.textureArrays[name] = [];
  55672. var array = this._textureArrays[name];
  55673. for (var index = 0; index < array.length; index++) {
  55674. serializationObject.textureArrays[name].push(array[index].serialize());
  55675. }
  55676. }
  55677. // Float
  55678. serializationObject.floats = {};
  55679. for (name in this._floats) {
  55680. serializationObject.floats[name] = this._floats[name];
  55681. }
  55682. // Float s
  55683. serializationObject.FloatArrays = {};
  55684. for (name in this._floatsArrays) {
  55685. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55686. }
  55687. // Color3
  55688. serializationObject.colors3 = {};
  55689. for (name in this._colors3) {
  55690. serializationObject.colors3[name] = this._colors3[name].asArray();
  55691. }
  55692. // Color3 array
  55693. serializationObject.colors3Arrays = {};
  55694. for (name in this._colors3Arrays) {
  55695. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55696. }
  55697. // Color4
  55698. serializationObject.colors4 = {};
  55699. for (name in this._colors4) {
  55700. serializationObject.colors4[name] = this._colors4[name].asArray();
  55701. }
  55702. // Vector2
  55703. serializationObject.vectors2 = {};
  55704. for (name in this._vectors2) {
  55705. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55706. }
  55707. // Vector3
  55708. serializationObject.vectors3 = {};
  55709. for (name in this._vectors3) {
  55710. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55711. }
  55712. // Vector4
  55713. serializationObject.vectors4 = {};
  55714. for (name in this._vectors4) {
  55715. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55716. }
  55717. // Matrix
  55718. serializationObject.matrices = {};
  55719. for (name in this._matrices) {
  55720. serializationObject.matrices[name] = this._matrices[name].asArray();
  55721. }
  55722. // Matrix 3x3
  55723. serializationObject.matrices3x3 = {};
  55724. for (name in this._matrices3x3) {
  55725. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55726. }
  55727. // Matrix 2x2
  55728. serializationObject.matrices2x2 = {};
  55729. for (name in this._matrices2x2) {
  55730. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55731. }
  55732. // Vector2Array
  55733. serializationObject.vectors2Arrays = {};
  55734. for (name in this._vectors2Arrays) {
  55735. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55736. }
  55737. // Vector3Array
  55738. serializationObject.vectors3Arrays = {};
  55739. for (name in this._vectors3Arrays) {
  55740. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55741. }
  55742. return serializationObject;
  55743. };
  55744. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55745. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55746. var name;
  55747. // Texture
  55748. for (name in source.textures) {
  55749. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55750. }
  55751. // Texture arrays
  55752. for (name in source.textureArrays) {
  55753. var array = source.textureArrays[name];
  55754. var textureArray = new Array();
  55755. for (var index = 0; index < array.length; index++) {
  55756. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55757. }
  55758. material.setTextureArray(name, textureArray);
  55759. }
  55760. // Float
  55761. for (name in source.floats) {
  55762. material.setFloat(name, source.floats[name]);
  55763. }
  55764. // Float s
  55765. for (name in source.floatsArrays) {
  55766. material.setFloats(name, source.floatsArrays[name]);
  55767. }
  55768. // Color3
  55769. for (name in source.colors3) {
  55770. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55771. }
  55772. // Color3 arrays
  55773. for (name in source.colors3Arrays) {
  55774. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55775. if (i % 3 === 0) {
  55776. arr.push([num]);
  55777. }
  55778. else {
  55779. arr[arr.length - 1].push(num);
  55780. }
  55781. return arr;
  55782. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55783. material.setColor3Array(name, colors);
  55784. }
  55785. // Color4
  55786. for (name in source.colors4) {
  55787. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55788. }
  55789. // Vector2
  55790. for (name in source.vectors2) {
  55791. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55792. }
  55793. // Vector3
  55794. for (name in source.vectors3) {
  55795. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55796. }
  55797. // Vector4
  55798. for (name in source.vectors4) {
  55799. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55800. }
  55801. // Matrix
  55802. for (name in source.matrices) {
  55803. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55804. }
  55805. // Matrix 3x3
  55806. for (name in source.matrices3x3) {
  55807. material.setMatrix3x3(name, source.matrices3x3[name]);
  55808. }
  55809. // Matrix 2x2
  55810. for (name in source.matrices2x2) {
  55811. material.setMatrix2x2(name, source.matrices2x2[name]);
  55812. }
  55813. // Vector2Array
  55814. for (name in source.vectors2Arrays) {
  55815. material.setArray2(name, source.vectors2Arrays[name]);
  55816. }
  55817. // Vector3Array
  55818. for (name in source.vectors3Arrays) {
  55819. material.setArray3(name, source.vectors3Arrays[name]);
  55820. }
  55821. return material;
  55822. };
  55823. return ShaderMaterial;
  55824. }(BABYLON.Material));
  55825. BABYLON.ShaderMaterial = ShaderMaterial;
  55826. })(BABYLON || (BABYLON = {}));
  55827. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55828. "use strict";
  55829. var BABYLON;
  55830. (function (BABYLON) {
  55831. var GroundMesh = /** @class */ (function (_super) {
  55832. __extends(GroundMesh, _super);
  55833. function GroundMesh(name, scene) {
  55834. var _this = _super.call(this, name, scene) || this;
  55835. _this.generateOctree = false;
  55836. return _this;
  55837. }
  55838. GroundMesh.prototype.getClassName = function () {
  55839. return "GroundMesh";
  55840. };
  55841. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55842. get: function () {
  55843. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55844. },
  55845. enumerable: true,
  55846. configurable: true
  55847. });
  55848. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55849. get: function () {
  55850. return this._subdivisionsX;
  55851. },
  55852. enumerable: true,
  55853. configurable: true
  55854. });
  55855. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55856. get: function () {
  55857. return this._subdivisionsY;
  55858. },
  55859. enumerable: true,
  55860. configurable: true
  55861. });
  55862. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55863. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55864. this._subdivisionsX = chunksCount;
  55865. this._subdivisionsY = chunksCount;
  55866. this.subdivide(chunksCount);
  55867. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55868. };
  55869. /**
  55870. * Returns a height (y) value in the Worl system :
  55871. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55872. * Returns the ground y position if (x, z) are outside the ground surface.
  55873. */
  55874. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55875. var world = this.getWorldMatrix();
  55876. var invMat = BABYLON.Tmp.Matrix[5];
  55877. world.invertToRef(invMat);
  55878. var tmpVect = BABYLON.Tmp.Vector3[8];
  55879. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55880. x = tmpVect.x;
  55881. z = tmpVect.z;
  55882. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55883. return this.position.y;
  55884. }
  55885. if (!this._heightQuads || this._heightQuads.length == 0) {
  55886. this._initHeightQuads();
  55887. this._computeHeightQuads();
  55888. }
  55889. var facet = this._getFacetAt(x, z);
  55890. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55891. // return y in the World system
  55892. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55893. return tmpVect.y;
  55894. };
  55895. /**
  55896. * Returns a normalized vector (Vector3) orthogonal to the ground
  55897. * at the ground coordinates (x, z) expressed in the World system.
  55898. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55899. */
  55900. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55901. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55902. this.getNormalAtCoordinatesToRef(x, z, normal);
  55903. return normal;
  55904. };
  55905. /**
  55906. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55907. * at the ground coordinates (x, z) expressed in the World system.
  55908. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55909. * Returns the GroundMesh.
  55910. */
  55911. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55912. var world = this.getWorldMatrix();
  55913. var tmpMat = BABYLON.Tmp.Matrix[5];
  55914. world.invertToRef(tmpMat);
  55915. var tmpVect = BABYLON.Tmp.Vector3[8];
  55916. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55917. x = tmpVect.x;
  55918. z = tmpVect.z;
  55919. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55920. return this;
  55921. }
  55922. if (!this._heightQuads || this._heightQuads.length == 0) {
  55923. this._initHeightQuads();
  55924. this._computeHeightQuads();
  55925. }
  55926. var facet = this._getFacetAt(x, z);
  55927. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55928. return this;
  55929. };
  55930. /**
  55931. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55932. * if the ground has been updated.
  55933. * This can be used in the render loop.
  55934. * Returns the GroundMesh.
  55935. */
  55936. GroundMesh.prototype.updateCoordinateHeights = function () {
  55937. if (!this._heightQuads || this._heightQuads.length == 0) {
  55938. this._initHeightQuads();
  55939. }
  55940. this._computeHeightQuads();
  55941. return this;
  55942. };
  55943. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55944. GroundMesh.prototype._getFacetAt = function (x, z) {
  55945. // retrieve col and row from x, z coordinates in the ground local system
  55946. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55947. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55948. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55949. var facet;
  55950. if (z < quad.slope.x * x + quad.slope.y) {
  55951. facet = quad.facet1;
  55952. }
  55953. else {
  55954. facet = quad.facet2;
  55955. }
  55956. return facet;
  55957. };
  55958. // Creates and populates the heightMap array with "facet" elements :
  55959. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55960. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55961. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55962. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55963. // Returns the GroundMesh.
  55964. GroundMesh.prototype._initHeightQuads = function () {
  55965. var subdivisionsX = this._subdivisionsX;
  55966. var subdivisionsY = this._subdivisionsY;
  55967. this._heightQuads = new Array();
  55968. for (var row = 0; row < subdivisionsY; row++) {
  55969. for (var col = 0; col < subdivisionsX; col++) {
  55970. 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) };
  55971. this._heightQuads[row * subdivisionsX + col] = quad;
  55972. }
  55973. }
  55974. return this;
  55975. };
  55976. // Compute each quad element values and update the the heightMap array :
  55977. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55978. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55979. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55980. // Returns the GroundMesh.
  55981. GroundMesh.prototype._computeHeightQuads = function () {
  55982. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55983. if (!positions) {
  55984. return this;
  55985. }
  55986. var v1 = BABYLON.Tmp.Vector3[3];
  55987. var v2 = BABYLON.Tmp.Vector3[2];
  55988. var v3 = BABYLON.Tmp.Vector3[1];
  55989. var v4 = BABYLON.Tmp.Vector3[0];
  55990. var v1v2 = BABYLON.Tmp.Vector3[4];
  55991. var v1v3 = BABYLON.Tmp.Vector3[5];
  55992. var v1v4 = BABYLON.Tmp.Vector3[6];
  55993. var norm1 = BABYLON.Tmp.Vector3[7];
  55994. var norm2 = BABYLON.Tmp.Vector3[8];
  55995. var i = 0;
  55996. var j = 0;
  55997. var k = 0;
  55998. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55999. var h = 0;
  56000. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  56001. var d2 = 0;
  56002. var subdivisionsX = this._subdivisionsX;
  56003. var subdivisionsY = this._subdivisionsY;
  56004. for (var row = 0; row < subdivisionsY; row++) {
  56005. for (var col = 0; col < subdivisionsX; col++) {
  56006. i = col * 3;
  56007. j = row * (subdivisionsX + 1) * 3;
  56008. k = (row + 1) * (subdivisionsX + 1) * 3;
  56009. v1.x = positions[j + i];
  56010. v1.y = positions[j + i + 1];
  56011. v1.z = positions[j + i + 2];
  56012. v2.x = positions[j + i + 3];
  56013. v2.y = positions[j + i + 4];
  56014. v2.z = positions[j + i + 5];
  56015. v3.x = positions[k + i];
  56016. v3.y = positions[k + i + 1];
  56017. v3.z = positions[k + i + 2];
  56018. v4.x = positions[k + i + 3];
  56019. v4.y = positions[k + i + 4];
  56020. v4.z = positions[k + i + 5];
  56021. // 2D slope V1V4
  56022. cd = (v4.z - v1.z) / (v4.x - v1.x);
  56023. h = v1.z - cd * v1.x; // v1 belongs to the slope
  56024. // facet equations :
  56025. // we compute each facet normal vector
  56026. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  56027. // we compute the value d by applying the equation to v1 which belongs to the plane
  56028. // then we store the facet equation in a Vector4
  56029. v2.subtractToRef(v1, v1v2);
  56030. v3.subtractToRef(v1, v1v3);
  56031. v4.subtractToRef(v1, v1v4);
  56032. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  56033. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  56034. norm1.normalize();
  56035. norm2.normalize();
  56036. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  56037. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  56038. var quad = this._heightQuads[row * subdivisionsX + col];
  56039. quad.slope.copyFromFloats(cd, h);
  56040. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  56041. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  56042. }
  56043. }
  56044. return this;
  56045. };
  56046. GroundMesh.prototype.serialize = function (serializationObject) {
  56047. _super.prototype.serialize.call(this, serializationObject);
  56048. serializationObject.subdivisionsX = this._subdivisionsX;
  56049. serializationObject.subdivisionsY = this._subdivisionsY;
  56050. serializationObject.minX = this._minX;
  56051. serializationObject.maxX = this._maxX;
  56052. serializationObject.minZ = this._minZ;
  56053. serializationObject.maxZ = this._maxZ;
  56054. serializationObject.width = this._width;
  56055. serializationObject.height = this._height;
  56056. };
  56057. GroundMesh.Parse = function (parsedMesh, scene) {
  56058. var result = new GroundMesh(parsedMesh.name, scene);
  56059. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  56060. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  56061. result._minX = parsedMesh.minX;
  56062. result._maxX = parsedMesh.maxX;
  56063. result._minZ = parsedMesh.minZ;
  56064. result._maxZ = parsedMesh.maxZ;
  56065. result._width = parsedMesh.width;
  56066. result._height = parsedMesh.height;
  56067. return result;
  56068. };
  56069. return GroundMesh;
  56070. }(BABYLON.Mesh));
  56071. BABYLON.GroundMesh = GroundMesh;
  56072. })(BABYLON || (BABYLON = {}));
  56073. //# sourceMappingURL=babylon.groundMesh.js.map
  56074. "use strict";
  56075. var BABYLON;
  56076. (function (BABYLON) {
  56077. /**
  56078. * Creates an instance based on a source mesh.
  56079. */
  56080. var InstancedMesh = /** @class */ (function (_super) {
  56081. __extends(InstancedMesh, _super);
  56082. function InstancedMesh(name, source) {
  56083. var _this = _super.call(this, name, source.getScene()) || this;
  56084. source.instances.push(_this);
  56085. _this._sourceMesh = source;
  56086. _this.position.copyFrom(source.position);
  56087. _this.rotation.copyFrom(source.rotation);
  56088. _this.scaling.copyFrom(source.scaling);
  56089. if (source.rotationQuaternion) {
  56090. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56091. }
  56092. _this.infiniteDistance = source.infiniteDistance;
  56093. _this.setPivotMatrix(source.getPivotMatrix());
  56094. _this.refreshBoundingInfo();
  56095. _this._syncSubMeshes();
  56096. return _this;
  56097. }
  56098. /**
  56099. * Returns the string "InstancedMesh".
  56100. */
  56101. InstancedMesh.prototype.getClassName = function () {
  56102. return "InstancedMesh";
  56103. };
  56104. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56105. // Methods
  56106. get: function () {
  56107. return this._sourceMesh.receiveShadows;
  56108. },
  56109. enumerable: true,
  56110. configurable: true
  56111. });
  56112. Object.defineProperty(InstancedMesh.prototype, "material", {
  56113. get: function () {
  56114. return this._sourceMesh.material;
  56115. },
  56116. enumerable: true,
  56117. configurable: true
  56118. });
  56119. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56120. get: function () {
  56121. return this._sourceMesh.visibility;
  56122. },
  56123. enumerable: true,
  56124. configurable: true
  56125. });
  56126. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56127. get: function () {
  56128. return this._sourceMesh.skeleton;
  56129. },
  56130. enumerable: true,
  56131. configurable: true
  56132. });
  56133. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56134. get: function () {
  56135. return this._sourceMesh.renderingGroupId;
  56136. },
  56137. set: function (value) {
  56138. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56139. return;
  56140. }
  56141. //no-op with warning
  56142. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56143. },
  56144. enumerable: true,
  56145. configurable: true
  56146. });
  56147. /**
  56148. * Returns the total number of vertices (integer).
  56149. */
  56150. InstancedMesh.prototype.getTotalVertices = function () {
  56151. return this._sourceMesh.getTotalVertices();
  56152. };
  56153. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56154. get: function () {
  56155. return this._sourceMesh;
  56156. },
  56157. enumerable: true,
  56158. configurable: true
  56159. });
  56160. /**
  56161. * Is this node ready to be used/rendered
  56162. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56163. * @return {boolean} is it ready
  56164. */
  56165. InstancedMesh.prototype.isReady = function (completeCheck) {
  56166. if (completeCheck === void 0) { completeCheck = false; }
  56167. return this._sourceMesh.isReady(completeCheck, true);
  56168. };
  56169. /**
  56170. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56171. */
  56172. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56173. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56174. };
  56175. /**
  56176. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56177. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56178. * The `data` are either a numeric array either a Float32Array.
  56179. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56180. * 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).
  56181. * Note that a new underlying VertexBuffer object is created each call.
  56182. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56183. *
  56184. * Possible `kind` values :
  56185. * - BABYLON.VertexBuffer.PositionKind
  56186. * - BABYLON.VertexBuffer.UVKind
  56187. * - BABYLON.VertexBuffer.UV2Kind
  56188. * - BABYLON.VertexBuffer.UV3Kind
  56189. * - BABYLON.VertexBuffer.UV4Kind
  56190. * - BABYLON.VertexBuffer.UV5Kind
  56191. * - BABYLON.VertexBuffer.UV6Kind
  56192. * - BABYLON.VertexBuffer.ColorKind
  56193. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56194. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56195. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56196. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56197. *
  56198. * Returns the Mesh.
  56199. */
  56200. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56201. if (this.sourceMesh) {
  56202. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56203. }
  56204. return this.sourceMesh;
  56205. };
  56206. /**
  56207. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56208. * If the mesh has no geometry, it is simply returned as it is.
  56209. * The `data` are either a numeric array either a Float32Array.
  56210. * No new underlying VertexBuffer object is created.
  56211. * 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.
  56212. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56213. *
  56214. * Possible `kind` values :
  56215. * - BABYLON.VertexBuffer.PositionKind
  56216. * - BABYLON.VertexBuffer.UVKind
  56217. * - BABYLON.VertexBuffer.UV2Kind
  56218. * - BABYLON.VertexBuffer.UV3Kind
  56219. * - BABYLON.VertexBuffer.UV4Kind
  56220. * - BABYLON.VertexBuffer.UV5Kind
  56221. * - BABYLON.VertexBuffer.UV6Kind
  56222. * - BABYLON.VertexBuffer.ColorKind
  56223. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56224. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56225. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56226. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56227. *
  56228. * Returns the Mesh.
  56229. */
  56230. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56231. if (this.sourceMesh) {
  56232. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56233. }
  56234. return this.sourceMesh;
  56235. };
  56236. /**
  56237. * Sets the mesh indices.
  56238. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56239. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56240. * This method creates a new index buffer each call.
  56241. * Returns the Mesh.
  56242. */
  56243. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56244. if (totalVertices === void 0) { totalVertices = null; }
  56245. if (this.sourceMesh) {
  56246. this.sourceMesh.setIndices(indices, totalVertices);
  56247. }
  56248. return this.sourceMesh;
  56249. };
  56250. /**
  56251. * Boolean : True if the mesh owns the requested kind of data.
  56252. */
  56253. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56254. return this._sourceMesh.isVerticesDataPresent(kind);
  56255. };
  56256. /**
  56257. * Returns an array of indices (IndicesArray).
  56258. */
  56259. InstancedMesh.prototype.getIndices = function () {
  56260. return this._sourceMesh.getIndices();
  56261. };
  56262. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56263. get: function () {
  56264. return this._sourceMesh._positions;
  56265. },
  56266. enumerable: true,
  56267. configurable: true
  56268. });
  56269. /**
  56270. * Sets a new updated BoundingInfo to the mesh.
  56271. * Returns the mesh.
  56272. */
  56273. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56274. var meshBB = this._sourceMesh.getBoundingInfo();
  56275. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56276. this._updateBoundingInfo();
  56277. return this;
  56278. };
  56279. InstancedMesh.prototype._preActivate = function () {
  56280. if (this._currentLOD) {
  56281. this._currentLOD._preActivate();
  56282. }
  56283. return this;
  56284. };
  56285. InstancedMesh.prototype._activate = function (renderId) {
  56286. if (this._currentLOD) {
  56287. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56288. }
  56289. return this;
  56290. };
  56291. /**
  56292. * Returns the current associated LOD AbstractMesh.
  56293. */
  56294. InstancedMesh.prototype.getLOD = function (camera) {
  56295. if (!camera) {
  56296. return this;
  56297. }
  56298. var boundingInfo = this.getBoundingInfo();
  56299. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56300. if (this._currentLOD === this.sourceMesh) {
  56301. return this;
  56302. }
  56303. return this._currentLOD;
  56304. };
  56305. InstancedMesh.prototype._syncSubMeshes = function () {
  56306. this.releaseSubMeshes();
  56307. if (this._sourceMesh.subMeshes) {
  56308. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56309. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56310. }
  56311. }
  56312. return this;
  56313. };
  56314. InstancedMesh.prototype._generatePointsArray = function () {
  56315. return this._sourceMesh._generatePointsArray();
  56316. };
  56317. /**
  56318. * Creates a new InstancedMesh from the current mesh.
  56319. * - name (string) : the cloned mesh name
  56320. * - newParent (optional Node) : the optional Node to parent the clone to.
  56321. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56322. *
  56323. * Returns the clone.
  56324. */
  56325. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56326. var result = this._sourceMesh.createInstance(name);
  56327. // Deep copy
  56328. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56329. // Bounding info
  56330. this.refreshBoundingInfo();
  56331. // Parent
  56332. if (newParent) {
  56333. result.parent = newParent;
  56334. }
  56335. if (!doNotCloneChildren) {
  56336. // Children
  56337. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56338. var mesh = this.getScene().meshes[index];
  56339. if (mesh.parent === this) {
  56340. mesh.clone(mesh.name, result);
  56341. }
  56342. }
  56343. }
  56344. result.computeWorldMatrix(true);
  56345. return result;
  56346. };
  56347. /**
  56348. * Disposes the InstancedMesh.
  56349. * Returns nothing.
  56350. */
  56351. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56352. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56353. // Remove from mesh
  56354. var index = this._sourceMesh.instances.indexOf(this);
  56355. this._sourceMesh.instances.splice(index, 1);
  56356. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56357. };
  56358. return InstancedMesh;
  56359. }(BABYLON.AbstractMesh));
  56360. BABYLON.InstancedMesh = InstancedMesh;
  56361. })(BABYLON || (BABYLON = {}));
  56362. //# sourceMappingURL=babylon.instancedMesh.js.map
  56363. "use strict";
  56364. var BABYLON;
  56365. (function (BABYLON) {
  56366. var LinesMesh = /** @class */ (function (_super) {
  56367. __extends(LinesMesh, _super);
  56368. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56369. if (scene === void 0) { scene = null; }
  56370. if (parent === void 0) { parent = null; }
  56371. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56372. _this.useVertexColor = useVertexColor;
  56373. _this.useVertexAlpha = useVertexAlpha;
  56374. _this.color = new BABYLON.Color3(1, 1, 1);
  56375. _this.alpha = 1;
  56376. if (source) {
  56377. _this.color = source.color.clone();
  56378. _this.alpha = source.alpha;
  56379. _this.useVertexColor = source.useVertexColor;
  56380. _this.useVertexAlpha = source.useVertexAlpha;
  56381. }
  56382. _this._intersectionThreshold = 0.1;
  56383. var defines = [];
  56384. var options = {
  56385. attributes: [BABYLON.VertexBuffer.PositionKind],
  56386. uniforms: ["world", "viewProjection"],
  56387. needAlphaBlending: true,
  56388. defines: defines
  56389. };
  56390. if (useVertexAlpha === false) {
  56391. options.needAlphaBlending = false;
  56392. }
  56393. if (!useVertexColor) {
  56394. options.uniforms.push("color");
  56395. }
  56396. else {
  56397. options.defines.push("#define VERTEXCOLOR");
  56398. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56399. }
  56400. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56401. return _this;
  56402. }
  56403. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56404. /**
  56405. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56406. * This margin is expressed in world space coordinates, so its value may vary.
  56407. * Default value is 0.1
  56408. * @returns the intersection Threshold value.
  56409. */
  56410. get: function () {
  56411. return this._intersectionThreshold;
  56412. },
  56413. /**
  56414. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56415. * This margin is expressed in world space coordinates, so its value may vary.
  56416. * @param value the new threshold to apply
  56417. */
  56418. set: function (value) {
  56419. if (this._intersectionThreshold === value) {
  56420. return;
  56421. }
  56422. this._intersectionThreshold = value;
  56423. if (this.geometry) {
  56424. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56425. }
  56426. },
  56427. enumerable: true,
  56428. configurable: true
  56429. });
  56430. /**
  56431. * Returns the string "LineMesh"
  56432. */
  56433. LinesMesh.prototype.getClassName = function () {
  56434. return "LinesMesh";
  56435. };
  56436. Object.defineProperty(LinesMesh.prototype, "material", {
  56437. get: function () {
  56438. return this._colorShader;
  56439. },
  56440. set: function (value) {
  56441. // Do nothing
  56442. },
  56443. enumerable: true,
  56444. configurable: true
  56445. });
  56446. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56447. get: function () {
  56448. return false;
  56449. },
  56450. enumerable: true,
  56451. configurable: true
  56452. });
  56453. LinesMesh.prototype.createInstance = function (name) {
  56454. throw new Error("LinesMeshes do not support createInstance.");
  56455. };
  56456. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56457. if (!this._geometry) {
  56458. return this;
  56459. }
  56460. // VBOs
  56461. this._geometry._bind(this._colorShader.getEffect());
  56462. // Color
  56463. if (!this.useVertexColor) {
  56464. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56465. }
  56466. return this;
  56467. };
  56468. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56469. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56470. return this;
  56471. }
  56472. var engine = this.getScene().getEngine();
  56473. // Draw order
  56474. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56475. return this;
  56476. };
  56477. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56478. this._colorShader.dispose();
  56479. _super.prototype.dispose.call(this, doNotRecurse);
  56480. };
  56481. /**
  56482. * Returns a new LineMesh object cloned from the current one.
  56483. */
  56484. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56485. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56486. };
  56487. return LinesMesh;
  56488. }(BABYLON.Mesh));
  56489. BABYLON.LinesMesh = LinesMesh;
  56490. })(BABYLON || (BABYLON = {}));
  56491. //# sourceMappingURL=babylon.linesMesh.js.map
  56492. "use strict";
  56493. var BABYLON;
  56494. (function (BABYLON) {
  56495. var MeshBuilder = /** @class */ (function () {
  56496. function MeshBuilder() {
  56497. }
  56498. MeshBuilder.updateSideOrientation = function (orientation) {
  56499. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56500. return BABYLON.Mesh.DOUBLESIDE;
  56501. }
  56502. if (orientation === undefined || orientation === null) {
  56503. return BABYLON.Mesh.FRONTSIDE;
  56504. }
  56505. return orientation;
  56506. };
  56507. /**
  56508. * Creates a box mesh.
  56509. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56510. * The parameter `size` sets the size (float) of each box side (default 1).
  56511. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56512. * 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).
  56513. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56514. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56515. * 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).
  56516. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56518. */
  56519. MeshBuilder.CreateBox = function (name, options, scene) {
  56520. if (scene === void 0) { scene = null; }
  56521. var box = new BABYLON.Mesh(name, scene);
  56522. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56523. box._originalBuilderSideOrientation = options.sideOrientation;
  56524. var vertexData = BABYLON.VertexData.CreateBox(options);
  56525. vertexData.applyToMesh(box, options.updatable);
  56526. return box;
  56527. };
  56528. /**
  56529. * Creates a sphere mesh.
  56530. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56531. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56532. * 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`).
  56533. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56534. * 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
  56535. * 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).
  56536. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56537. * 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).
  56538. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56540. */
  56541. MeshBuilder.CreateSphere = function (name, options, scene) {
  56542. var sphere = new BABYLON.Mesh(name, scene);
  56543. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56544. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56545. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56546. vertexData.applyToMesh(sphere, options.updatable);
  56547. return sphere;
  56548. };
  56549. /**
  56550. * Creates a plane polygonal mesh. By default, this is a disc.
  56551. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56552. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56553. * 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.
  56554. * 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
  56555. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56556. * 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).
  56557. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56559. */
  56560. MeshBuilder.CreateDisc = function (name, options, scene) {
  56561. if (scene === void 0) { scene = null; }
  56562. var disc = new BABYLON.Mesh(name, scene);
  56563. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56564. disc._originalBuilderSideOrientation = options.sideOrientation;
  56565. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56566. vertexData.applyToMesh(disc, options.updatable);
  56567. return disc;
  56568. };
  56569. /**
  56570. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56571. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56572. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56573. * 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`).
  56574. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56575. * 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.
  56576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56577. * 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).
  56578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56580. */
  56581. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56582. var sphere = new BABYLON.Mesh(name, scene);
  56583. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56584. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56585. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56586. vertexData.applyToMesh(sphere, options.updatable);
  56587. return sphere;
  56588. };
  56589. ;
  56590. /**
  56591. * Creates a ribbon mesh.
  56592. * 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.
  56593. *
  56594. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56595. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56596. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56597. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56598. * 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.
  56599. * 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.
  56600. * 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
  56601. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56602. * 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).
  56603. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56604. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56605. * 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.
  56606. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56607. * 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
  56608. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56609. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56611. */
  56612. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56613. if (scene === void 0) { scene = null; }
  56614. var pathArray = options.pathArray;
  56615. var closeArray = options.closeArray;
  56616. var closePath = options.closePath;
  56617. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56618. var instance = options.instance;
  56619. var updatable = options.updatable;
  56620. if (instance) {
  56621. // positionFunction : ribbon case
  56622. // only pathArray and sideOrientation parameters are taken into account for positions update
  56623. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56624. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56625. var positionFunction = function (positions) {
  56626. var minlg = pathArray[0].length;
  56627. var i = 0;
  56628. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56629. for (var si = 1; si <= ns; si++) {
  56630. for (var p = 0; p < pathArray.length; p++) {
  56631. var path = pathArray[p];
  56632. var l = path.length;
  56633. minlg = (minlg < l) ? minlg : l;
  56634. var j = 0;
  56635. while (j < minlg) {
  56636. positions[i] = path[j].x;
  56637. positions[i + 1] = path[j].y;
  56638. positions[i + 2] = path[j].z;
  56639. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56640. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56641. }
  56642. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56643. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56644. }
  56645. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56646. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56647. }
  56648. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56649. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56650. }
  56651. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56652. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56653. }
  56654. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56655. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56656. }
  56657. j++;
  56658. i += 3;
  56659. }
  56660. if (instance._closePath) {
  56661. positions[i] = path[0].x;
  56662. positions[i + 1] = path[0].y;
  56663. positions[i + 2] = path[0].z;
  56664. i += 3;
  56665. }
  56666. }
  56667. }
  56668. };
  56669. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56670. positionFunction(positions);
  56671. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56672. instance._boundingInfo.update(instance._worldMatrix);
  56673. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56674. if (options.colors) {
  56675. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56676. for (var c = 0; c < options.colors.length; c++) {
  56677. colors[c * 4] = options.colors[c].r;
  56678. colors[c * 4 + 1] = options.colors[c].g;
  56679. colors[c * 4 + 2] = options.colors[c].b;
  56680. colors[c * 4 + 3] = options.colors[c].a;
  56681. }
  56682. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56683. }
  56684. if (options.uvs) {
  56685. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56686. for (var i = 0; i < options.uvs.length; i++) {
  56687. uvs[i * 2] = options.uvs[i].x;
  56688. uvs[i * 2 + 1] = options.uvs[i].y;
  56689. }
  56690. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56691. }
  56692. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56693. var indices = instance.getIndices();
  56694. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56695. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56696. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56697. if (instance._closePath) {
  56698. var indexFirst = 0;
  56699. var indexLast = 0;
  56700. for (var p = 0; p < pathArray.length; p++) {
  56701. indexFirst = instance._idx[p] * 3;
  56702. if (p + 1 < pathArray.length) {
  56703. indexLast = (instance._idx[p + 1] - 1) * 3;
  56704. }
  56705. else {
  56706. indexLast = normals.length - 3;
  56707. }
  56708. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56709. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56710. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56711. normals[indexLast] = normals[indexFirst];
  56712. normals[indexLast + 1] = normals[indexFirst + 1];
  56713. normals[indexLast + 2] = normals[indexFirst + 2];
  56714. }
  56715. }
  56716. if (!(instance.areNormalsFrozen)) {
  56717. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56718. }
  56719. }
  56720. return instance;
  56721. }
  56722. else {
  56723. var ribbon = new BABYLON.Mesh(name, scene);
  56724. ribbon._originalBuilderSideOrientation = sideOrientation;
  56725. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56726. if (closePath) {
  56727. ribbon._idx = vertexData._idx;
  56728. }
  56729. ribbon._closePath = closePath;
  56730. ribbon._closeArray = closeArray;
  56731. vertexData.applyToMesh(ribbon, updatable);
  56732. return ribbon;
  56733. }
  56734. };
  56735. /**
  56736. * Creates a cylinder or a cone mesh.
  56737. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56738. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56739. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56740. * 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.
  56741. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56742. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56743. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56744. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56745. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56746. * 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).
  56747. * 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
  56748. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56749. * 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
  56750. * 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.
  56751. * If `enclose` is false, a ring surface is one element.
  56752. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56753. * 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
  56754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56755. * 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).
  56756. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56758. */
  56759. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56760. var cylinder = new BABYLON.Mesh(name, scene);
  56761. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56762. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56763. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56764. vertexData.applyToMesh(cylinder, options.updatable);
  56765. return cylinder;
  56766. };
  56767. /**
  56768. * Creates a torus mesh.
  56769. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56770. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56771. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56772. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56774. * 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).
  56775. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56777. */
  56778. MeshBuilder.CreateTorus = function (name, options, scene) {
  56779. var torus = new BABYLON.Mesh(name, scene);
  56780. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56781. torus._originalBuilderSideOrientation = options.sideOrientation;
  56782. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56783. vertexData.applyToMesh(torus, options.updatable);
  56784. return torus;
  56785. };
  56786. /**
  56787. * Creates a torus knot mesh.
  56788. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56789. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56790. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56791. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56792. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56793. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56794. * 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).
  56795. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56797. */
  56798. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56799. var torusKnot = new BABYLON.Mesh(name, scene);
  56800. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56801. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56802. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56803. vertexData.applyToMesh(torusKnot, options.updatable);
  56804. return torusKnot;
  56805. };
  56806. /**
  56807. * Creates a line system mesh.
  56808. * A line system is a pool of many lines gathered in a single mesh.
  56809. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56810. * 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.
  56811. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56812. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56813. * 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
  56814. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56815. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56816. * 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
  56817. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56819. */
  56820. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56821. var instance = options.instance;
  56822. var lines = options.lines;
  56823. var colors = options.colors;
  56824. if (instance) {
  56825. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56826. var vertexColor;
  56827. var lineColors;
  56828. if (colors) {
  56829. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56830. }
  56831. var i = 0;
  56832. var c = 0;
  56833. for (var l = 0; l < lines.length; l++) {
  56834. var points = lines[l];
  56835. for (var p = 0; p < points.length; p++) {
  56836. positions[i] = points[p].x;
  56837. positions[i + 1] = points[p].y;
  56838. positions[i + 2] = points[p].z;
  56839. if (colors && vertexColor) {
  56840. lineColors = colors[l];
  56841. vertexColor[c] = lineColors[p].r;
  56842. vertexColor[c + 1] = lineColors[p].g;
  56843. vertexColor[c + 2] = lineColors[p].b;
  56844. vertexColor[c + 3] = lineColors[p].a;
  56845. c += 4;
  56846. }
  56847. i += 3;
  56848. }
  56849. }
  56850. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56851. if (colors && vertexColor) {
  56852. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56853. }
  56854. return instance;
  56855. }
  56856. // line system creation
  56857. var useVertexColor = (colors) ? true : false;
  56858. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56859. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56860. vertexData.applyToMesh(lineSystem, options.updatable);
  56861. return lineSystem;
  56862. };
  56863. /**
  56864. * Creates a line mesh.
  56865. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56866. * 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.
  56867. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56868. * The parameter `points` is an array successive Vector3.
  56869. * 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
  56870. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56871. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56872. * When updating an instance, remember that only point positions can change, not the number of points.
  56873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56874. */
  56875. MeshBuilder.CreateLines = function (name, options, scene) {
  56876. if (scene === void 0) { scene = null; }
  56877. var colors = (options.colors) ? [options.colors] : null;
  56878. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56879. return lines;
  56880. };
  56881. /**
  56882. * Creates a dashed line mesh.
  56883. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56884. * 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.
  56885. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56886. * The parameter `points` is an array successive Vector3.
  56887. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56888. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56889. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56890. * 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
  56891. * When updating an instance, remember that only point positions can change, not the number of points.
  56892. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56893. */
  56894. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56895. if (scene === void 0) { scene = null; }
  56896. var points = options.points;
  56897. var instance = options.instance;
  56898. var gapSize = options.gapSize || 1;
  56899. var dashSize = options.dashSize || 3;
  56900. if (instance) {
  56901. var positionFunction = function (positions) {
  56902. var curvect = BABYLON.Vector3.Zero();
  56903. var nbSeg = positions.length / 6;
  56904. var lg = 0;
  56905. var nb = 0;
  56906. var shft = 0;
  56907. var dashshft = 0;
  56908. var curshft = 0;
  56909. var p = 0;
  56910. var i = 0;
  56911. var j = 0;
  56912. for (i = 0; i < points.length - 1; i++) {
  56913. points[i + 1].subtractToRef(points[i], curvect);
  56914. lg += curvect.length();
  56915. }
  56916. shft = lg / nbSeg;
  56917. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56918. for (i = 0; i < points.length - 1; i++) {
  56919. points[i + 1].subtractToRef(points[i], curvect);
  56920. nb = Math.floor(curvect.length() / shft);
  56921. curvect.normalize();
  56922. j = 0;
  56923. while (j < nb && p < positions.length) {
  56924. curshft = shft * j;
  56925. positions[p] = points[i].x + curshft * curvect.x;
  56926. positions[p + 1] = points[i].y + curshft * curvect.y;
  56927. positions[p + 2] = points[i].z + curshft * curvect.z;
  56928. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56929. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56930. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56931. p += 6;
  56932. j++;
  56933. }
  56934. }
  56935. while (p < positions.length) {
  56936. positions[p] = points[i].x;
  56937. positions[p + 1] = points[i].y;
  56938. positions[p + 2] = points[i].z;
  56939. p += 3;
  56940. }
  56941. };
  56942. instance.updateMeshPositions(positionFunction, false);
  56943. return instance;
  56944. }
  56945. // dashed lines creation
  56946. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56947. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56948. vertexData.applyToMesh(dashedLines, options.updatable);
  56949. dashedLines.dashSize = dashSize;
  56950. dashedLines.gapSize = gapSize;
  56951. return dashedLines;
  56952. };
  56953. /**
  56954. * Creates an extruded shape mesh.
  56955. * 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.
  56956. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56957. *
  56958. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56959. * 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
  56960. * extruded along the Z axis.
  56961. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56962. * 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.
  56963. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56964. * 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
  56965. * 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
  56966. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56967. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56968. * 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).
  56969. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56970. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56972. */
  56973. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56974. if (scene === void 0) { scene = null; }
  56975. var path = options.path;
  56976. var shape = options.shape;
  56977. var scale = options.scale || 1;
  56978. var rotation = options.rotation || 0;
  56979. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56980. var updatable = options.updatable;
  56981. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56982. var instance = options.instance || null;
  56983. var invertUV = options.invertUV || false;
  56984. 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);
  56985. };
  56986. /**
  56987. * Creates an custom extruded shape mesh.
  56988. * 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.
  56989. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56990. *
  56991. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56992. * 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
  56993. * extruded along the Z axis.
  56994. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56995. * 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
  56996. * and the distance of this point from the begining of the path :
  56997. * ```javascript
  56998. * var rotationFunction = function(i, distance) {
  56999. * // do things
  57000. * return rotationValue; }
  57001. * ```
  57002. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  57003. * 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
  57004. * and the distance of this point from the begining of the path :
  57005. * ```javascript
  57006. * var scaleFunction = function(i, distance) {
  57007. * // do things
  57008. * return scaleValue;}
  57009. * ```
  57010. * It must returns a float value that will be the scale value applied to the shape on each path point.
  57011. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  57012. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  57013. * 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
  57014. * 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
  57015. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57016. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57017. * 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).
  57018. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57019. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57021. */
  57022. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  57023. var path = options.path;
  57024. var shape = options.shape;
  57025. var scaleFunction = options.scaleFunction || (function () { return 1; });
  57026. var rotationFunction = options.rotationFunction || (function () { return 0; });
  57027. var ribbonCloseArray = options.ribbonCloseArray || false;
  57028. var ribbonClosePath = options.ribbonClosePath || false;
  57029. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57030. var updatable = options.updatable;
  57031. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57032. var instance = options.instance;
  57033. var invertUV = options.invertUV || false;
  57034. 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);
  57035. };
  57036. /**
  57037. * Creates lathe mesh.
  57038. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  57039. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  57040. *
  57041. * 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
  57042. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  57043. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  57044. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  57045. * 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.
  57046. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  57047. * 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
  57048. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57049. * 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).
  57050. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57051. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57053. */
  57054. MeshBuilder.CreateLathe = function (name, options, scene) {
  57055. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  57056. var closed = (options.closed === undefined) ? true : options.closed;
  57057. var shape = options.shape;
  57058. var radius = options.radius || 1;
  57059. var tessellation = options.tessellation || 64;
  57060. var updatable = options.updatable;
  57061. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57062. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57063. var pi2 = Math.PI * 2;
  57064. var paths = new Array();
  57065. var invertUV = options.invertUV || false;
  57066. var i = 0;
  57067. var p = 0;
  57068. var step = pi2 / tessellation * arc;
  57069. var rotated;
  57070. var path = new Array();
  57071. ;
  57072. for (i = 0; i <= tessellation; i++) {
  57073. var path = [];
  57074. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  57075. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  57076. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  57077. }
  57078. for (p = 0; p < shape.length; p++) {
  57079. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  57080. path.push(rotated);
  57081. }
  57082. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  57083. 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));
  57084. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57085. }
  57086. paths.push(path);
  57087. }
  57088. // lathe ribbon
  57089. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57090. return lathe;
  57091. };
  57092. /**
  57093. * Creates a plane mesh.
  57094. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57095. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57096. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57097. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57099. * 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).
  57100. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57102. */
  57103. MeshBuilder.CreatePlane = function (name, options, scene) {
  57104. var plane = new BABYLON.Mesh(name, scene);
  57105. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57106. plane._originalBuilderSideOrientation = options.sideOrientation;
  57107. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57108. vertexData.applyToMesh(plane, options.updatable);
  57109. if (options.sourcePlane) {
  57110. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57111. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57112. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57113. plane.rotate(vectorProduct, product);
  57114. }
  57115. return plane;
  57116. };
  57117. /**
  57118. * Creates a ground mesh.
  57119. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57120. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57121. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57123. */
  57124. MeshBuilder.CreateGround = function (name, options, scene) {
  57125. var ground = new BABYLON.GroundMesh(name, scene);
  57126. ground._setReady(false);
  57127. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57128. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57129. ground._width = options.width || 1;
  57130. ground._height = options.height || 1;
  57131. ground._maxX = ground._width / 2;
  57132. ground._maxZ = ground._height / 2;
  57133. ground._minX = -ground._maxX;
  57134. ground._minZ = -ground._maxZ;
  57135. var vertexData = BABYLON.VertexData.CreateGround(options);
  57136. vertexData.applyToMesh(ground, options.updatable);
  57137. ground._setReady(true);
  57138. return ground;
  57139. };
  57140. /**
  57141. * Creates a tiled ground mesh.
  57142. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57143. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57144. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57145. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57146. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57147. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57148. * numbers of subdivisions on the ground width and height of each tile.
  57149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57150. */
  57151. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57152. var tiledGround = new BABYLON.Mesh(name, scene);
  57153. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57154. vertexData.applyToMesh(tiledGround, options.updatable);
  57155. return tiledGround;
  57156. };
  57157. /**
  57158. * Creates a ground mesh from a height map.
  57159. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57160. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57161. * The parameter `url` sets the URL of the height map image resource.
  57162. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57163. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57164. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57165. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57166. * 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.
  57167. * 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).
  57168. * This function is passed the newly built mesh :
  57169. * ```javascript
  57170. * function(mesh) { // do things
  57171. * return; }
  57172. * ```
  57173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57174. */
  57175. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57176. var width = options.width || 10.0;
  57177. var height = options.height || 10.0;
  57178. var subdivisions = options.subdivisions || 1 | 0;
  57179. var minHeight = options.minHeight || 0.0;
  57180. var maxHeight = options.maxHeight || 1.0;
  57181. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57182. var updatable = options.updatable;
  57183. var onReady = options.onReady;
  57184. var ground = new BABYLON.GroundMesh(name, scene);
  57185. ground._subdivisionsX = subdivisions;
  57186. ground._subdivisionsY = subdivisions;
  57187. ground._width = width;
  57188. ground._height = height;
  57189. ground._maxX = ground._width / 2.0;
  57190. ground._maxZ = ground._height / 2.0;
  57191. ground._minX = -ground._maxX;
  57192. ground._minZ = -ground._maxZ;
  57193. ground._setReady(false);
  57194. var onload = function (img) {
  57195. // Getting height map data
  57196. var canvas = document.createElement("canvas");
  57197. var context = canvas.getContext("2d");
  57198. if (!context) {
  57199. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57200. }
  57201. if (scene.isDisposed) {
  57202. return;
  57203. }
  57204. var bufferWidth = img.width;
  57205. var bufferHeight = img.height;
  57206. canvas.width = bufferWidth;
  57207. canvas.height = bufferHeight;
  57208. context.drawImage(img, 0, 0);
  57209. // Create VertexData from map data
  57210. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57211. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57212. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57213. width: width, height: height,
  57214. subdivisions: subdivisions,
  57215. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57216. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57217. });
  57218. vertexData.applyToMesh(ground, updatable);
  57219. //execute ready callback, if set
  57220. if (onReady) {
  57221. onReady(ground);
  57222. }
  57223. ground._setReady(true);
  57224. };
  57225. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57226. return ground;
  57227. };
  57228. /**
  57229. * Creates a polygon mesh.
  57230. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57231. * 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.
  57232. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57234. * 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).
  57235. * Remember you can only change the shape positions, not their number when updating a polygon.
  57236. */
  57237. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57238. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57239. var shape = options.shape;
  57240. var holes = options.holes || [];
  57241. var depth = options.depth || 0;
  57242. var contours = [];
  57243. var hole = [];
  57244. for (var i = 0; i < shape.length; i++) {
  57245. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57246. }
  57247. var epsilon = 0.00000001;
  57248. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57249. contours.pop();
  57250. }
  57251. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57252. for (var hNb = 0; hNb < holes.length; hNb++) {
  57253. hole = [];
  57254. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57255. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57256. }
  57257. polygonTriangulation.addHole(hole);
  57258. }
  57259. var polygon = polygonTriangulation.build(options.updatable, depth);
  57260. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57261. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57262. vertexData.applyToMesh(polygon, options.updatable);
  57263. return polygon;
  57264. };
  57265. ;
  57266. /**
  57267. * Creates an extruded polygon mesh, with depth in the Y direction.
  57268. * 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).
  57269. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57270. */
  57271. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57272. return MeshBuilder.CreatePolygon(name, options, scene);
  57273. };
  57274. ;
  57275. /**
  57276. * Creates a tube mesh.
  57277. * 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.
  57278. *
  57279. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57280. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57281. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57282. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57283. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57284. * 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.
  57285. * It must return a radius value (positive float) :
  57286. * ```javascript
  57287. * var radiusFunction = function(i, distance) {
  57288. * // do things
  57289. * return radius; }
  57290. * ```
  57291. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57292. * 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
  57293. * 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
  57294. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57295. * 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).
  57296. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57297. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57298. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57299. */
  57300. MeshBuilder.CreateTube = function (name, options, scene) {
  57301. var path = options.path;
  57302. var instance = options.instance;
  57303. var radius = 1.0;
  57304. if (instance) {
  57305. radius = instance.radius;
  57306. }
  57307. if (options.radius !== undefined) {
  57308. radius = options.radius;
  57309. }
  57310. ;
  57311. var tessellation = options.tessellation || 64 | 0;
  57312. var radiusFunction = options.radiusFunction || null;
  57313. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57314. var invertUV = options.invertUV || false;
  57315. var updatable = options.updatable;
  57316. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57317. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57318. // tube geometry
  57319. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57320. var tangents = path3D.getTangents();
  57321. var normals = path3D.getNormals();
  57322. var distances = path3D.getDistances();
  57323. var pi2 = Math.PI * 2;
  57324. var step = pi2 / tessellation * arc;
  57325. var returnRadius = function () { return radius; };
  57326. var radiusFunctionFinal = radiusFunction || returnRadius;
  57327. var circlePath;
  57328. var rad;
  57329. var normal;
  57330. var rotated;
  57331. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57332. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57333. for (var i = 0; i < path.length; i++) {
  57334. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57335. circlePath = Array(); // current circle array
  57336. normal = normals[i]; // current normal
  57337. for (var t = 0; t < tessellation; t++) {
  57338. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57339. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57340. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57341. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57342. circlePath[t] = rotated;
  57343. }
  57344. circlePaths[index] = circlePath;
  57345. index++;
  57346. }
  57347. // cap
  57348. var capPath = function (nbPoints, pathIndex) {
  57349. var pointCap = Array();
  57350. for (var i = 0; i < nbPoints; i++) {
  57351. pointCap.push(path[pathIndex]);
  57352. }
  57353. return pointCap;
  57354. };
  57355. switch (cap) {
  57356. case BABYLON.Mesh.NO_CAP:
  57357. break;
  57358. case BABYLON.Mesh.CAP_START:
  57359. circlePaths[0] = capPath(tessellation, 0);
  57360. circlePaths[1] = circlePaths[2].slice(0);
  57361. break;
  57362. case BABYLON.Mesh.CAP_END:
  57363. circlePaths[index] = circlePaths[index - 1].slice(0);
  57364. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57365. break;
  57366. case BABYLON.Mesh.CAP_ALL:
  57367. circlePaths[0] = capPath(tessellation, 0);
  57368. circlePaths[1] = circlePaths[2].slice(0);
  57369. circlePaths[index] = circlePaths[index - 1].slice(0);
  57370. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57371. break;
  57372. default:
  57373. break;
  57374. }
  57375. return circlePaths;
  57376. };
  57377. var path3D;
  57378. var pathArray;
  57379. if (instance) {
  57380. var arc = options.arc || instance.arc;
  57381. path3D = (instance.path3D).update(path);
  57382. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57383. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57384. instance.path3D = path3D;
  57385. instance.pathArray = pathArray;
  57386. instance.arc = arc;
  57387. instance.radius = radius;
  57388. return instance;
  57389. }
  57390. // tube creation
  57391. path3D = new BABYLON.Path3D(path);
  57392. var newPathArray = new Array();
  57393. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57394. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57395. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57396. tube.pathArray = pathArray;
  57397. tube.path3D = path3D;
  57398. tube.tessellation = tessellation;
  57399. tube.cap = cap;
  57400. tube.arc = options.arc;
  57401. tube.radius = radius;
  57402. return tube;
  57403. };
  57404. /**
  57405. * Creates a polyhedron mesh.
  57406. *
  57407. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57408. * 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
  57409. * to choose the wanted type.
  57410. * The parameter `size` (positive float, default 1) sets the polygon size.
  57411. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57412. * 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`.
  57413. * 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
  57414. * 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)`).
  57415. * 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
  57416. * 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.
  57417. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57418. * 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).
  57419. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57421. */
  57422. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57423. var polyhedron = new BABYLON.Mesh(name, scene);
  57424. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57425. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57426. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57427. vertexData.applyToMesh(polyhedron, options.updatable);
  57428. return polyhedron;
  57429. };
  57430. /**
  57431. * Creates a decal mesh.
  57432. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57433. * 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.
  57434. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57435. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57436. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57437. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57438. */
  57439. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57440. var indices = sourceMesh.getIndices();
  57441. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57442. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57443. var position = options.position || BABYLON.Vector3.Zero();
  57444. var normal = options.normal || BABYLON.Vector3.Up();
  57445. var size = options.size || BABYLON.Vector3.One();
  57446. var angle = options.angle || 0;
  57447. // Getting correct rotation
  57448. if (!normal) {
  57449. var target = new BABYLON.Vector3(0, 0, 1);
  57450. var camera = sourceMesh.getScene().activeCamera;
  57451. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57452. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57453. }
  57454. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57455. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57456. var pitch = Math.atan2(normal.y, len);
  57457. // Matrix
  57458. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57459. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57460. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57461. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57462. var vertexData = new BABYLON.VertexData();
  57463. vertexData.indices = [];
  57464. vertexData.positions = [];
  57465. vertexData.normals = [];
  57466. vertexData.uvs = [];
  57467. var currentVertexDataIndex = 0;
  57468. var extractDecalVector3 = function (indexId) {
  57469. var result = new BABYLON.PositionNormalVertex();
  57470. if (!indices || !positions || !normals) {
  57471. return result;
  57472. }
  57473. var vertexId = indices[indexId];
  57474. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57475. // Send vector to decal local world
  57476. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57477. // Get normal
  57478. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57479. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57480. return result;
  57481. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57482. var clip = function (vertices, axis) {
  57483. if (vertices.length === 0) {
  57484. return vertices;
  57485. }
  57486. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57487. var clipVertices = function (v0, v1) {
  57488. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57489. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57490. };
  57491. var result = new Array();
  57492. for (var index = 0; index < vertices.length; index += 3) {
  57493. var v1Out;
  57494. var v2Out;
  57495. var v3Out;
  57496. var total = 0;
  57497. var nV1 = null;
  57498. var nV2 = null;
  57499. var nV3 = null;
  57500. var nV4 = null;
  57501. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57502. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57503. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57504. v1Out = d1 > 0;
  57505. v2Out = d2 > 0;
  57506. v3Out = d3 > 0;
  57507. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57508. switch (total) {
  57509. case 0:
  57510. result.push(vertices[index]);
  57511. result.push(vertices[index + 1]);
  57512. result.push(vertices[index + 2]);
  57513. break;
  57514. case 1:
  57515. if (v1Out) {
  57516. nV1 = vertices[index + 1];
  57517. nV2 = vertices[index + 2];
  57518. nV3 = clipVertices(vertices[index], nV1);
  57519. nV4 = clipVertices(vertices[index], nV2);
  57520. }
  57521. if (v2Out) {
  57522. nV1 = vertices[index];
  57523. nV2 = vertices[index + 2];
  57524. nV3 = clipVertices(vertices[index + 1], nV1);
  57525. nV4 = clipVertices(vertices[index + 1], nV2);
  57526. result.push(nV3);
  57527. result.push(nV2.clone());
  57528. result.push(nV1.clone());
  57529. result.push(nV2.clone());
  57530. result.push(nV3.clone());
  57531. result.push(nV4);
  57532. break;
  57533. }
  57534. if (v3Out) {
  57535. nV1 = vertices[index];
  57536. nV2 = vertices[index + 1];
  57537. nV3 = clipVertices(vertices[index + 2], nV1);
  57538. nV4 = clipVertices(vertices[index + 2], nV2);
  57539. }
  57540. if (nV1 && nV2 && nV3 && nV4) {
  57541. result.push(nV1.clone());
  57542. result.push(nV2.clone());
  57543. result.push(nV3);
  57544. result.push(nV4);
  57545. result.push(nV3.clone());
  57546. result.push(nV2.clone());
  57547. }
  57548. break;
  57549. case 2:
  57550. if (!v1Out) {
  57551. nV1 = vertices[index].clone();
  57552. nV2 = clipVertices(nV1, vertices[index + 1]);
  57553. nV3 = clipVertices(nV1, vertices[index + 2]);
  57554. result.push(nV1);
  57555. result.push(nV2);
  57556. result.push(nV3);
  57557. }
  57558. if (!v2Out) {
  57559. nV1 = vertices[index + 1].clone();
  57560. nV2 = clipVertices(nV1, vertices[index + 2]);
  57561. nV3 = clipVertices(nV1, vertices[index]);
  57562. result.push(nV1);
  57563. result.push(nV2);
  57564. result.push(nV3);
  57565. }
  57566. if (!v3Out) {
  57567. nV1 = vertices[index + 2].clone();
  57568. nV2 = clipVertices(nV1, vertices[index]);
  57569. nV3 = clipVertices(nV1, vertices[index + 1]);
  57570. result.push(nV1);
  57571. result.push(nV2);
  57572. result.push(nV3);
  57573. }
  57574. break;
  57575. case 3:
  57576. break;
  57577. }
  57578. }
  57579. return result;
  57580. };
  57581. for (var index = 0; index < indices.length; index += 3) {
  57582. var faceVertices = new Array();
  57583. faceVertices.push(extractDecalVector3(index));
  57584. faceVertices.push(extractDecalVector3(index + 1));
  57585. faceVertices.push(extractDecalVector3(index + 2));
  57586. // Clip
  57587. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57588. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57589. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57590. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57591. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57592. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57593. if (faceVertices.length === 0) {
  57594. continue;
  57595. }
  57596. // Add UVs and get back to world
  57597. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57598. var vertex = faceVertices[vIndex];
  57599. //TODO check for Int32Array | Uint32Array | Uint16Array
  57600. vertexData.indices.push(currentVertexDataIndex);
  57601. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57602. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57603. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57604. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57605. currentVertexDataIndex++;
  57606. }
  57607. }
  57608. // Return mesh
  57609. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57610. vertexData.applyToMesh(decal);
  57611. decal.position = position.clone();
  57612. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57613. return decal;
  57614. };
  57615. // Privates
  57616. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57617. // extrusion geometry
  57618. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57619. var tangents = path3D.getTangents();
  57620. var normals = path3D.getNormals();
  57621. var binormals = path3D.getBinormals();
  57622. var distances = path3D.getDistances();
  57623. var angle = 0;
  57624. var returnScale = function () { return scale !== null ? scale : 1; };
  57625. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57626. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57627. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57628. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57629. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57630. for (var i = 0; i < curve.length; i++) {
  57631. var shapePath = new Array();
  57632. var angleStep = rotate(i, distances[i]);
  57633. var scaleRatio = scl(i, distances[i]);
  57634. for (var p = 0; p < shape.length; p++) {
  57635. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57636. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57637. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57638. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57639. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57640. shapePath[p] = rotated;
  57641. }
  57642. shapePaths[index] = shapePath;
  57643. angle += angleStep;
  57644. index++;
  57645. }
  57646. // cap
  57647. var capPath = function (shapePath) {
  57648. var pointCap = Array();
  57649. var barycenter = BABYLON.Vector3.Zero();
  57650. var i;
  57651. for (i = 0; i < shapePath.length; i++) {
  57652. barycenter.addInPlace(shapePath[i]);
  57653. }
  57654. barycenter.scaleInPlace(1.0 / shapePath.length);
  57655. for (i = 0; i < shapePath.length; i++) {
  57656. pointCap.push(barycenter);
  57657. }
  57658. return pointCap;
  57659. };
  57660. switch (cap) {
  57661. case BABYLON.Mesh.NO_CAP:
  57662. break;
  57663. case BABYLON.Mesh.CAP_START:
  57664. shapePaths[0] = capPath(shapePaths[2]);
  57665. shapePaths[1] = shapePaths[2];
  57666. break;
  57667. case BABYLON.Mesh.CAP_END:
  57668. shapePaths[index] = shapePaths[index - 1];
  57669. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57670. break;
  57671. case BABYLON.Mesh.CAP_ALL:
  57672. shapePaths[0] = capPath(shapePaths[2]);
  57673. shapePaths[1] = shapePaths[2];
  57674. shapePaths[index] = shapePaths[index - 1];
  57675. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57676. break;
  57677. default:
  57678. break;
  57679. }
  57680. return shapePaths;
  57681. };
  57682. var path3D;
  57683. var pathArray;
  57684. if (instance) {
  57685. path3D = (instance.path3D).update(curve);
  57686. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57687. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57688. return instance;
  57689. }
  57690. // extruded shape creation
  57691. path3D = new BABYLON.Path3D(curve);
  57692. var newShapePaths = new Array();
  57693. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57694. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57695. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57696. extrudedGeneric.pathArray = pathArray;
  57697. extrudedGeneric.path3D = path3D;
  57698. extrudedGeneric.cap = cap;
  57699. return extrudedGeneric;
  57700. };
  57701. return MeshBuilder;
  57702. }());
  57703. BABYLON.MeshBuilder = MeshBuilder;
  57704. })(BABYLON || (BABYLON = {}));
  57705. //# sourceMappingURL=babylon.meshBuilder.js.map
  57706. "use strict";
  57707. var BABYLON;
  57708. (function (BABYLON) {
  57709. /**
  57710. * Draco compression (https://google.github.io/draco/)
  57711. */
  57712. var DracoCompression = /** @class */ (function () {
  57713. /**
  57714. * Constructor
  57715. * @param numWorkers The number of workers for async operations
  57716. */
  57717. function DracoCompression(numWorkers) {
  57718. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57719. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57720. if (!workerBlobUrl || !Worker) {
  57721. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57722. return;
  57723. }
  57724. var workers = new Array(numWorkers);
  57725. for (var i = 0; i < workers.length; i++) {
  57726. var worker = new Worker(workerBlobUrl);
  57727. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57728. workers[i] = worker;
  57729. }
  57730. this._workerPool = new BABYLON.WorkerPool(workers);
  57731. }
  57732. /**
  57733. * Stop all async operations and release resources.
  57734. */
  57735. DracoCompression.prototype.dispose = function () {
  57736. this._workerPool.dispose();
  57737. delete this._workerPool;
  57738. };
  57739. /**
  57740. * Decode Draco compressed mesh data to vertex data.
  57741. * @param data The array buffer view for the Draco compression data
  57742. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57743. * @returns A promise that resolves with the decoded vertex data
  57744. */
  57745. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57746. var _this = this;
  57747. return new Promise(function (resolve, reject) {
  57748. _this._workerPool.push(function (worker, onComplete) {
  57749. var vertexData = new BABYLON.VertexData();
  57750. var onError = function (error) {
  57751. worker.removeEventListener("error", onError);
  57752. worker.removeEventListener("message", onMessage);
  57753. reject(error);
  57754. onComplete();
  57755. };
  57756. var onMessage = function (message) {
  57757. if (message.data === "done") {
  57758. worker.removeEventListener("error", onError);
  57759. worker.removeEventListener("message", onMessage);
  57760. resolve(vertexData);
  57761. onComplete();
  57762. }
  57763. else if (message.data.id === "indices") {
  57764. vertexData.indices = message.data.value;
  57765. }
  57766. else {
  57767. vertexData.set(message.data.value, message.data.id);
  57768. }
  57769. };
  57770. worker.addEventListener("error", onError);
  57771. worker.addEventListener("message", onMessage);
  57772. var dataCopy = new Uint8Array(data.byteLength);
  57773. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57774. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57775. });
  57776. });
  57777. };
  57778. /**
  57779. * The worker function that gets converted to a blob url to pass into a worker.
  57780. */
  57781. DracoCompression._Worker = function () {
  57782. // self is actually a DedicatedWorkerGlobalScope
  57783. var _self = self;
  57784. var decodeMesh = function (data, attributes) {
  57785. var dracoModule = new DracoDecoderModule();
  57786. var buffer = new dracoModule.DecoderBuffer();
  57787. buffer.Init(data, data.byteLength);
  57788. var decoder = new dracoModule.Decoder();
  57789. var geometry;
  57790. var status;
  57791. try {
  57792. var type = decoder.GetEncodedGeometryType(buffer);
  57793. switch (type) {
  57794. case dracoModule.TRIANGULAR_MESH:
  57795. geometry = new dracoModule.Mesh();
  57796. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57797. break;
  57798. case dracoModule.POINT_CLOUD:
  57799. geometry = new dracoModule.PointCloud();
  57800. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57801. break;
  57802. default:
  57803. throw new Error("Invalid geometry type " + type);
  57804. }
  57805. if (!status.ok() || !geometry.ptr) {
  57806. throw new Error(status.error_msg());
  57807. }
  57808. var numPoints = geometry.num_points();
  57809. if (type === dracoModule.TRIANGULAR_MESH) {
  57810. var numFaces = geometry.num_faces();
  57811. var faceIndices = new dracoModule.DracoInt32Array();
  57812. try {
  57813. var indices = new Uint32Array(numFaces * 3);
  57814. for (var i = 0; i < numFaces; i++) {
  57815. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57816. var offset = i * 3;
  57817. indices[offset + 0] = faceIndices.GetValue(0);
  57818. indices[offset + 1] = faceIndices.GetValue(1);
  57819. indices[offset + 2] = faceIndices.GetValue(2);
  57820. }
  57821. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57822. }
  57823. finally {
  57824. dracoModule.destroy(faceIndices);
  57825. }
  57826. }
  57827. for (var kind in attributes) {
  57828. var uniqueId = attributes[kind];
  57829. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57830. var dracoData = new dracoModule.DracoFloat32Array();
  57831. try {
  57832. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57833. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57834. for (var i = 0; i < babylonData.length; i++) {
  57835. babylonData[i] = dracoData.GetValue(i);
  57836. }
  57837. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57838. }
  57839. finally {
  57840. dracoModule.destroy(dracoData);
  57841. }
  57842. }
  57843. }
  57844. finally {
  57845. if (geometry) {
  57846. dracoModule.destroy(geometry);
  57847. }
  57848. dracoModule.destroy(decoder);
  57849. dracoModule.destroy(buffer);
  57850. }
  57851. _self.postMessage("done");
  57852. };
  57853. _self.onmessage = function (event) {
  57854. switch (event.data.id) {
  57855. case "initDecoder": {
  57856. importScripts(event.data.url);
  57857. break;
  57858. }
  57859. case "decodeMesh": {
  57860. decodeMesh(event.data.data, event.data.attributes);
  57861. break;
  57862. }
  57863. }
  57864. };
  57865. };
  57866. DracoCompression._GetDefaultDecoderUrl = function () {
  57867. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57868. return null;
  57869. }
  57870. for (var i = 0; i < document.scripts.length; i++) {
  57871. if (document.scripts[i].type === "text/x-draco-decoder") {
  57872. return document.scripts[i].src;
  57873. }
  57874. }
  57875. return null;
  57876. };
  57877. /**
  57878. * Gets the url to the draco decoder if available.
  57879. */
  57880. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57881. return DracoCompression;
  57882. }());
  57883. BABYLON.DracoCompression = DracoCompression;
  57884. })(BABYLON || (BABYLON = {}));
  57885. //# sourceMappingURL=babylon.dracoCompression.js.map
  57886. "use strict";
  57887. var BABYLON;
  57888. (function (BABYLON) {
  57889. var AudioEngine = /** @class */ (function () {
  57890. function AudioEngine() {
  57891. this._audioContext = null;
  57892. this._audioContextInitialized = false;
  57893. this.canUseWebAudio = false;
  57894. this.WarnedWebAudioUnsupported = false;
  57895. this.unlocked = false;
  57896. this.isMP3supported = false;
  57897. this.isOGGsupported = false;
  57898. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57899. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57900. this.canUseWebAudio = true;
  57901. }
  57902. var audioElem = document.createElement('audio');
  57903. try {
  57904. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57905. this.isMP3supported = true;
  57906. }
  57907. }
  57908. catch (e) {
  57909. // protect error during capability check.
  57910. }
  57911. try {
  57912. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57913. this.isOGGsupported = true;
  57914. }
  57915. }
  57916. catch (e) {
  57917. // protect error during capability check.
  57918. }
  57919. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57920. this._unlockiOSaudio();
  57921. }
  57922. else {
  57923. this.unlocked = true;
  57924. }
  57925. }
  57926. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57927. get: function () {
  57928. if (!this._audioContextInitialized) {
  57929. this._initializeAudioContext();
  57930. }
  57931. return this._audioContext;
  57932. },
  57933. enumerable: true,
  57934. configurable: true
  57935. });
  57936. AudioEngine.prototype._unlockiOSaudio = function () {
  57937. var _this = this;
  57938. var unlockaudio = function () {
  57939. if (!_this.audioContext) {
  57940. return;
  57941. }
  57942. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57943. var source = _this.audioContext.createBufferSource();
  57944. source.buffer = buffer;
  57945. source.connect(_this.audioContext.destination);
  57946. source.start(0);
  57947. setTimeout(function () {
  57948. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57949. _this.unlocked = true;
  57950. window.removeEventListener('touchend', unlockaudio, false);
  57951. if (_this.onAudioUnlocked) {
  57952. _this.onAudioUnlocked();
  57953. }
  57954. }
  57955. }, 0);
  57956. };
  57957. window.addEventListener('touchend', unlockaudio, false);
  57958. };
  57959. AudioEngine.prototype._initializeAudioContext = function () {
  57960. try {
  57961. if (this.canUseWebAudio) {
  57962. this._audioContext = new AudioContext();
  57963. // create a global volume gain node
  57964. this.masterGain = this._audioContext.createGain();
  57965. this.masterGain.gain.value = 1;
  57966. this.masterGain.connect(this._audioContext.destination);
  57967. this._audioContextInitialized = true;
  57968. }
  57969. }
  57970. catch (e) {
  57971. this.canUseWebAudio = false;
  57972. BABYLON.Tools.Error("Web Audio: " + e.message);
  57973. }
  57974. };
  57975. AudioEngine.prototype.dispose = function () {
  57976. if (this.canUseWebAudio && this._audioContextInitialized) {
  57977. if (this._connectedAnalyser && this._audioContext) {
  57978. this._connectedAnalyser.stopDebugCanvas();
  57979. this._connectedAnalyser.dispose();
  57980. this.masterGain.disconnect();
  57981. this.masterGain.connect(this._audioContext.destination);
  57982. this._connectedAnalyser = null;
  57983. }
  57984. this.masterGain.gain.value = 1;
  57985. }
  57986. this.WarnedWebAudioUnsupported = false;
  57987. };
  57988. AudioEngine.prototype.getGlobalVolume = function () {
  57989. if (this.canUseWebAudio && this._audioContextInitialized) {
  57990. return this.masterGain.gain.value;
  57991. }
  57992. else {
  57993. return -1;
  57994. }
  57995. };
  57996. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57997. if (this.canUseWebAudio && this._audioContextInitialized) {
  57998. this.masterGain.gain.value = newVolume;
  57999. }
  58000. };
  58001. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  58002. if (this._connectedAnalyser) {
  58003. this._connectedAnalyser.stopDebugCanvas();
  58004. }
  58005. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  58006. this._connectedAnalyser = analyser;
  58007. this.masterGain.disconnect();
  58008. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  58009. }
  58010. };
  58011. return AudioEngine;
  58012. }());
  58013. BABYLON.AudioEngine = AudioEngine;
  58014. })(BABYLON || (BABYLON = {}));
  58015. //# sourceMappingURL=babylon.audioEngine.js.map
  58016. "use strict";
  58017. var BABYLON;
  58018. (function (BABYLON) {
  58019. var Sound = /** @class */ (function () {
  58020. /**
  58021. * Create a sound and attach it to a scene
  58022. * @param name Name of your sound
  58023. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  58024. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  58025. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  58026. */
  58027. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  58028. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  58029. var _this = this;
  58030. this.autoplay = false;
  58031. this.loop = false;
  58032. this.useCustomAttenuation = false;
  58033. this.spatialSound = false;
  58034. this.refDistance = 1;
  58035. this.rolloffFactor = 1;
  58036. this.maxDistance = 100;
  58037. this.distanceModel = "linear";
  58038. this._panningModel = "equalpower";
  58039. this._playbackRate = 1;
  58040. this._streaming = false;
  58041. this._startTime = 0;
  58042. this._startOffset = 0;
  58043. this._position = BABYLON.Vector3.Zero();
  58044. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  58045. this._volume = 1;
  58046. this._isReadyToPlay = false;
  58047. this.isPlaying = false;
  58048. this.isPaused = false;
  58049. this._isDirectional = false;
  58050. // Used if you'd like to create a directional sound.
  58051. // If not set, the sound will be omnidirectional
  58052. this._coneInnerAngle = 360;
  58053. this._coneOuterAngle = 360;
  58054. this._coneOuterGain = 0;
  58055. this._isOutputConnected = false;
  58056. this._urlType = "Unknown";
  58057. this.name = name;
  58058. this._scene = scene;
  58059. this._readyToPlayCallback = readyToPlayCallback;
  58060. // Default custom attenuation function is a linear attenuation
  58061. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  58062. if (currentDistance < maxDistance) {
  58063. return currentVolume * (1 - currentDistance / maxDistance);
  58064. }
  58065. else {
  58066. return 0;
  58067. }
  58068. };
  58069. if (options) {
  58070. this.autoplay = options.autoplay || false;
  58071. this.loop = options.loop || false;
  58072. // if volume === 0, we need another way to check this option
  58073. if (options.volume !== undefined) {
  58074. this._volume = options.volume;
  58075. }
  58076. this.spatialSound = options.spatialSound || false;
  58077. this.maxDistance = options.maxDistance || 100;
  58078. this.useCustomAttenuation = options.useCustomAttenuation || false;
  58079. this.rolloffFactor = options.rolloffFactor || 1;
  58080. this.refDistance = options.refDistance || 1;
  58081. this.distanceModel = options.distanceModel || "linear";
  58082. this._playbackRate = options.playbackRate || 1;
  58083. this._streaming = options.streaming || false;
  58084. }
  58085. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58086. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58087. this._soundGain.gain.value = this._volume;
  58088. this._inputAudioNode = this._soundGain;
  58089. this._ouputAudioNode = this._soundGain;
  58090. if (this.spatialSound) {
  58091. this._createSpatialParameters();
  58092. }
  58093. this._scene.mainSoundTrack.AddSound(this);
  58094. var validParameter = true;
  58095. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58096. if (urlOrArrayBuffer) {
  58097. try {
  58098. if (typeof (urlOrArrayBuffer) === "string")
  58099. this._urlType = "String";
  58100. if (Array.isArray(urlOrArrayBuffer))
  58101. this._urlType = "Array";
  58102. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58103. this._urlType = "ArrayBuffer";
  58104. var urls = [];
  58105. var codecSupportedFound = false;
  58106. switch (this._urlType) {
  58107. case "ArrayBuffer":
  58108. if (urlOrArrayBuffer.byteLength > 0) {
  58109. codecSupportedFound = true;
  58110. this._soundLoaded(urlOrArrayBuffer);
  58111. }
  58112. break;
  58113. case "String":
  58114. urls.push(urlOrArrayBuffer);
  58115. case "Array":
  58116. if (urls.length === 0)
  58117. urls = urlOrArrayBuffer;
  58118. // If we found a supported format, we load it immediately and stop the loop
  58119. for (var i = 0; i < urls.length; i++) {
  58120. var url = urls[i];
  58121. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58122. codecSupportedFound = true;
  58123. }
  58124. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58125. codecSupportedFound = true;
  58126. }
  58127. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58128. codecSupportedFound = true;
  58129. }
  58130. if (url.indexOf("blob:") !== -1) {
  58131. codecSupportedFound = true;
  58132. }
  58133. if (codecSupportedFound) {
  58134. // Loading sound using XHR2
  58135. if (!this._streaming) {
  58136. this._scene._loadFile(url, function (data) {
  58137. _this._soundLoaded(data);
  58138. }, undefined, true, true, function (exception) {
  58139. if (exception) {
  58140. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58141. }
  58142. BABYLON.Tools.Error("Sound creation aborted.");
  58143. _this._scene.mainSoundTrack.RemoveSound(_this);
  58144. });
  58145. }
  58146. else {
  58147. this._htmlAudioElement = new Audio(url);
  58148. this._htmlAudioElement.controls = false;
  58149. this._htmlAudioElement.loop = this.loop;
  58150. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58151. this._htmlAudioElement.preload = "auto";
  58152. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58153. _this._isReadyToPlay = true;
  58154. if (_this.autoplay) {
  58155. _this.play();
  58156. }
  58157. if (_this._readyToPlayCallback) {
  58158. _this._readyToPlayCallback();
  58159. }
  58160. });
  58161. document.body.appendChild(this._htmlAudioElement);
  58162. }
  58163. break;
  58164. }
  58165. }
  58166. break;
  58167. default:
  58168. validParameter = false;
  58169. break;
  58170. }
  58171. if (!validParameter) {
  58172. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58173. }
  58174. else {
  58175. if (!codecSupportedFound) {
  58176. this._isReadyToPlay = true;
  58177. // Simulating a ready to play event to avoid breaking code path
  58178. if (this._readyToPlayCallback) {
  58179. window.setTimeout(function () {
  58180. if (_this._readyToPlayCallback) {
  58181. _this._readyToPlayCallback();
  58182. }
  58183. }, 1000);
  58184. }
  58185. }
  58186. }
  58187. }
  58188. catch (ex) {
  58189. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58190. this._scene.mainSoundTrack.RemoveSound(this);
  58191. }
  58192. }
  58193. }
  58194. else {
  58195. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58196. this._scene.mainSoundTrack.AddSound(this);
  58197. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58198. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58199. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58200. }
  58201. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58202. if (this._readyToPlayCallback) {
  58203. window.setTimeout(function () {
  58204. if (_this._readyToPlayCallback) {
  58205. _this._readyToPlayCallback();
  58206. }
  58207. }, 1000);
  58208. }
  58209. }
  58210. }
  58211. Sound.prototype.dispose = function () {
  58212. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58213. if (this.isPlaying) {
  58214. this.stop();
  58215. }
  58216. this._isReadyToPlay = false;
  58217. if (this.soundTrackId === -1) {
  58218. this._scene.mainSoundTrack.RemoveSound(this);
  58219. }
  58220. else {
  58221. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58222. }
  58223. if (this._soundGain) {
  58224. this._soundGain.disconnect();
  58225. this._soundGain = null;
  58226. }
  58227. if (this._soundPanner) {
  58228. this._soundPanner.disconnect();
  58229. this._soundPanner = null;
  58230. }
  58231. if (this._soundSource) {
  58232. this._soundSource.disconnect();
  58233. this._soundSource = null;
  58234. }
  58235. this._audioBuffer = null;
  58236. if (this._htmlAudioElement) {
  58237. this._htmlAudioElement.pause();
  58238. this._htmlAudioElement.src = "";
  58239. document.body.removeChild(this._htmlAudioElement);
  58240. }
  58241. if (this._connectedMesh && this._registerFunc) {
  58242. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58243. this._connectedMesh = null;
  58244. }
  58245. }
  58246. };
  58247. Sound.prototype.isReady = function () {
  58248. return this._isReadyToPlay;
  58249. };
  58250. Sound.prototype._soundLoaded = function (audioData) {
  58251. var _this = this;
  58252. if (!BABYLON.Engine.audioEngine.audioContext) {
  58253. return;
  58254. }
  58255. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58256. _this._audioBuffer = buffer;
  58257. _this._isReadyToPlay = true;
  58258. if (_this.autoplay) {
  58259. _this.play();
  58260. }
  58261. if (_this._readyToPlayCallback) {
  58262. _this._readyToPlayCallback();
  58263. }
  58264. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58265. };
  58266. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58267. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58268. this._audioBuffer = audioBuffer;
  58269. this._isReadyToPlay = true;
  58270. }
  58271. };
  58272. Sound.prototype.updateOptions = function (options) {
  58273. if (options) {
  58274. this.loop = options.loop || this.loop;
  58275. this.maxDistance = options.maxDistance || this.maxDistance;
  58276. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58277. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58278. this.refDistance = options.refDistance || this.refDistance;
  58279. this.distanceModel = options.distanceModel || this.distanceModel;
  58280. this._playbackRate = options.playbackRate || this._playbackRate;
  58281. this._updateSpatialParameters();
  58282. if (this.isPlaying) {
  58283. if (this._streaming) {
  58284. this._htmlAudioElement.playbackRate = this._playbackRate;
  58285. }
  58286. else {
  58287. if (this._soundSource) {
  58288. this._soundSource.playbackRate.value = this._playbackRate;
  58289. }
  58290. }
  58291. }
  58292. }
  58293. };
  58294. Sound.prototype._createSpatialParameters = function () {
  58295. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58296. if (this._scene.headphone) {
  58297. this._panningModel = "HRTF";
  58298. }
  58299. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58300. this._updateSpatialParameters();
  58301. this._soundPanner.connect(this._ouputAudioNode);
  58302. this._inputAudioNode = this._soundPanner;
  58303. }
  58304. };
  58305. Sound.prototype._updateSpatialParameters = function () {
  58306. if (this.spatialSound && this._soundPanner) {
  58307. if (this.useCustomAttenuation) {
  58308. // Tricks to disable in a way embedded Web Audio attenuation
  58309. this._soundPanner.distanceModel = "linear";
  58310. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58311. this._soundPanner.refDistance = 1;
  58312. this._soundPanner.rolloffFactor = 1;
  58313. this._soundPanner.panningModel = this._panningModel;
  58314. }
  58315. else {
  58316. this._soundPanner.distanceModel = this.distanceModel;
  58317. this._soundPanner.maxDistance = this.maxDistance;
  58318. this._soundPanner.refDistance = this.refDistance;
  58319. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58320. this._soundPanner.panningModel = this._panningModel;
  58321. }
  58322. }
  58323. };
  58324. Sound.prototype.switchPanningModelToHRTF = function () {
  58325. this._panningModel = "HRTF";
  58326. this._switchPanningModel();
  58327. };
  58328. Sound.prototype.switchPanningModelToEqualPower = function () {
  58329. this._panningModel = "equalpower";
  58330. this._switchPanningModel();
  58331. };
  58332. Sound.prototype._switchPanningModel = function () {
  58333. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58334. this._soundPanner.panningModel = this._panningModel;
  58335. }
  58336. };
  58337. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58338. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58339. if (this._isOutputConnected) {
  58340. this._ouputAudioNode.disconnect();
  58341. }
  58342. this._ouputAudioNode.connect(soundTrackAudioNode);
  58343. this._isOutputConnected = true;
  58344. }
  58345. };
  58346. /**
  58347. * Transform this sound into a directional source
  58348. * @param coneInnerAngle Size of the inner cone in degree
  58349. * @param coneOuterAngle Size of the outer cone in degree
  58350. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58351. */
  58352. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58353. if (coneOuterAngle < coneInnerAngle) {
  58354. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58355. return;
  58356. }
  58357. this._coneInnerAngle = coneInnerAngle;
  58358. this._coneOuterAngle = coneOuterAngle;
  58359. this._coneOuterGain = coneOuterGain;
  58360. this._isDirectional = true;
  58361. if (this.isPlaying && this.loop) {
  58362. this.stop();
  58363. this.play();
  58364. }
  58365. };
  58366. Sound.prototype.setPosition = function (newPosition) {
  58367. this._position = newPosition;
  58368. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58369. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58370. }
  58371. };
  58372. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58373. this._localDirection = newLocalDirection;
  58374. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58375. this._updateDirection();
  58376. }
  58377. };
  58378. Sound.prototype._updateDirection = function () {
  58379. if (!this._connectedMesh || !this._soundPanner) {
  58380. return;
  58381. }
  58382. var mat = this._connectedMesh.getWorldMatrix();
  58383. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58384. direction.normalize();
  58385. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58386. };
  58387. Sound.prototype.updateDistanceFromListener = function () {
  58388. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58389. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58390. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58391. }
  58392. };
  58393. Sound.prototype.setAttenuationFunction = function (callback) {
  58394. this._customAttenuationFunction = callback;
  58395. };
  58396. /**
  58397. * Play the sound
  58398. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58399. * @param offset (optional) Start the sound setting it at a specific time
  58400. */
  58401. Sound.prototype.play = function (time, offset) {
  58402. var _this = this;
  58403. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58404. try {
  58405. if (this._startOffset < 0) {
  58406. time = -this._startOffset;
  58407. this._startOffset = 0;
  58408. }
  58409. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58410. if (!this._soundSource || !this._streamingSource) {
  58411. if (this.spatialSound && this._soundPanner) {
  58412. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58413. if (this._isDirectional) {
  58414. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58415. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58416. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58417. if (this._connectedMesh) {
  58418. this._updateDirection();
  58419. }
  58420. else {
  58421. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58422. }
  58423. }
  58424. }
  58425. }
  58426. if (this._streaming) {
  58427. if (!this._streamingSource) {
  58428. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58429. this._htmlAudioElement.onended = function () { _this._onended(); };
  58430. this._htmlAudioElement.playbackRate = this._playbackRate;
  58431. }
  58432. this._streamingSource.disconnect();
  58433. this._streamingSource.connect(this._inputAudioNode);
  58434. this._htmlAudioElement.play();
  58435. }
  58436. else {
  58437. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58438. this._soundSource.buffer = this._audioBuffer;
  58439. this._soundSource.connect(this._inputAudioNode);
  58440. this._soundSource.loop = this.loop;
  58441. this._soundSource.playbackRate.value = this._playbackRate;
  58442. this._soundSource.onended = function () { _this._onended(); };
  58443. if (this._soundSource.buffer) {
  58444. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58445. }
  58446. }
  58447. this._startTime = startTime;
  58448. this.isPlaying = true;
  58449. this.isPaused = false;
  58450. }
  58451. catch (ex) {
  58452. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58453. }
  58454. }
  58455. };
  58456. Sound.prototype._onended = function () {
  58457. this.isPlaying = false;
  58458. if (this.onended) {
  58459. this.onended();
  58460. }
  58461. };
  58462. /**
  58463. * Stop the sound
  58464. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58465. */
  58466. Sound.prototype.stop = function (time) {
  58467. if (this.isPlaying) {
  58468. if (this._streaming) {
  58469. this._htmlAudioElement.pause();
  58470. // Test needed for Firefox or it will generate an Invalid State Error
  58471. if (this._htmlAudioElement.currentTime > 0) {
  58472. this._htmlAudioElement.currentTime = 0;
  58473. }
  58474. }
  58475. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58476. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58477. this._soundSource.stop(stopTime);
  58478. this._soundSource.onended = function () { };
  58479. if (!this.isPaused) {
  58480. this._startOffset = 0;
  58481. }
  58482. }
  58483. this.isPlaying = false;
  58484. }
  58485. };
  58486. Sound.prototype.pause = function () {
  58487. if (this.isPlaying) {
  58488. this.isPaused = true;
  58489. if (this._streaming) {
  58490. this._htmlAudioElement.pause();
  58491. }
  58492. else if (BABYLON.Engine.audioEngine.audioContext) {
  58493. this.stop(0);
  58494. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58495. }
  58496. }
  58497. };
  58498. Sound.prototype.setVolume = function (newVolume, time) {
  58499. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58500. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58501. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58502. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58503. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58504. }
  58505. else {
  58506. this._soundGain.gain.value = newVolume;
  58507. }
  58508. }
  58509. this._volume = newVolume;
  58510. };
  58511. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58512. this._playbackRate = newPlaybackRate;
  58513. if (this.isPlaying) {
  58514. if (this._streaming) {
  58515. this._htmlAudioElement.playbackRate = this._playbackRate;
  58516. }
  58517. else if (this._soundSource) {
  58518. this._soundSource.playbackRate.value = this._playbackRate;
  58519. }
  58520. }
  58521. };
  58522. Sound.prototype.getVolume = function () {
  58523. return this._volume;
  58524. };
  58525. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58526. var _this = this;
  58527. if (this._connectedMesh && this._registerFunc) {
  58528. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58529. this._registerFunc = null;
  58530. }
  58531. this._connectedMesh = meshToConnectTo;
  58532. if (!this.spatialSound) {
  58533. this.spatialSound = true;
  58534. this._createSpatialParameters();
  58535. if (this.isPlaying && this.loop) {
  58536. this.stop();
  58537. this.play();
  58538. }
  58539. }
  58540. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58541. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58542. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58543. };
  58544. Sound.prototype.detachFromMesh = function () {
  58545. if (this._connectedMesh && this._registerFunc) {
  58546. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58547. this._registerFunc = null;
  58548. this._connectedMesh = null;
  58549. }
  58550. };
  58551. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58552. if (!node.getBoundingInfo) {
  58553. return;
  58554. }
  58555. var mesh = node;
  58556. var boundingInfo = mesh.getBoundingInfo();
  58557. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58558. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58559. this._updateDirection();
  58560. }
  58561. };
  58562. Sound.prototype.clone = function () {
  58563. var _this = this;
  58564. if (!this._streaming) {
  58565. var setBufferAndRun = function () {
  58566. if (_this._isReadyToPlay) {
  58567. clonedSound._audioBuffer = _this.getAudioBuffer();
  58568. clonedSound._isReadyToPlay = true;
  58569. if (clonedSound.autoplay) {
  58570. clonedSound.play();
  58571. }
  58572. }
  58573. else {
  58574. window.setTimeout(setBufferAndRun, 300);
  58575. }
  58576. };
  58577. var currentOptions = {
  58578. autoplay: this.autoplay, loop: this.loop,
  58579. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58580. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58581. refDistance: this.refDistance, distanceModel: this.distanceModel
  58582. };
  58583. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58584. if (this.useCustomAttenuation) {
  58585. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58586. }
  58587. clonedSound.setPosition(this._position);
  58588. clonedSound.setPlaybackRate(this._playbackRate);
  58589. setBufferAndRun();
  58590. return clonedSound;
  58591. }
  58592. else {
  58593. return null;
  58594. }
  58595. };
  58596. Sound.prototype.getAudioBuffer = function () {
  58597. return this._audioBuffer;
  58598. };
  58599. Sound.prototype.serialize = function () {
  58600. var serializationObject = {
  58601. name: this.name,
  58602. url: this.name,
  58603. autoplay: this.autoplay,
  58604. loop: this.loop,
  58605. volume: this._volume,
  58606. spatialSound: this.spatialSound,
  58607. maxDistance: this.maxDistance,
  58608. rolloffFactor: this.rolloffFactor,
  58609. refDistance: this.refDistance,
  58610. distanceModel: this.distanceModel,
  58611. playbackRate: this._playbackRate,
  58612. panningModel: this._panningModel,
  58613. soundTrackId: this.soundTrackId
  58614. };
  58615. if (this.spatialSound) {
  58616. if (this._connectedMesh)
  58617. serializationObject.connectedMeshId = this._connectedMesh.id;
  58618. serializationObject.position = this._position.asArray();
  58619. serializationObject.refDistance = this.refDistance;
  58620. serializationObject.distanceModel = this.distanceModel;
  58621. serializationObject.isDirectional = this._isDirectional;
  58622. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58623. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58624. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58625. serializationObject.coneOuterGain = this._coneOuterGain;
  58626. }
  58627. return serializationObject;
  58628. };
  58629. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58630. var soundName = parsedSound.name;
  58631. var soundUrl;
  58632. if (parsedSound.url) {
  58633. soundUrl = rootUrl + parsedSound.url;
  58634. }
  58635. else {
  58636. soundUrl = rootUrl + soundName;
  58637. }
  58638. var options = {
  58639. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58640. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58641. rolloffFactor: parsedSound.rolloffFactor,
  58642. refDistance: parsedSound.refDistance,
  58643. distanceModel: parsedSound.distanceModel,
  58644. playbackRate: parsedSound.playbackRate
  58645. };
  58646. var newSound;
  58647. if (!sourceSound) {
  58648. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58649. scene._addPendingData(newSound);
  58650. }
  58651. else {
  58652. var setBufferAndRun = function () {
  58653. if (sourceSound._isReadyToPlay) {
  58654. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58655. newSound._isReadyToPlay = true;
  58656. if (newSound.autoplay) {
  58657. newSound.play();
  58658. }
  58659. }
  58660. else {
  58661. window.setTimeout(setBufferAndRun, 300);
  58662. }
  58663. };
  58664. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58665. setBufferAndRun();
  58666. }
  58667. if (parsedSound.position) {
  58668. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58669. newSound.setPosition(soundPosition);
  58670. }
  58671. if (parsedSound.isDirectional) {
  58672. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58673. if (parsedSound.localDirectionToMesh) {
  58674. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58675. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58676. }
  58677. }
  58678. if (parsedSound.connectedMeshId) {
  58679. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58680. if (connectedMesh) {
  58681. newSound.attachToMesh(connectedMesh);
  58682. }
  58683. }
  58684. return newSound;
  58685. };
  58686. return Sound;
  58687. }());
  58688. BABYLON.Sound = Sound;
  58689. })(BABYLON || (BABYLON = {}));
  58690. //# sourceMappingURL=babylon.sound.js.map
  58691. "use strict";
  58692. var BABYLON;
  58693. (function (BABYLON) {
  58694. var SoundTrack = /** @class */ (function () {
  58695. function SoundTrack(scene, options) {
  58696. this.id = -1;
  58697. this._isMainTrack = false;
  58698. this._isInitialized = false;
  58699. this._scene = scene;
  58700. this.soundCollection = new Array();
  58701. this._options = options;
  58702. if (!this._isMainTrack) {
  58703. this._scene.soundTracks.push(this);
  58704. this.id = this._scene.soundTracks.length - 1;
  58705. }
  58706. }
  58707. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58708. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58709. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58710. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58711. if (this._options) {
  58712. if (this._options.volume) {
  58713. this._outputAudioNode.gain.value = this._options.volume;
  58714. }
  58715. if (this._options.mainTrack) {
  58716. this._isMainTrack = this._options.mainTrack;
  58717. }
  58718. }
  58719. this._isInitialized = true;
  58720. }
  58721. };
  58722. SoundTrack.prototype.dispose = function () {
  58723. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58724. if (this._connectedAnalyser) {
  58725. this._connectedAnalyser.stopDebugCanvas();
  58726. }
  58727. while (this.soundCollection.length) {
  58728. this.soundCollection[0].dispose();
  58729. }
  58730. if (this._outputAudioNode) {
  58731. this._outputAudioNode.disconnect();
  58732. }
  58733. this._outputAudioNode = null;
  58734. }
  58735. };
  58736. SoundTrack.prototype.AddSound = function (sound) {
  58737. if (!this._isInitialized) {
  58738. this._initializeSoundTrackAudioGraph();
  58739. }
  58740. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58741. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58742. }
  58743. if (sound.soundTrackId) {
  58744. if (sound.soundTrackId === -1) {
  58745. this._scene.mainSoundTrack.RemoveSound(sound);
  58746. }
  58747. else {
  58748. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58749. }
  58750. }
  58751. this.soundCollection.push(sound);
  58752. sound.soundTrackId = this.id;
  58753. };
  58754. SoundTrack.prototype.RemoveSound = function (sound) {
  58755. var index = this.soundCollection.indexOf(sound);
  58756. if (index !== -1) {
  58757. this.soundCollection.splice(index, 1);
  58758. }
  58759. };
  58760. SoundTrack.prototype.setVolume = function (newVolume) {
  58761. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58762. this._outputAudioNode.gain.value = newVolume;
  58763. }
  58764. };
  58765. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58766. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58767. for (var i = 0; i < this.soundCollection.length; i++) {
  58768. this.soundCollection[i].switchPanningModelToHRTF();
  58769. }
  58770. }
  58771. };
  58772. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58773. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58774. for (var i = 0; i < this.soundCollection.length; i++) {
  58775. this.soundCollection[i].switchPanningModelToEqualPower();
  58776. }
  58777. }
  58778. };
  58779. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58780. if (this._connectedAnalyser) {
  58781. this._connectedAnalyser.stopDebugCanvas();
  58782. }
  58783. this._connectedAnalyser = analyser;
  58784. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58785. this._outputAudioNode.disconnect();
  58786. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58787. }
  58788. };
  58789. return SoundTrack;
  58790. }());
  58791. BABYLON.SoundTrack = SoundTrack;
  58792. })(BABYLON || (BABYLON = {}));
  58793. //# sourceMappingURL=babylon.soundtrack.js.map
  58794. "use strict";
  58795. var BABYLON;
  58796. (function (BABYLON) {
  58797. var Analyser = /** @class */ (function () {
  58798. function Analyser(scene) {
  58799. this.SMOOTHING = 0.75;
  58800. this.FFT_SIZE = 512;
  58801. this.BARGRAPHAMPLITUDE = 256;
  58802. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58803. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58804. this._scene = scene;
  58805. this._audioEngine = BABYLON.Engine.audioEngine;
  58806. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58807. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58808. this._webAudioAnalyser.minDecibels = -140;
  58809. this._webAudioAnalyser.maxDecibels = 0;
  58810. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58811. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58812. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58813. }
  58814. }
  58815. Analyser.prototype.getFrequencyBinCount = function () {
  58816. if (this._audioEngine.canUseWebAudio) {
  58817. return this._webAudioAnalyser.frequencyBinCount;
  58818. }
  58819. else {
  58820. return 0;
  58821. }
  58822. };
  58823. Analyser.prototype.getByteFrequencyData = function () {
  58824. if (this._audioEngine.canUseWebAudio) {
  58825. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58826. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58827. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58828. }
  58829. return this._byteFreqs;
  58830. };
  58831. Analyser.prototype.getByteTimeDomainData = function () {
  58832. if (this._audioEngine.canUseWebAudio) {
  58833. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58834. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58835. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58836. }
  58837. return this._byteTime;
  58838. };
  58839. Analyser.prototype.getFloatFrequencyData = function () {
  58840. if (this._audioEngine.canUseWebAudio) {
  58841. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58842. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58843. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58844. }
  58845. return this._floatFreqs;
  58846. };
  58847. Analyser.prototype.drawDebugCanvas = function () {
  58848. var _this = this;
  58849. if (this._audioEngine.canUseWebAudio) {
  58850. if (!this._debugCanvas) {
  58851. this._debugCanvas = document.createElement("canvas");
  58852. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58853. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58854. this._debugCanvas.style.position = "absolute";
  58855. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58856. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58857. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58858. document.body.appendChild(this._debugCanvas);
  58859. this._registerFunc = function () {
  58860. _this.drawDebugCanvas();
  58861. };
  58862. this._scene.registerBeforeRender(this._registerFunc);
  58863. }
  58864. if (this._registerFunc && this._debugCanvasContext) {
  58865. var workingArray = this.getByteFrequencyData();
  58866. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58867. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58868. // Draw the frequency domain chart.
  58869. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58870. var value = workingArray[i];
  58871. var percent = value / this.BARGRAPHAMPLITUDE;
  58872. var height = this.DEBUGCANVASSIZE.height * percent;
  58873. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58874. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58875. var hue = i / this.getFrequencyBinCount() * 360;
  58876. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58877. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58878. }
  58879. }
  58880. }
  58881. };
  58882. Analyser.prototype.stopDebugCanvas = function () {
  58883. if (this._debugCanvas) {
  58884. if (this._registerFunc) {
  58885. this._scene.unregisterBeforeRender(this._registerFunc);
  58886. this._registerFunc = null;
  58887. }
  58888. document.body.removeChild(this._debugCanvas);
  58889. this._debugCanvas = null;
  58890. this._debugCanvasContext = null;
  58891. }
  58892. };
  58893. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58894. if (this._audioEngine.canUseWebAudio) {
  58895. inputAudioNode.connect(this._webAudioAnalyser);
  58896. this._webAudioAnalyser.connect(outputAudioNode);
  58897. }
  58898. };
  58899. Analyser.prototype.dispose = function () {
  58900. if (this._audioEngine.canUseWebAudio) {
  58901. this._webAudioAnalyser.disconnect();
  58902. }
  58903. };
  58904. return Analyser;
  58905. }());
  58906. BABYLON.Analyser = Analyser;
  58907. })(BABYLON || (BABYLON = {}));
  58908. //# sourceMappingURL=babylon.analyser.js.map
  58909. "use strict";
  58910. var BABYLON;
  58911. (function (BABYLON) {
  58912. var CubeTexture = /** @class */ (function (_super) {
  58913. __extends(CubeTexture, _super);
  58914. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58915. if (extensions === void 0) { extensions = null; }
  58916. if (noMipmap === void 0) { noMipmap = false; }
  58917. if (files === void 0) { files = null; }
  58918. if (onLoad === void 0) { onLoad = null; }
  58919. if (onError === void 0) { onError = null; }
  58920. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58921. if (prefiltered === void 0) { prefiltered = false; }
  58922. if (forcedExtension === void 0) { forcedExtension = null; }
  58923. var _this = _super.call(this, scene) || this;
  58924. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58925. /**
  58926. * Gets or sets the center of the bounding box associated with the cube texture
  58927. * It must define where the camera used to render the texture was set
  58928. */
  58929. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58930. _this.name = rootUrl;
  58931. _this.url = rootUrl;
  58932. _this._noMipmap = noMipmap;
  58933. _this.hasAlpha = false;
  58934. _this._format = format;
  58935. _this._prefiltered = prefiltered;
  58936. _this.isCube = true;
  58937. _this._textureMatrix = BABYLON.Matrix.Identity();
  58938. if (prefiltered) {
  58939. _this.gammaSpace = false;
  58940. }
  58941. if (!rootUrl && !files) {
  58942. return _this;
  58943. }
  58944. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58945. var lastDot = rootUrl.lastIndexOf(".");
  58946. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58947. var isDDS = (extension === ".dds");
  58948. if (!files) {
  58949. if (!isDDS && !extensions) {
  58950. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58951. }
  58952. files = [];
  58953. if (extensions) {
  58954. for (var index = 0; index < extensions.length; index++) {
  58955. files.push(rootUrl + extensions[index]);
  58956. }
  58957. }
  58958. }
  58959. _this._files = files;
  58960. if (!_this._texture) {
  58961. if (!scene.useDelayedTextureLoading) {
  58962. if (prefiltered) {
  58963. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58964. }
  58965. else {
  58966. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58967. }
  58968. }
  58969. else {
  58970. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58971. }
  58972. }
  58973. else if (onLoad) {
  58974. if (_this._texture.isReady) {
  58975. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58976. }
  58977. else {
  58978. _this._texture.onLoadedObservable.add(onLoad);
  58979. }
  58980. }
  58981. return _this;
  58982. }
  58983. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58984. get: function () {
  58985. return this._boundingBoxSize;
  58986. },
  58987. /**
  58988. * Gets or sets the size of the bounding box associated with the cube texture
  58989. * When defined, the cubemap will switch to local mode
  58990. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58991. * @example https://www.babylonjs-playground.com/#RNASML
  58992. */
  58993. set: function (value) {
  58994. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58995. return;
  58996. }
  58997. this._boundingBoxSize = value;
  58998. var scene = this.getScene();
  58999. if (scene) {
  59000. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59001. }
  59002. },
  59003. enumerable: true,
  59004. configurable: true
  59005. });
  59006. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  59007. var rootUrlKey = "";
  59008. files.forEach(function (url) { return rootUrlKey += url; });
  59009. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  59010. };
  59011. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  59012. if (forcedExtension === void 0) { forcedExtension = null; }
  59013. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  59014. };
  59015. // Methods
  59016. CubeTexture.prototype.delayLoad = function () {
  59017. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59018. return;
  59019. }
  59020. var scene = this.getScene();
  59021. if (!scene) {
  59022. return;
  59023. }
  59024. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59025. this._texture = this._getFromCache(this.url, this._noMipmap);
  59026. if (!this._texture) {
  59027. if (this._prefiltered) {
  59028. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  59029. }
  59030. else {
  59031. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  59032. }
  59033. }
  59034. };
  59035. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  59036. return this._textureMatrix;
  59037. };
  59038. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59039. this._textureMatrix = value;
  59040. };
  59041. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59042. var texture = BABYLON.SerializationHelper.Parse(function () {
  59043. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  59044. }, parsedTexture, scene);
  59045. // Local Cubemaps
  59046. if (parsedTexture.boundingBoxPosition) {
  59047. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  59048. }
  59049. if (parsedTexture.boundingBoxSize) {
  59050. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  59051. }
  59052. // Animations
  59053. if (parsedTexture.animations) {
  59054. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  59055. var parsedAnimation = parsedTexture.animations[animationIndex];
  59056. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59057. }
  59058. }
  59059. return texture;
  59060. };
  59061. CubeTexture.prototype.clone = function () {
  59062. var _this = this;
  59063. return BABYLON.SerializationHelper.Clone(function () {
  59064. var scene = _this.getScene();
  59065. if (!scene) {
  59066. return _this;
  59067. }
  59068. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  59069. }, this);
  59070. };
  59071. return CubeTexture;
  59072. }(BABYLON.BaseTexture));
  59073. BABYLON.CubeTexture = CubeTexture;
  59074. })(BABYLON || (BABYLON = {}));
  59075. //# sourceMappingURL=babylon.cubeTexture.js.map
  59076. "use strict";
  59077. var BABYLON;
  59078. (function (BABYLON) {
  59079. var RenderTargetTexture = /** @class */ (function (_super) {
  59080. __extends(RenderTargetTexture, _super);
  59081. /**
  59082. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  59083. * or used a shadow, depth texture...
  59084. * @param name The friendly name of the texture
  59085. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  59086. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59087. * @param generateMipMaps True if mip maps need to be generated after render.
  59088. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59089. * @param type The type of the buffer in the RTT (int, half float, float...)
  59090. * @param isCube True if a cube texture needs to be created
  59091. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59092. * @param generateDepthBuffer True to generate a depth buffer
  59093. * @param generateStencilBuffer True to generate a stencil buffer
  59094. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59095. */
  59096. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59097. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59098. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59099. if (isCube === void 0) { isCube = false; }
  59100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59101. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59102. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59103. if (isMulti === void 0) { isMulti = false; }
  59104. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59105. _this.isCube = isCube;
  59106. /**
  59107. * Use this list to define the list of mesh you want to render.
  59108. */
  59109. _this.renderList = new Array();
  59110. _this.renderParticles = true;
  59111. _this.renderSprites = false;
  59112. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59113. _this.ignoreCameraViewport = false;
  59114. // Events
  59115. /**
  59116. * An event triggered when the texture is unbind.
  59117. */
  59118. _this.onBeforeBindObservable = new BABYLON.Observable();
  59119. /**
  59120. * An event triggered when the texture is unbind.
  59121. */
  59122. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59123. /**
  59124. * An event triggered before rendering the texture
  59125. */
  59126. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59127. /**
  59128. * An event triggered after rendering the texture
  59129. */
  59130. _this.onAfterRenderObservable = new BABYLON.Observable();
  59131. /**
  59132. * An event triggered after the texture clear
  59133. */
  59134. _this.onClearObservable = new BABYLON.Observable();
  59135. _this._currentRefreshId = -1;
  59136. _this._refreshRate = 1;
  59137. _this._samples = 1;
  59138. /**
  59139. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59140. * It must define where the camera used to render the texture is set
  59141. */
  59142. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59143. scene = _this.getScene();
  59144. if (!scene) {
  59145. return _this;
  59146. }
  59147. _this._engine = scene.getEngine();
  59148. _this.name = name;
  59149. _this.isRenderTarget = true;
  59150. _this._initialSizeParameter = size;
  59151. _this._processSizeParameter(size);
  59152. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59153. });
  59154. _this._generateMipMaps = generateMipMaps ? true : false;
  59155. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59156. // Rendering groups
  59157. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59158. if (isMulti) {
  59159. return _this;
  59160. }
  59161. _this._renderTargetOptions = {
  59162. generateMipMaps: generateMipMaps,
  59163. type: type,
  59164. samplingMode: samplingMode,
  59165. generateDepthBuffer: generateDepthBuffer,
  59166. generateStencilBuffer: generateStencilBuffer
  59167. };
  59168. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59169. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59170. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59171. }
  59172. if (isCube) {
  59173. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59174. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59175. _this._textureMatrix = BABYLON.Matrix.Identity();
  59176. }
  59177. else {
  59178. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59179. }
  59180. return _this;
  59181. }
  59182. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59183. get: function () {
  59184. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59185. },
  59186. enumerable: true,
  59187. configurable: true
  59188. });
  59189. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59190. get: function () {
  59191. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59192. },
  59193. enumerable: true,
  59194. configurable: true
  59195. });
  59196. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59197. get: function () {
  59198. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59199. },
  59200. enumerable: true,
  59201. configurable: true
  59202. });
  59203. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59204. set: function (callback) {
  59205. if (this._onAfterUnbindObserver) {
  59206. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59207. }
  59208. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59209. },
  59210. enumerable: true,
  59211. configurable: true
  59212. });
  59213. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59214. set: function (callback) {
  59215. if (this._onBeforeRenderObserver) {
  59216. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59217. }
  59218. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59219. },
  59220. enumerable: true,
  59221. configurable: true
  59222. });
  59223. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59224. set: function (callback) {
  59225. if (this._onAfterRenderObserver) {
  59226. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59227. }
  59228. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59229. },
  59230. enumerable: true,
  59231. configurable: true
  59232. });
  59233. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59234. set: function (callback) {
  59235. if (this._onClearObserver) {
  59236. this.onClearObservable.remove(this._onClearObserver);
  59237. }
  59238. this._onClearObserver = this.onClearObservable.add(callback);
  59239. },
  59240. enumerable: true,
  59241. configurable: true
  59242. });
  59243. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59244. get: function () {
  59245. return this._renderTargetOptions;
  59246. },
  59247. enumerable: true,
  59248. configurable: true
  59249. });
  59250. RenderTargetTexture.prototype._onRatioRescale = function () {
  59251. if (this._sizeRatio) {
  59252. this.resize(this._initialSizeParameter);
  59253. }
  59254. };
  59255. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59256. get: function () {
  59257. return this._boundingBoxSize;
  59258. },
  59259. /**
  59260. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59261. * When defined, the cubemap will switch to local mode
  59262. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59263. * @example https://www.babylonjs-playground.com/#RNASML
  59264. */
  59265. set: function (value) {
  59266. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59267. return;
  59268. }
  59269. this._boundingBoxSize = value;
  59270. var scene = this.getScene();
  59271. if (scene) {
  59272. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59273. }
  59274. },
  59275. enumerable: true,
  59276. configurable: true
  59277. });
  59278. /**
  59279. * Creates a depth stencil texture.
  59280. * This is only available in WebGL 2 or with the depth texture extension available.
  59281. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59282. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59283. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59284. */
  59285. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59286. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59287. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59288. if (generateStencil === void 0) { generateStencil = false; }
  59289. if (!this.getScene()) {
  59290. return;
  59291. }
  59292. var engine = this.getScene().getEngine();
  59293. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59294. bilinearFiltering: bilinearFiltering,
  59295. comparisonFunction: comparisonFunction,
  59296. generateStencil: generateStencil,
  59297. isCube: this.isCube
  59298. });
  59299. engine.setFrameBufferDepthStencilTexture(this);
  59300. };
  59301. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59302. if (size.ratio) {
  59303. this._sizeRatio = size.ratio;
  59304. this._size = {
  59305. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59306. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59307. };
  59308. }
  59309. else {
  59310. this._size = size;
  59311. }
  59312. };
  59313. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59314. get: function () {
  59315. return this._samples;
  59316. },
  59317. set: function (value) {
  59318. if (this._samples === value) {
  59319. return;
  59320. }
  59321. var scene = this.getScene();
  59322. if (!scene) {
  59323. return;
  59324. }
  59325. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59326. },
  59327. enumerable: true,
  59328. configurable: true
  59329. });
  59330. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59331. this._currentRefreshId = -1;
  59332. };
  59333. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59334. get: function () {
  59335. return this._refreshRate;
  59336. },
  59337. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59338. set: function (value) {
  59339. this._refreshRate = value;
  59340. this.resetRefreshCounter();
  59341. },
  59342. enumerable: true,
  59343. configurable: true
  59344. });
  59345. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59346. if (!this._postProcessManager) {
  59347. var scene = this.getScene();
  59348. if (!scene) {
  59349. return;
  59350. }
  59351. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59352. this._postProcesses = new Array();
  59353. }
  59354. this._postProcesses.push(postProcess);
  59355. this._postProcesses[0].autoClear = false;
  59356. };
  59357. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59358. if (!this._postProcesses) {
  59359. return;
  59360. }
  59361. if (dispose) {
  59362. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59363. var postProcess = _a[_i];
  59364. postProcess.dispose();
  59365. }
  59366. }
  59367. this._postProcesses = [];
  59368. };
  59369. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59370. if (!this._postProcesses) {
  59371. return;
  59372. }
  59373. var index = this._postProcesses.indexOf(postProcess);
  59374. if (index === -1) {
  59375. return;
  59376. }
  59377. this._postProcesses.splice(index, 1);
  59378. if (this._postProcesses.length > 0) {
  59379. this._postProcesses[0].autoClear = false;
  59380. }
  59381. };
  59382. RenderTargetTexture.prototype._shouldRender = function () {
  59383. if (this._currentRefreshId === -1) {
  59384. this._currentRefreshId = 1;
  59385. return true;
  59386. }
  59387. if (this.refreshRate === this._currentRefreshId) {
  59388. this._currentRefreshId = 1;
  59389. return true;
  59390. }
  59391. this._currentRefreshId++;
  59392. return false;
  59393. };
  59394. RenderTargetTexture.prototype.getRenderSize = function () {
  59395. if (this._size.width) {
  59396. return this._size.width;
  59397. }
  59398. return this._size;
  59399. };
  59400. RenderTargetTexture.prototype.getRenderWidth = function () {
  59401. if (this._size.width) {
  59402. return this._size.width;
  59403. }
  59404. return this._size;
  59405. };
  59406. RenderTargetTexture.prototype.getRenderHeight = function () {
  59407. if (this._size.width) {
  59408. return this._size.height;
  59409. }
  59410. return this._size;
  59411. };
  59412. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59413. get: function () {
  59414. return true;
  59415. },
  59416. enumerable: true,
  59417. configurable: true
  59418. });
  59419. RenderTargetTexture.prototype.scale = function (ratio) {
  59420. var newSize = this.getRenderSize() * ratio;
  59421. this.resize(newSize);
  59422. };
  59423. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59424. if (this.isCube) {
  59425. return this._textureMatrix;
  59426. }
  59427. return _super.prototype.getReflectionTextureMatrix.call(this);
  59428. };
  59429. RenderTargetTexture.prototype.resize = function (size) {
  59430. this.releaseInternalTexture();
  59431. var scene = this.getScene();
  59432. if (!scene) {
  59433. return;
  59434. }
  59435. this._processSizeParameter(size);
  59436. if (this.isCube) {
  59437. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59438. }
  59439. else {
  59440. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59441. }
  59442. };
  59443. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59444. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59445. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59446. var scene = this.getScene();
  59447. if (!scene) {
  59448. return;
  59449. }
  59450. var engine = scene.getEngine();
  59451. if (this.useCameraPostProcesses !== undefined) {
  59452. useCameraPostProcess = this.useCameraPostProcesses;
  59453. }
  59454. if (this._waitingRenderList) {
  59455. this.renderList = [];
  59456. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59457. var id = this._waitingRenderList[index];
  59458. var mesh_1 = scene.getMeshByID(id);
  59459. if (mesh_1) {
  59460. this.renderList.push(mesh_1);
  59461. }
  59462. }
  59463. delete this._waitingRenderList;
  59464. }
  59465. // Is predicate defined?
  59466. if (this.renderListPredicate) {
  59467. if (this.renderList) {
  59468. this.renderList.splice(0); // Clear previous renderList
  59469. }
  59470. else {
  59471. this.renderList = [];
  59472. }
  59473. var scene = this.getScene();
  59474. if (!scene) {
  59475. return;
  59476. }
  59477. var sceneMeshes = scene.meshes;
  59478. for (var index = 0; index < sceneMeshes.length; index++) {
  59479. var mesh = sceneMeshes[index];
  59480. if (this.renderListPredicate(mesh)) {
  59481. this.renderList.push(mesh);
  59482. }
  59483. }
  59484. }
  59485. this.onBeforeBindObservable.notifyObservers(this);
  59486. // Set custom projection.
  59487. // Needs to be before binding to prevent changing the aspect ratio.
  59488. var camera;
  59489. if (this.activeCamera) {
  59490. camera = this.activeCamera;
  59491. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59492. if (this.activeCamera !== scene.activeCamera) {
  59493. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59494. }
  59495. }
  59496. else {
  59497. camera = scene.activeCamera;
  59498. if (camera) {
  59499. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59500. }
  59501. }
  59502. // Prepare renderingManager
  59503. this._renderingManager.reset();
  59504. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59505. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59506. var sceneRenderId = scene.getRenderId();
  59507. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59508. var mesh = currentRenderList[meshIndex];
  59509. if (mesh) {
  59510. if (!mesh.isReady(this.refreshRate === 0)) {
  59511. this.resetRefreshCounter();
  59512. continue;
  59513. }
  59514. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59515. var isMasked = void 0;
  59516. if (!this.renderList && camera) {
  59517. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59518. }
  59519. else {
  59520. isMasked = false;
  59521. }
  59522. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59523. mesh._activate(sceneRenderId);
  59524. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59525. var subMesh = mesh.subMeshes[subIndex];
  59526. scene._activeIndices.addCount(subMesh.indexCount, false);
  59527. this._renderingManager.dispatch(subMesh, mesh);
  59528. }
  59529. }
  59530. }
  59531. }
  59532. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59533. var particleSystem = scene.particleSystems[particleIndex];
  59534. var emitter = particleSystem.emitter;
  59535. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59536. continue;
  59537. }
  59538. if (currentRenderList.indexOf(emitter) >= 0) {
  59539. this._renderingManager.dispatchParticles(particleSystem);
  59540. }
  59541. }
  59542. if (this.isCube) {
  59543. for (var face = 0; face < 6; face++) {
  59544. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59545. scene.incrementRenderId();
  59546. scene.resetCachedMaterial();
  59547. }
  59548. }
  59549. else {
  59550. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59551. }
  59552. this.onAfterUnbindObservable.notifyObservers(this);
  59553. if (scene.activeCamera) {
  59554. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59555. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59556. }
  59557. engine.setViewport(scene.activeCamera.viewport);
  59558. }
  59559. scene.resetCachedMaterial();
  59560. };
  59561. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59562. var minimum = 128;
  59563. var x = renderDimension * scale;
  59564. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59565. // Ensure we don't exceed the render dimension (while staying POT)
  59566. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59567. };
  59568. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59569. var _this = this;
  59570. if (!this._texture) {
  59571. return;
  59572. }
  59573. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59574. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59575. });
  59576. };
  59577. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59578. var scene = this.getScene();
  59579. if (!scene) {
  59580. return;
  59581. }
  59582. var engine = scene.getEngine();
  59583. if (!this._texture) {
  59584. return;
  59585. }
  59586. // Bind
  59587. if (this._postProcessManager) {
  59588. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59589. }
  59590. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59591. if (this._texture) {
  59592. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59593. }
  59594. }
  59595. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59596. // Clear
  59597. if (this.onClearObservable.hasObservers()) {
  59598. this.onClearObservable.notifyObservers(engine);
  59599. }
  59600. else {
  59601. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59602. }
  59603. if (!this._doNotChangeAspectRatio) {
  59604. scene.updateTransformMatrix(true);
  59605. }
  59606. // Render
  59607. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59608. if (this._postProcessManager) {
  59609. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59610. }
  59611. else if (useCameraPostProcess) {
  59612. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59613. }
  59614. if (!this._doNotChangeAspectRatio) {
  59615. scene.updateTransformMatrix(true);
  59616. }
  59617. // Dump ?
  59618. if (dumpForDebug) {
  59619. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59620. }
  59621. // Unbind
  59622. if (!this.isCube || faceIndex === 5) {
  59623. if (this.isCube) {
  59624. if (faceIndex === 5) {
  59625. engine.generateMipMapsForCubemap(this._texture);
  59626. }
  59627. }
  59628. this.unbindFrameBuffer(engine, faceIndex);
  59629. }
  59630. else {
  59631. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59632. }
  59633. };
  59634. /**
  59635. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59636. * This allowed control for front to back rendering or reversly depending of the special needs.
  59637. *
  59638. * @param renderingGroupId The rendering group id corresponding to its index
  59639. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59640. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59641. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59642. */
  59643. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59644. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59645. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59646. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59647. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59648. };
  59649. /**
  59650. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59651. *
  59652. * @param renderingGroupId The rendering group id corresponding to its index
  59653. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59654. */
  59655. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59656. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59657. };
  59658. RenderTargetTexture.prototype.clone = function () {
  59659. var textureSize = this.getSize();
  59660. 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);
  59661. // Base texture
  59662. newTexture.hasAlpha = this.hasAlpha;
  59663. newTexture.level = this.level;
  59664. // RenderTarget Texture
  59665. newTexture.coordinatesMode = this.coordinatesMode;
  59666. if (this.renderList) {
  59667. newTexture.renderList = this.renderList.slice(0);
  59668. }
  59669. return newTexture;
  59670. };
  59671. RenderTargetTexture.prototype.serialize = function () {
  59672. if (!this.name) {
  59673. return null;
  59674. }
  59675. var serializationObject = _super.prototype.serialize.call(this);
  59676. serializationObject.renderTargetSize = this.getRenderSize();
  59677. serializationObject.renderList = [];
  59678. if (this.renderList) {
  59679. for (var index = 0; index < this.renderList.length; index++) {
  59680. serializationObject.renderList.push(this.renderList[index].id);
  59681. }
  59682. }
  59683. return serializationObject;
  59684. };
  59685. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59686. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59687. var objBuffer = this.getInternalTexture();
  59688. var scene = this.getScene();
  59689. if (objBuffer && scene) {
  59690. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59691. }
  59692. };
  59693. RenderTargetTexture.prototype.dispose = function () {
  59694. if (this._postProcessManager) {
  59695. this._postProcessManager.dispose();
  59696. this._postProcessManager = null;
  59697. }
  59698. this.clearPostProcesses(true);
  59699. if (this._resizeObserver) {
  59700. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59701. this._resizeObserver = null;
  59702. }
  59703. this.renderList = null;
  59704. // Remove from custom render targets
  59705. var scene = this.getScene();
  59706. if (!scene) {
  59707. return;
  59708. }
  59709. var index = scene.customRenderTargets.indexOf(this);
  59710. if (index >= 0) {
  59711. scene.customRenderTargets.splice(index, 1);
  59712. }
  59713. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59714. var camera = _a[_i];
  59715. index = camera.customRenderTargets.indexOf(this);
  59716. if (index >= 0) {
  59717. camera.customRenderTargets.splice(index, 1);
  59718. }
  59719. }
  59720. _super.prototype.dispose.call(this);
  59721. };
  59722. RenderTargetTexture.prototype._rebuild = function () {
  59723. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59724. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59725. }
  59726. if (this._postProcessManager) {
  59727. this._postProcessManager._rebuild();
  59728. }
  59729. };
  59730. /**
  59731. * Clear the info related to rendering groups preventing retention point in material dispose.
  59732. */
  59733. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59734. if (this._renderingManager) {
  59735. this._renderingManager.freeRenderingGroups();
  59736. }
  59737. };
  59738. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59739. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59740. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59741. return RenderTargetTexture;
  59742. }(BABYLON.Texture));
  59743. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59744. })(BABYLON || (BABYLON = {}));
  59745. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59746. "use strict";
  59747. var BABYLON;
  59748. (function (BABYLON) {
  59749. ;
  59750. var MultiRenderTarget = /** @class */ (function (_super) {
  59751. __extends(MultiRenderTarget, _super);
  59752. function MultiRenderTarget(name, size, count, scene, options) {
  59753. var _this = this;
  59754. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59755. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59756. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59757. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59758. _this._engine = scene.getEngine();
  59759. if (!_this.isSupported) {
  59760. _this.dispose();
  59761. return;
  59762. }
  59763. var types = [];
  59764. var samplingModes = [];
  59765. for (var i = 0; i < count; i++) {
  59766. if (options && options.types && options.types[i] !== undefined) {
  59767. types.push(options.types[i]);
  59768. }
  59769. else {
  59770. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59771. }
  59772. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59773. samplingModes.push(options.samplingModes[i]);
  59774. }
  59775. else {
  59776. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59777. }
  59778. }
  59779. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59780. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59781. _this._size = size;
  59782. _this._multiRenderTargetOptions = {
  59783. samplingModes: samplingModes,
  59784. generateMipMaps: generateMipMaps,
  59785. generateDepthBuffer: generateDepthBuffer,
  59786. generateStencilBuffer: generateStencilBuffer,
  59787. generateDepthTexture: generateDepthTexture,
  59788. types: types,
  59789. textureCount: count
  59790. };
  59791. _this._createInternalTextures();
  59792. _this._createTextures();
  59793. return _this;
  59794. }
  59795. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59796. get: function () {
  59797. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59798. },
  59799. enumerable: true,
  59800. configurable: true
  59801. });
  59802. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59803. get: function () {
  59804. return this._textures;
  59805. },
  59806. enumerable: true,
  59807. configurable: true
  59808. });
  59809. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59810. get: function () {
  59811. return this._textures[this._textures.length - 1];
  59812. },
  59813. enumerable: true,
  59814. configurable: true
  59815. });
  59816. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59817. set: function (wrap) {
  59818. if (this._textures) {
  59819. for (var i = 0; i < this._textures.length; i++) {
  59820. this._textures[i].wrapU = wrap;
  59821. }
  59822. }
  59823. },
  59824. enumerable: true,
  59825. configurable: true
  59826. });
  59827. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59828. set: function (wrap) {
  59829. if (this._textures) {
  59830. for (var i = 0; i < this._textures.length; i++) {
  59831. this._textures[i].wrapV = wrap;
  59832. }
  59833. }
  59834. },
  59835. enumerable: true,
  59836. configurable: true
  59837. });
  59838. MultiRenderTarget.prototype._rebuild = function () {
  59839. this.releaseInternalTextures();
  59840. this._createInternalTextures();
  59841. for (var i = 0; i < this._internalTextures.length; i++) {
  59842. var texture = this._textures[i];
  59843. texture._texture = this._internalTextures[i];
  59844. }
  59845. // Keeps references to frame buffer and stencil/depth buffer
  59846. this._texture = this._internalTextures[0];
  59847. };
  59848. MultiRenderTarget.prototype._createInternalTextures = function () {
  59849. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59850. };
  59851. MultiRenderTarget.prototype._createTextures = function () {
  59852. this._textures = [];
  59853. for (var i = 0; i < this._internalTextures.length; i++) {
  59854. var texture = new BABYLON.Texture(null, this.getScene());
  59855. texture._texture = this._internalTextures[i];
  59856. this._textures.push(texture);
  59857. }
  59858. // Keeps references to frame buffer and stencil/depth buffer
  59859. this._texture = this._internalTextures[0];
  59860. };
  59861. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59862. get: function () {
  59863. return this._samples;
  59864. },
  59865. set: function (value) {
  59866. if (this._samples === value) {
  59867. return;
  59868. }
  59869. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59870. },
  59871. enumerable: true,
  59872. configurable: true
  59873. });
  59874. MultiRenderTarget.prototype.resize = function (size) {
  59875. this.releaseInternalTextures();
  59876. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59877. this._createInternalTextures();
  59878. };
  59879. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59880. var _this = this;
  59881. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59882. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59883. });
  59884. };
  59885. MultiRenderTarget.prototype.dispose = function () {
  59886. this.releaseInternalTextures();
  59887. _super.prototype.dispose.call(this);
  59888. };
  59889. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59890. if (!this._internalTextures) {
  59891. return;
  59892. }
  59893. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59894. if (this._internalTextures[i] !== undefined) {
  59895. this._internalTextures[i].dispose();
  59896. this._internalTextures.splice(i, 1);
  59897. }
  59898. }
  59899. };
  59900. return MultiRenderTarget;
  59901. }(BABYLON.RenderTargetTexture));
  59902. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59903. })(BABYLON || (BABYLON = {}));
  59904. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59905. "use strict";
  59906. var BABYLON;
  59907. (function (BABYLON) {
  59908. var MirrorTexture = /** @class */ (function (_super) {
  59909. __extends(MirrorTexture, _super);
  59910. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59911. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59913. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59914. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59915. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59916. _this._transformMatrix = BABYLON.Matrix.Zero();
  59917. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59918. _this._adaptiveBlurKernel = 0;
  59919. _this._blurKernelX = 0;
  59920. _this._blurKernelY = 0;
  59921. _this._blurRatio = 1.0;
  59922. _this.ignoreCameraViewport = true;
  59923. _this.onBeforeRenderObservable.add(function () {
  59924. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59925. _this._savedViewMatrix = scene.getViewMatrix();
  59926. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59927. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59928. scene.clipPlane = _this.mirrorPlane;
  59929. scene.getEngine().cullBackFaces = false;
  59930. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59931. });
  59932. _this.onAfterRenderObservable.add(function () {
  59933. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59934. scene.getEngine().cullBackFaces = true;
  59935. scene._mirroredCameraPosition = null;
  59936. delete scene.clipPlane;
  59937. });
  59938. return _this;
  59939. }
  59940. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59941. get: function () {
  59942. return this._blurRatio;
  59943. },
  59944. set: function (value) {
  59945. if (this._blurRatio === value) {
  59946. return;
  59947. }
  59948. this._blurRatio = value;
  59949. this._preparePostProcesses();
  59950. },
  59951. enumerable: true,
  59952. configurable: true
  59953. });
  59954. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59955. set: function (value) {
  59956. this._adaptiveBlurKernel = value;
  59957. this._autoComputeBlurKernel();
  59958. },
  59959. enumerable: true,
  59960. configurable: true
  59961. });
  59962. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59963. set: function (value) {
  59964. this.blurKernelX = value;
  59965. this.blurKernelY = value;
  59966. },
  59967. enumerable: true,
  59968. configurable: true
  59969. });
  59970. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59971. get: function () {
  59972. return this._blurKernelX;
  59973. },
  59974. set: function (value) {
  59975. if (this._blurKernelX === value) {
  59976. return;
  59977. }
  59978. this._blurKernelX = value;
  59979. this._preparePostProcesses();
  59980. },
  59981. enumerable: true,
  59982. configurable: true
  59983. });
  59984. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59985. get: function () {
  59986. return this._blurKernelY;
  59987. },
  59988. set: function (value) {
  59989. if (this._blurKernelY === value) {
  59990. return;
  59991. }
  59992. this._blurKernelY = value;
  59993. this._preparePostProcesses();
  59994. },
  59995. enumerable: true,
  59996. configurable: true
  59997. });
  59998. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59999. var engine = this.getScene().getEngine();
  60000. var dw = this.getRenderWidth() / engine.getRenderWidth();
  60001. var dh = this.getRenderHeight() / engine.getRenderHeight();
  60002. this.blurKernelX = this._adaptiveBlurKernel * dw;
  60003. this.blurKernelY = this._adaptiveBlurKernel * dh;
  60004. };
  60005. MirrorTexture.prototype._onRatioRescale = function () {
  60006. if (this._sizeRatio) {
  60007. this.resize(this._initialSizeParameter);
  60008. if (!this._adaptiveBlurKernel) {
  60009. this._preparePostProcesses();
  60010. }
  60011. }
  60012. if (this._adaptiveBlurKernel) {
  60013. this._autoComputeBlurKernel();
  60014. }
  60015. };
  60016. MirrorTexture.prototype._preparePostProcesses = function () {
  60017. this.clearPostProcesses(true);
  60018. if (this._blurKernelX && this._blurKernelY) {
  60019. var engine = this.getScene().getEngine();
  60020. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60021. 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);
  60022. this._blurX.autoClear = false;
  60023. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  60024. this._blurX.inputTexture = this._texture;
  60025. }
  60026. else {
  60027. this._blurX.alwaysForcePOT = true;
  60028. }
  60029. 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);
  60030. this._blurY.autoClear = false;
  60031. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  60032. this.addPostProcess(this._blurX);
  60033. this.addPostProcess(this._blurY);
  60034. }
  60035. else {
  60036. if (this._blurY) {
  60037. this.removePostProcess(this._blurY);
  60038. this._blurY.dispose();
  60039. this._blurY = null;
  60040. }
  60041. if (this._blurX) {
  60042. this.removePostProcess(this._blurX);
  60043. this._blurX.dispose();
  60044. this._blurX = null;
  60045. }
  60046. }
  60047. };
  60048. MirrorTexture.prototype.clone = function () {
  60049. var scene = this.getScene();
  60050. if (!scene) {
  60051. return this;
  60052. }
  60053. var textureSize = this.getSize();
  60054. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  60055. // Base texture
  60056. newTexture.hasAlpha = this.hasAlpha;
  60057. newTexture.level = this.level;
  60058. // Mirror Texture
  60059. newTexture.mirrorPlane = this.mirrorPlane.clone();
  60060. if (this.renderList) {
  60061. newTexture.renderList = this.renderList.slice(0);
  60062. }
  60063. return newTexture;
  60064. };
  60065. MirrorTexture.prototype.serialize = function () {
  60066. if (!this.name) {
  60067. return null;
  60068. }
  60069. var serializationObject = _super.prototype.serialize.call(this);
  60070. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  60071. return serializationObject;
  60072. };
  60073. return MirrorTexture;
  60074. }(BABYLON.RenderTargetTexture));
  60075. BABYLON.MirrorTexture = MirrorTexture;
  60076. })(BABYLON || (BABYLON = {}));
  60077. //# sourceMappingURL=babylon.mirrorTexture.js.map
  60078. "use strict";
  60079. var BABYLON;
  60080. (function (BABYLON) {
  60081. /**
  60082. * Creates a refraction texture used by refraction channel of the standard material.
  60083. * @param name the texture name
  60084. * @param size size of the underlying texture
  60085. * @param scene root scene
  60086. */
  60087. var RefractionTexture = /** @class */ (function (_super) {
  60088. __extends(RefractionTexture, _super);
  60089. function RefractionTexture(name, size, scene, generateMipMaps) {
  60090. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60091. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60092. _this.depth = 2.0;
  60093. _this.onBeforeRenderObservable.add(function () {
  60094. scene.clipPlane = _this.refractionPlane;
  60095. });
  60096. _this.onAfterRenderObservable.add(function () {
  60097. delete scene.clipPlane;
  60098. });
  60099. return _this;
  60100. }
  60101. RefractionTexture.prototype.clone = function () {
  60102. var scene = this.getScene();
  60103. if (!scene) {
  60104. return this;
  60105. }
  60106. var textureSize = this.getSize();
  60107. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60108. // Base texture
  60109. newTexture.hasAlpha = this.hasAlpha;
  60110. newTexture.level = this.level;
  60111. // Refraction Texture
  60112. newTexture.refractionPlane = this.refractionPlane.clone();
  60113. if (this.renderList) {
  60114. newTexture.renderList = this.renderList.slice(0);
  60115. }
  60116. newTexture.depth = this.depth;
  60117. return newTexture;
  60118. };
  60119. RefractionTexture.prototype.serialize = function () {
  60120. if (!this.name) {
  60121. return null;
  60122. }
  60123. var serializationObject = _super.prototype.serialize.call(this);
  60124. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60125. serializationObject.depth = this.depth;
  60126. return serializationObject;
  60127. };
  60128. return RefractionTexture;
  60129. }(BABYLON.RenderTargetTexture));
  60130. BABYLON.RefractionTexture = RefractionTexture;
  60131. })(BABYLON || (BABYLON = {}));
  60132. //# sourceMappingURL=babylon.refractionTexture.js.map
  60133. "use strict";
  60134. var BABYLON;
  60135. (function (BABYLON) {
  60136. /**
  60137. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60138. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60139. */
  60140. var DynamicTexture = /** @class */ (function (_super) {
  60141. __extends(DynamicTexture, _super);
  60142. /**
  60143. * Creates a {BABYLON.DynamicTexture}
  60144. * @param name defines the name of the texture
  60145. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  60146. * @param scene defines the scene where you want the texture
  60147. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60148. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60149. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60150. */
  60151. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60152. if (scene === void 0) { scene = null; }
  60153. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60154. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60155. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60156. _this.name = name;
  60157. _this._engine = _this.getScene().getEngine();
  60158. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60159. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60160. _this._generateMipMaps = generateMipMaps;
  60161. if (options.getContext) {
  60162. _this._canvas = options;
  60163. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60164. }
  60165. else {
  60166. _this._canvas = document.createElement("canvas");
  60167. if (options.width) {
  60168. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60169. }
  60170. else {
  60171. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60172. }
  60173. }
  60174. var textureSize = _this.getSize();
  60175. _this._canvas.width = textureSize.width;
  60176. _this._canvas.height = textureSize.height;
  60177. _this._context = _this._canvas.getContext("2d");
  60178. return _this;
  60179. }
  60180. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60181. /**
  60182. * Gets the current state of canRescale
  60183. */
  60184. get: function () {
  60185. return true;
  60186. },
  60187. enumerable: true,
  60188. configurable: true
  60189. });
  60190. DynamicTexture.prototype._recreate = function (textureSize) {
  60191. this._canvas.width = textureSize.width;
  60192. this._canvas.height = textureSize.height;
  60193. this.releaseInternalTexture();
  60194. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60195. };
  60196. /**
  60197. * Scales the texture
  60198. * @param ratio the scale factor to apply to both width and height
  60199. */
  60200. DynamicTexture.prototype.scale = function (ratio) {
  60201. var textureSize = this.getSize();
  60202. textureSize.width *= ratio;
  60203. textureSize.height *= ratio;
  60204. this._recreate(textureSize);
  60205. };
  60206. /**
  60207. * Resizes the texture
  60208. * @param width the new width
  60209. * @param height the new height
  60210. */
  60211. DynamicTexture.prototype.scaleTo = function (width, height) {
  60212. var textureSize = this.getSize();
  60213. textureSize.width = width;
  60214. textureSize.height = height;
  60215. this._recreate(textureSize);
  60216. };
  60217. /**
  60218. * Gets the context of the canvas used by the texture
  60219. * @returns the canvas context of the dynamic texture
  60220. */
  60221. DynamicTexture.prototype.getContext = function () {
  60222. return this._context;
  60223. };
  60224. /**
  60225. * Clears the texture
  60226. */
  60227. DynamicTexture.prototype.clear = function () {
  60228. var size = this.getSize();
  60229. this._context.fillRect(0, 0, size.width, size.height);
  60230. };
  60231. /**
  60232. * Updates the texture
  60233. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60234. */
  60235. DynamicTexture.prototype.update = function (invertY) {
  60236. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60237. };
  60238. /**
  60239. * Draws text onto the texture
  60240. * @param text defines the text to be drawn
  60241. * @param x defines the placement of the text from the left
  60242. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60243. * @param font defines the font to be used with font-style, font-size, font-name
  60244. * @param color defines the color used for the text
  60245. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60246. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60247. * @param update defines whether texture is immediately update (default is true)
  60248. */
  60249. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60250. if (update === void 0) { update = true; }
  60251. var size = this.getSize();
  60252. if (clearColor) {
  60253. this._context.fillStyle = clearColor;
  60254. this._context.fillRect(0, 0, size.width, size.height);
  60255. }
  60256. this._context.font = font;
  60257. if (x === null || x === undefined) {
  60258. var textSize = this._context.measureText(text);
  60259. x = (size.width - textSize.width) / 2;
  60260. }
  60261. if (y === null || y === undefined) {
  60262. var fontSize = parseInt((font.replace(/\D/g, '')));
  60263. ;
  60264. y = (size.height / 2) + (fontSize / 3.65);
  60265. }
  60266. this._context.fillStyle = color;
  60267. this._context.fillText(text, x, y);
  60268. if (update) {
  60269. this.update(invertY);
  60270. }
  60271. };
  60272. /**
  60273. * Clones the texture
  60274. * @returns the clone of the texture.
  60275. */
  60276. DynamicTexture.prototype.clone = function () {
  60277. var scene = this.getScene();
  60278. if (!scene) {
  60279. return this;
  60280. }
  60281. var textureSize = this.getSize();
  60282. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60283. // Base texture
  60284. newTexture.hasAlpha = this.hasAlpha;
  60285. newTexture.level = this.level;
  60286. // Dynamic Texture
  60287. newTexture.wrapU = this.wrapU;
  60288. newTexture.wrapV = this.wrapV;
  60289. return newTexture;
  60290. };
  60291. /** @ignore */
  60292. DynamicTexture.prototype._rebuild = function () {
  60293. this.update();
  60294. };
  60295. return DynamicTexture;
  60296. }(BABYLON.Texture));
  60297. BABYLON.DynamicTexture = DynamicTexture;
  60298. })(BABYLON || (BABYLON = {}));
  60299. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60300. "use strict";
  60301. var BABYLON;
  60302. (function (BABYLON) {
  60303. var VideoTexture = /** @class */ (function (_super) {
  60304. __extends(VideoTexture, _super);
  60305. /**
  60306. * Creates a video texture.
  60307. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60308. * @param {string | null} name optional name, will detect from video source, if not defined
  60309. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60310. * @param {BABYLON.Scene} scene is obviously the current scene.
  60311. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60312. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60313. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60314. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60315. */
  60316. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60317. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60318. if (invertY === void 0) { invertY = false; }
  60319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60320. if (settings === void 0) { settings = {
  60321. autoPlay: true,
  60322. loop: true,
  60323. autoUpdateTexture: true,
  60324. }; }
  60325. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60326. _this._createInternalTexture = function () {
  60327. if (_this._texture != null) {
  60328. return;
  60329. }
  60330. if (!_this._engine.needPOTTextures ||
  60331. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60332. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60333. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60334. }
  60335. else {
  60336. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60337. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60338. _this._generateMipMaps = false;
  60339. }
  60340. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60341. _this._texture.isReady = true;
  60342. _this._updateInternalTexture();
  60343. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60344. _this.onLoadObservable.notifyObservers(_this);
  60345. }
  60346. };
  60347. _this.reset = function () {
  60348. if (_this._texture == null) {
  60349. return;
  60350. }
  60351. _this._texture.dispose();
  60352. _this._texture = null;
  60353. };
  60354. _this._updateInternalTexture = function (e) {
  60355. if (_this._texture == null || !_this._texture.isReady) {
  60356. return;
  60357. }
  60358. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60359. return;
  60360. }
  60361. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60362. };
  60363. _this._engine = _this.getScene().getEngine();
  60364. _this._generateMipMaps = generateMipMaps;
  60365. _this._samplingMode = samplingMode;
  60366. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60367. _this.name = name || _this._getName(src);
  60368. _this.video = _this._getVideo(src);
  60369. if (settings.autoPlay !== undefined) {
  60370. _this.video.autoplay = settings.autoPlay;
  60371. }
  60372. if (settings.loop !== undefined) {
  60373. _this.video.loop = settings.loop;
  60374. }
  60375. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60376. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60377. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60378. _this.video.addEventListener("emptied", _this.reset);
  60379. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60380. _this._createInternalTexture();
  60381. }
  60382. return _this;
  60383. }
  60384. VideoTexture.prototype._getName = function (src) {
  60385. if (src instanceof HTMLVideoElement) {
  60386. return src.currentSrc;
  60387. }
  60388. if (typeof src === "object") {
  60389. return src.toString();
  60390. }
  60391. return src;
  60392. };
  60393. ;
  60394. VideoTexture.prototype._getVideo = function (src) {
  60395. if (src instanceof HTMLVideoElement) {
  60396. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60397. return src;
  60398. }
  60399. var video = document.createElement("video");
  60400. if (typeof src === "string") {
  60401. BABYLON.Tools.SetCorsBehavior(src, video);
  60402. video.src = src;
  60403. }
  60404. else {
  60405. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60406. src.forEach(function (url) {
  60407. var source = document.createElement("source");
  60408. source.src = url;
  60409. video.appendChild(source);
  60410. });
  60411. }
  60412. return video;
  60413. };
  60414. ;
  60415. /**
  60416. * Internal method to initiate `update`.
  60417. */
  60418. VideoTexture.prototype._rebuild = function () {
  60419. this.update();
  60420. };
  60421. /**
  60422. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60423. */
  60424. VideoTexture.prototype.update = function () {
  60425. if (!this.autoUpdateTexture) {
  60426. // Expecting user to call `updateTexture` manually
  60427. return;
  60428. }
  60429. this.updateTexture(true);
  60430. };
  60431. /**
  60432. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60433. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60434. */
  60435. VideoTexture.prototype.updateTexture = function (isVisible) {
  60436. if (!isVisible) {
  60437. return;
  60438. }
  60439. if (this.video.paused) {
  60440. return;
  60441. }
  60442. this._updateInternalTexture();
  60443. };
  60444. /**
  60445. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60446. * @param url New url.
  60447. */
  60448. VideoTexture.prototype.updateURL = function (url) {
  60449. this.video.src = url;
  60450. };
  60451. VideoTexture.prototype.dispose = function () {
  60452. _super.prototype.dispose.call(this);
  60453. this.video.removeEventListener("canplay", this._createInternalTexture);
  60454. this.video.removeEventListener("paused", this._updateInternalTexture);
  60455. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60456. this.video.removeEventListener("emptied", this.reset);
  60457. this.video.pause();
  60458. };
  60459. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60460. var video = document.createElement("video");
  60461. var constraintsDeviceId;
  60462. if (constraints && constraints.deviceId) {
  60463. constraintsDeviceId = {
  60464. exact: constraints.deviceId,
  60465. };
  60466. }
  60467. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60468. if (navigator.mediaDevices) {
  60469. navigator.mediaDevices.getUserMedia({ video: constraints })
  60470. .then(function (stream) {
  60471. if (video.mozSrcObject !== undefined) {
  60472. // hack for Firefox < 19
  60473. video.mozSrcObject = stream;
  60474. }
  60475. else {
  60476. video.srcObject = stream;
  60477. }
  60478. var onPlaying = function () {
  60479. if (onReady) {
  60480. onReady(new VideoTexture("video", video, scene, true, true));
  60481. }
  60482. video.removeEventListener("playing", onPlaying);
  60483. };
  60484. video.addEventListener("playing", onPlaying);
  60485. video.play();
  60486. })
  60487. .catch(function (err) {
  60488. BABYLON.Tools.Error(err.name);
  60489. });
  60490. }
  60491. else {
  60492. navigator.getUserMedia =
  60493. navigator.getUserMedia ||
  60494. navigator.webkitGetUserMedia ||
  60495. navigator.mozGetUserMedia ||
  60496. navigator.msGetUserMedia;
  60497. if (navigator.getUserMedia) {
  60498. navigator.getUserMedia({
  60499. video: {
  60500. deviceId: constraintsDeviceId,
  60501. width: {
  60502. min: (constraints && constraints.minWidth) || 256,
  60503. max: (constraints && constraints.maxWidth) || 640,
  60504. },
  60505. height: {
  60506. min: (constraints && constraints.minHeight) || 256,
  60507. max: (constraints && constraints.maxHeight) || 480,
  60508. },
  60509. },
  60510. }, function (stream) {
  60511. if (video.mozSrcObject !== undefined) {
  60512. // hack for Firefox < 19
  60513. video.mozSrcObject = stream;
  60514. }
  60515. else {
  60516. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60517. }
  60518. video.play();
  60519. if (onReady) {
  60520. onReady(new VideoTexture("video", video, scene, true, true));
  60521. }
  60522. }, function (e) {
  60523. BABYLON.Tools.Error(e.name);
  60524. });
  60525. }
  60526. }
  60527. };
  60528. return VideoTexture;
  60529. }(BABYLON.Texture));
  60530. BABYLON.VideoTexture = VideoTexture;
  60531. })(BABYLON || (BABYLON = {}));
  60532. //# sourceMappingURL=babylon.videoTexture.js.map
  60533. "use strict";
  60534. var BABYLON;
  60535. (function (BABYLON) {
  60536. var RawTexture = /** @class */ (function (_super) {
  60537. __extends(RawTexture, _super);
  60538. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60539. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60540. if (invertY === void 0) { invertY = false; }
  60541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60542. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60543. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60544. _this.format = format;
  60545. _this._engine = scene.getEngine();
  60546. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60547. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60548. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60549. return _this;
  60550. }
  60551. RawTexture.prototype.update = function (data) {
  60552. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60553. };
  60554. // Statics
  60555. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60556. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60557. if (invertY === void 0) { invertY = false; }
  60558. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60559. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60560. };
  60561. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60562. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60563. if (invertY === void 0) { invertY = false; }
  60564. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60565. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60566. };
  60567. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60568. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60569. if (invertY === void 0) { invertY = false; }
  60570. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60571. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60572. };
  60573. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60574. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60575. if (invertY === void 0) { invertY = false; }
  60576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60577. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60578. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60579. };
  60580. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60581. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60582. if (invertY === void 0) { invertY = false; }
  60583. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60584. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60585. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60586. };
  60587. return RawTexture;
  60588. }(BABYLON.Texture));
  60589. BABYLON.RawTexture = RawTexture;
  60590. })(BABYLON || (BABYLON = {}));
  60591. //# sourceMappingURL=babylon.rawTexture.js.map
  60592. "use strict";
  60593. var BABYLON;
  60594. (function (BABYLON) {
  60595. /**
  60596. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60597. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60598. */
  60599. var PostProcess = /** @class */ (function () {
  60600. /**
  60601. * Creates a new instance PostProcess
  60602. * @param name The name of the PostProcess.
  60603. * @param fragmentUrl The url of the fragment shader to be used.
  60604. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60605. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60606. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60607. * @param camera The camera to apply the render pass to.
  60608. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60609. * @param engine The engine which the post process will be applied. (default: current engine)
  60610. * @param reusable If the post process can be reused on the same frame. (default: false)
  60611. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60612. * @param textureType Type of textures used when performing the post process. (default: 0)
  60613. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60614. * @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
  60615. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60616. */
  60617. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60619. if (defines === void 0) { defines = null; }
  60620. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60621. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60622. if (blockCompilation === void 0) { blockCompilation = false; }
  60623. this.name = name;
  60624. /**
  60625. * Width of the texture to apply the post process on
  60626. */
  60627. this.width = -1;
  60628. /**
  60629. * Height of the texture to apply the post process on
  60630. */
  60631. this.height = -1;
  60632. /**
  60633. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60634. */
  60635. this._outputTexture = null;
  60636. /**
  60637. * If the buffer needs to be cleared before applying the post process. (default: true)
  60638. * Should be set to false if shader will overwrite all previous pixels.
  60639. */
  60640. this.autoClear = true;
  60641. /**
  60642. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60643. */
  60644. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60645. /**
  60646. * Animations to be used for the post processing
  60647. */
  60648. this.animations = new Array();
  60649. /**
  60650. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60651. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60652. */
  60653. this.enablePixelPerfectMode = false;
  60654. /**
  60655. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60656. */
  60657. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60658. /**
  60659. * Force textures to be a power of two (default: false)
  60660. */
  60661. this.alwaysForcePOT = false;
  60662. /**
  60663. * Number of sample textures (default: 1)
  60664. */
  60665. this.samples = 1;
  60666. /**
  60667. * Modify the scale of the post process to be the same as the viewport (default: false)
  60668. */
  60669. this.adaptScaleToCurrentViewport = false;
  60670. this._reusable = false;
  60671. /**
  60672. * Smart array of input and output textures for the post process.
  60673. */
  60674. this._textures = new BABYLON.SmartArray(2);
  60675. /**
  60676. * The index in _textures that corresponds to the output texture.
  60677. */
  60678. this._currentRenderTextureInd = 0;
  60679. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60680. this._texelSize = BABYLON.Vector2.Zero();
  60681. // Events
  60682. /**
  60683. * An event triggered when the postprocess is activated.
  60684. */
  60685. this.onActivateObservable = new BABYLON.Observable();
  60686. /**
  60687. * An event triggered when the postprocess changes its size.
  60688. */
  60689. this.onSizeChangedObservable = new BABYLON.Observable();
  60690. /**
  60691. * An event triggered when the postprocess applies its effect.
  60692. */
  60693. this.onApplyObservable = new BABYLON.Observable();
  60694. /**
  60695. * An event triggered before rendering the postprocess
  60696. */
  60697. this.onBeforeRenderObservable = new BABYLON.Observable();
  60698. /**
  60699. * An event triggered after rendering the postprocess
  60700. */
  60701. this.onAfterRenderObservable = new BABYLON.Observable();
  60702. if (camera != null) {
  60703. this._camera = camera;
  60704. this._scene = camera.getScene();
  60705. camera.attachPostProcess(this);
  60706. this._engine = this._scene.getEngine();
  60707. this._scene.postProcesses.push(this);
  60708. }
  60709. else if (engine) {
  60710. this._engine = engine;
  60711. this._engine.postProcesses.push(this);
  60712. }
  60713. this._options = options;
  60714. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60715. this._reusable = reusable || false;
  60716. this._textureType = textureType;
  60717. this._samplers = samplers || [];
  60718. this._samplers.push("textureSampler");
  60719. this._fragmentUrl = fragmentUrl;
  60720. this._vertexUrl = vertexUrl;
  60721. this._parameters = parameters || [];
  60722. this._parameters.push("scale");
  60723. this._indexParameters = indexParameters;
  60724. if (!blockCompilation) {
  60725. this.updateEffect(defines);
  60726. }
  60727. }
  60728. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60729. /**
  60730. * A function that is added to the onActivateObservable
  60731. */
  60732. set: function (callback) {
  60733. if (this._onActivateObserver) {
  60734. this.onActivateObservable.remove(this._onActivateObserver);
  60735. }
  60736. if (callback) {
  60737. this._onActivateObserver = this.onActivateObservable.add(callback);
  60738. }
  60739. },
  60740. enumerable: true,
  60741. configurable: true
  60742. });
  60743. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60744. /**
  60745. * A function that is added to the onSizeChangedObservable
  60746. */
  60747. set: function (callback) {
  60748. if (this._onSizeChangedObserver) {
  60749. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60750. }
  60751. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60752. },
  60753. enumerable: true,
  60754. configurable: true
  60755. });
  60756. Object.defineProperty(PostProcess.prototype, "onApply", {
  60757. /**
  60758. * A function that is added to the onApplyObservable
  60759. */
  60760. set: function (callback) {
  60761. if (this._onApplyObserver) {
  60762. this.onApplyObservable.remove(this._onApplyObserver);
  60763. }
  60764. this._onApplyObserver = this.onApplyObservable.add(callback);
  60765. },
  60766. enumerable: true,
  60767. configurable: true
  60768. });
  60769. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60770. /**
  60771. * A function that is added to the onBeforeRenderObservable
  60772. */
  60773. set: function (callback) {
  60774. if (this._onBeforeRenderObserver) {
  60775. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60776. }
  60777. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60778. },
  60779. enumerable: true,
  60780. configurable: true
  60781. });
  60782. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60783. /**
  60784. * A function that is added to the onAfterRenderObservable
  60785. */
  60786. set: function (callback) {
  60787. if (this._onAfterRenderObserver) {
  60788. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60789. }
  60790. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60791. },
  60792. enumerable: true,
  60793. configurable: true
  60794. });
  60795. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60796. /**
  60797. * 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
  60798. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60799. */
  60800. get: function () {
  60801. return this._textures.data[this._currentRenderTextureInd];
  60802. },
  60803. set: function (value) {
  60804. this._forcedOutputTexture = value;
  60805. },
  60806. enumerable: true,
  60807. configurable: true
  60808. });
  60809. /**
  60810. * Gets the camera which post process is applied to.
  60811. * @returns The camera the post process is applied to.
  60812. */
  60813. PostProcess.prototype.getCamera = function () {
  60814. return this._camera;
  60815. };
  60816. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60817. /**
  60818. * Gets the texel size of the postprocess.
  60819. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60820. */
  60821. get: function () {
  60822. if (this._shareOutputWithPostProcess) {
  60823. return this._shareOutputWithPostProcess.texelSize;
  60824. }
  60825. if (this._forcedOutputTexture) {
  60826. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60827. }
  60828. return this._texelSize;
  60829. },
  60830. enumerable: true,
  60831. configurable: true
  60832. });
  60833. /**
  60834. * Gets the engine which this post process belongs to.
  60835. * @returns The engine the post process was enabled with.
  60836. */
  60837. PostProcess.prototype.getEngine = function () {
  60838. return this._engine;
  60839. };
  60840. /**
  60841. * The effect that is created when initializing the post process.
  60842. * @returns The created effect corrisponding the the postprocess.
  60843. */
  60844. PostProcess.prototype.getEffect = function () {
  60845. return this._effect;
  60846. };
  60847. /**
  60848. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60849. * @param postProcess The post process to share the output with.
  60850. * @returns This post process.
  60851. */
  60852. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60853. this._disposeTextures();
  60854. this._shareOutputWithPostProcess = postProcess;
  60855. return this;
  60856. };
  60857. /**
  60858. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60859. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60860. */
  60861. PostProcess.prototype.useOwnOutput = function () {
  60862. if (this._textures.length == 0) {
  60863. this._textures = new BABYLON.SmartArray(2);
  60864. }
  60865. this._shareOutputWithPostProcess = null;
  60866. };
  60867. /**
  60868. * Updates the effect with the current post process compile time values and recompiles the shader.
  60869. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60870. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60871. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60872. * @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
  60873. * @param onCompiled Called when the shader has been compiled.
  60874. * @param onError Called if there is an error when compiling a shader.
  60875. */
  60876. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60877. if (defines === void 0) { defines = null; }
  60878. if (uniforms === void 0) { uniforms = null; }
  60879. if (samplers === void 0) { samplers = null; }
  60880. 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);
  60881. };
  60882. /**
  60883. * The post process is reusable if it can be used multiple times within one frame.
  60884. * @returns If the post process is reusable
  60885. */
  60886. PostProcess.prototype.isReusable = function () {
  60887. return this._reusable;
  60888. };
  60889. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60890. PostProcess.prototype.markTextureDirty = function () {
  60891. this.width = -1;
  60892. };
  60893. /**
  60894. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60895. * 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.
  60896. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60897. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60898. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60899. * @returns The target texture that was bound to be written to.
  60900. */
  60901. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60902. var _this = this;
  60903. if (sourceTexture === void 0) { sourceTexture = null; }
  60904. camera = camera || this._camera;
  60905. var scene = camera.getScene();
  60906. var engine = scene.getEngine();
  60907. var maxSize = engine.getCaps().maxTextureSize;
  60908. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60909. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60910. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  60911. var webVRCamera = camera.parent;
  60912. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60913. requiredWidth /= 2;
  60914. }
  60915. var desiredWidth = (this._options.width || requiredWidth);
  60916. var desiredHeight = this._options.height || requiredHeight;
  60917. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60918. if (this.adaptScaleToCurrentViewport) {
  60919. var currentViewport = engine.currentViewport;
  60920. if (currentViewport) {
  60921. desiredWidth *= currentViewport.width;
  60922. desiredHeight *= currentViewport.height;
  60923. }
  60924. }
  60925. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60926. if (!this._options.width) {
  60927. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60928. }
  60929. if (!this._options.height) {
  60930. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60931. }
  60932. }
  60933. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60934. if (this._textures.length > 0) {
  60935. for (var i = 0; i < this._textures.length; i++) {
  60936. this._engine._releaseTexture(this._textures.data[i]);
  60937. }
  60938. this._textures.reset();
  60939. }
  60940. this.width = desiredWidth;
  60941. this.height = desiredHeight;
  60942. var textureSize = { width: this.width, height: this.height };
  60943. var textureOptions = {
  60944. generateMipMaps: false,
  60945. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60946. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60947. samplingMode: this.renderTargetSamplingMode,
  60948. type: this._textureType
  60949. };
  60950. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60951. if (this._reusable) {
  60952. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60953. }
  60954. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60955. this.onSizeChangedObservable.notifyObservers(this);
  60956. }
  60957. this._textures.forEach(function (texture) {
  60958. if (texture.samples !== _this.samples) {
  60959. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60960. }
  60961. });
  60962. }
  60963. var target;
  60964. if (this._shareOutputWithPostProcess) {
  60965. target = this._shareOutputWithPostProcess.inputTexture;
  60966. }
  60967. else if (this._forcedOutputTexture) {
  60968. target = this._forcedOutputTexture;
  60969. this.width = this._forcedOutputTexture.width;
  60970. this.height = this._forcedOutputTexture.height;
  60971. }
  60972. else {
  60973. target = this.inputTexture;
  60974. }
  60975. // Bind the input of this post process to be used as the output of the previous post process.
  60976. if (this.enablePixelPerfectMode) {
  60977. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60978. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60979. }
  60980. else {
  60981. this._scaleRatio.copyFromFloats(1, 1);
  60982. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60983. }
  60984. this.onActivateObservable.notifyObservers(camera);
  60985. // Clear
  60986. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60987. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60988. }
  60989. if (this._reusable) {
  60990. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60991. }
  60992. return target;
  60993. };
  60994. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60995. /**
  60996. * If the post process is supported.
  60997. */
  60998. get: function () {
  60999. return this._effect.isSupported;
  61000. },
  61001. enumerable: true,
  61002. configurable: true
  61003. });
  61004. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  61005. /**
  61006. * The aspect ratio of the output texture.
  61007. */
  61008. get: function () {
  61009. if (this._shareOutputWithPostProcess) {
  61010. return this._shareOutputWithPostProcess.aspectRatio;
  61011. }
  61012. if (this._forcedOutputTexture) {
  61013. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  61014. }
  61015. return this.width / this.height;
  61016. },
  61017. enumerable: true,
  61018. configurable: true
  61019. });
  61020. /**
  61021. * Get a value indicating if the post-process is ready to be used
  61022. * @returns true if the post-process is ready (shader is compiled)
  61023. */
  61024. PostProcess.prototype.isReady = function () {
  61025. return this._effect && this._effect.isReady();
  61026. };
  61027. /**
  61028. * Binds all textures and uniforms to the shader, this will be run on every pass.
  61029. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  61030. */
  61031. PostProcess.prototype.apply = function () {
  61032. // Check
  61033. if (!this._effect || !this._effect.isReady())
  61034. return null;
  61035. // States
  61036. this._engine.enableEffect(this._effect);
  61037. this._engine.setState(false);
  61038. this._engine.setDepthBuffer(false);
  61039. this._engine.setDepthWrite(false);
  61040. // Alpha
  61041. this._engine.setAlphaMode(this.alphaMode);
  61042. if (this.alphaConstants) {
  61043. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  61044. }
  61045. // Bind the output texture of the preivous post process as the input to this post process.
  61046. var source;
  61047. if (this._shareOutputWithPostProcess) {
  61048. source = this._shareOutputWithPostProcess.inputTexture;
  61049. }
  61050. else if (this._forcedOutputTexture) {
  61051. source = this._forcedOutputTexture;
  61052. }
  61053. else {
  61054. source = this.inputTexture;
  61055. }
  61056. this._effect._bindTexture("textureSampler", source);
  61057. // Parameters
  61058. this._effect.setVector2("scale", this._scaleRatio);
  61059. this.onApplyObservable.notifyObservers(this._effect);
  61060. return this._effect;
  61061. };
  61062. PostProcess.prototype._disposeTextures = function () {
  61063. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  61064. return;
  61065. }
  61066. if (this._textures.length > 0) {
  61067. for (var i = 0; i < this._textures.length; i++) {
  61068. this._engine._releaseTexture(this._textures.data[i]);
  61069. }
  61070. }
  61071. this._textures.dispose();
  61072. };
  61073. /**
  61074. * Disposes the post process.
  61075. * @param camera The camera to dispose the post process on.
  61076. */
  61077. PostProcess.prototype.dispose = function (camera) {
  61078. camera = camera || this._camera;
  61079. this._disposeTextures();
  61080. if (this._scene) {
  61081. var index_1 = this._scene.postProcesses.indexOf(this);
  61082. if (index_1 !== -1) {
  61083. this._scene.postProcesses.splice(index_1, 1);
  61084. }
  61085. }
  61086. else {
  61087. var index_2 = this._engine.postProcesses.indexOf(this);
  61088. if (index_2 !== -1) {
  61089. this._engine.postProcesses.splice(index_2, 1);
  61090. }
  61091. }
  61092. if (!camera) {
  61093. return;
  61094. }
  61095. camera.detachPostProcess(this);
  61096. var index = camera._postProcesses.indexOf(this);
  61097. if (index === 0 && camera._postProcesses.length > 0) {
  61098. var firstPostProcess = this._camera._getFirstPostProcess();
  61099. if (firstPostProcess) {
  61100. firstPostProcess.markTextureDirty();
  61101. }
  61102. }
  61103. this.onActivateObservable.clear();
  61104. this.onAfterRenderObservable.clear();
  61105. this.onApplyObservable.clear();
  61106. this.onBeforeRenderObservable.clear();
  61107. this.onSizeChangedObservable.clear();
  61108. };
  61109. return PostProcess;
  61110. }());
  61111. BABYLON.PostProcess = PostProcess;
  61112. })(BABYLON || (BABYLON = {}));
  61113. //# sourceMappingURL=babylon.postProcess.js.map
  61114. "use strict";
  61115. var BABYLON;
  61116. (function (BABYLON) {
  61117. var PassPostProcess = /** @class */ (function (_super) {
  61118. __extends(PassPostProcess, _super);
  61119. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61120. if (camera === void 0) { camera = null; }
  61121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61122. if (blockCompilation === void 0) { blockCompilation = false; }
  61123. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61124. }
  61125. return PassPostProcess;
  61126. }(BABYLON.PostProcess));
  61127. BABYLON.PassPostProcess = PassPostProcess;
  61128. })(BABYLON || (BABYLON = {}));
  61129. //# sourceMappingURL=babylon.passPostProcess.js.map
  61130. "use strict";
  61131. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61132. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61133. s = arguments[i];
  61134. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61135. t[p] = s[p];
  61136. }
  61137. return t;
  61138. };
  61139. var BABYLON;
  61140. (function (BABYLON) {
  61141. /**
  61142. * Default implementation IShadowGenerator.
  61143. * This is the main object responsible of generating shadows in the framework.
  61144. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61145. */
  61146. var ShadowGenerator = /** @class */ (function () {
  61147. /**
  61148. * Creates a ShadowGenerator object.
  61149. * A ShadowGenerator is the required tool to use the shadows.
  61150. * Each light casting shadows needs to use its own ShadowGenerator.
  61151. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61152. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61153. * @param light The light object generating the shadows.
  61154. * @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.
  61155. */
  61156. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61157. this._bias = 0.00005;
  61158. this._normalBias = 0;
  61159. this._blurBoxOffset = 1;
  61160. this._blurScale = 2;
  61161. this._blurKernel = 1;
  61162. this._useKernelBlur = false;
  61163. this._filter = ShadowGenerator.FILTER_NONE;
  61164. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61165. this._contactHardeningLightSizeUVRatio = 0.1;
  61166. this._darkness = 0;
  61167. this._transparencyShadow = false;
  61168. /**
  61169. * Controls the extent to which the shadows fade out at the edge of the frustum
  61170. * Used only by directionals and spots
  61171. */
  61172. this.frustumEdgeFalloff = 0;
  61173. /**
  61174. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61175. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61176. * It might on the other hand introduce peter panning.
  61177. */
  61178. this.forceBackFacesOnly = false;
  61179. this._lightDirection = BABYLON.Vector3.Zero();
  61180. this._viewMatrix = BABYLON.Matrix.Zero();
  61181. this._projectionMatrix = BABYLON.Matrix.Zero();
  61182. this._transformMatrix = BABYLON.Matrix.Zero();
  61183. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61184. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61185. this._currentFaceIndex = 0;
  61186. this._currentFaceIndexCache = 0;
  61187. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61188. this._mapSize = mapSize;
  61189. this._light = light;
  61190. this._scene = light.getScene();
  61191. light._shadowGenerator = this;
  61192. // Texture type fallback from float to int if not supported.
  61193. var caps = this._scene.getEngine().getCaps();
  61194. if (!useFullFloatFirst) {
  61195. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61196. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61197. }
  61198. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61199. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61200. }
  61201. else {
  61202. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61203. }
  61204. }
  61205. else {
  61206. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61207. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61208. }
  61209. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61210. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61211. }
  61212. else {
  61213. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61214. }
  61215. }
  61216. this._initializeGenerator();
  61217. this._applyFilterValues();
  61218. }
  61219. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61220. /**
  61221. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61222. */
  61223. get: function () {
  61224. return this._bias;
  61225. },
  61226. /**
  61227. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61228. */
  61229. set: function (bias) {
  61230. this._bias = bias;
  61231. },
  61232. enumerable: true,
  61233. configurable: true
  61234. });
  61235. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61236. /**
  61237. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61238. */
  61239. get: function () {
  61240. return this._normalBias;
  61241. },
  61242. /**
  61243. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61244. */
  61245. set: function (normalBias) {
  61246. this._normalBias = normalBias;
  61247. },
  61248. enumerable: true,
  61249. configurable: true
  61250. });
  61251. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61252. /**
  61253. * Gets the blur box offset: offset applied during the blur pass.
  61254. * Only usefull if useKernelBlur = false
  61255. */
  61256. get: function () {
  61257. return this._blurBoxOffset;
  61258. },
  61259. /**
  61260. * Sets the blur box offset: offset applied during the blur pass.
  61261. * Only usefull if useKernelBlur = false
  61262. */
  61263. set: function (value) {
  61264. if (this._blurBoxOffset === value) {
  61265. return;
  61266. }
  61267. this._blurBoxOffset = value;
  61268. this._disposeBlurPostProcesses();
  61269. },
  61270. enumerable: true,
  61271. configurable: true
  61272. });
  61273. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61274. /**
  61275. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61276. * 2 means half of the size.
  61277. */
  61278. get: function () {
  61279. return this._blurScale;
  61280. },
  61281. /**
  61282. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61283. * 2 means half of the size.
  61284. */
  61285. set: function (value) {
  61286. if (this._blurScale === value) {
  61287. return;
  61288. }
  61289. this._blurScale = value;
  61290. this._disposeBlurPostProcesses();
  61291. },
  61292. enumerable: true,
  61293. configurable: true
  61294. });
  61295. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61296. /**
  61297. * Gets the blur kernel: kernel size of the blur pass.
  61298. * Only usefull if useKernelBlur = true
  61299. */
  61300. get: function () {
  61301. return this._blurKernel;
  61302. },
  61303. /**
  61304. * Sets the blur kernel: kernel size of the blur pass.
  61305. * Only usefull if useKernelBlur = true
  61306. */
  61307. set: function (value) {
  61308. if (this._blurKernel === value) {
  61309. return;
  61310. }
  61311. this._blurKernel = value;
  61312. this._disposeBlurPostProcesses();
  61313. },
  61314. enumerable: true,
  61315. configurable: true
  61316. });
  61317. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61318. /**
  61319. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61320. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61321. */
  61322. get: function () {
  61323. return this._useKernelBlur;
  61324. },
  61325. /**
  61326. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61327. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61328. */
  61329. set: function (value) {
  61330. if (this._useKernelBlur === value) {
  61331. return;
  61332. }
  61333. this._useKernelBlur = value;
  61334. this._disposeBlurPostProcesses();
  61335. },
  61336. enumerable: true,
  61337. configurable: true
  61338. });
  61339. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61340. /**
  61341. * Gets the depth scale used in ESM mode.
  61342. */
  61343. get: function () {
  61344. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61345. },
  61346. /**
  61347. * Sets the depth scale used in ESM mode.
  61348. * This can override the scale stored on the light.
  61349. */
  61350. set: function (value) {
  61351. this._depthScale = value;
  61352. },
  61353. enumerable: true,
  61354. configurable: true
  61355. });
  61356. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61357. /**
  61358. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61359. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61360. */
  61361. get: function () {
  61362. return this._filter;
  61363. },
  61364. /**
  61365. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61366. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61367. */
  61368. set: function (value) {
  61369. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61370. if (this._light.needCube()) {
  61371. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61372. this.useExponentialShadowMap = true;
  61373. return;
  61374. }
  61375. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61376. this.useCloseExponentialShadowMap = true;
  61377. return;
  61378. }
  61379. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61380. this.usePoissonSampling = true;
  61381. return;
  61382. }
  61383. }
  61384. // Weblg1 fallback for PCF.
  61385. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61386. if (this._scene.getEngine().webGLVersion === 1) {
  61387. this.usePoissonSampling = true;
  61388. return;
  61389. }
  61390. }
  61391. if (this._filter === value) {
  61392. return;
  61393. }
  61394. this._filter = value;
  61395. this._disposeBlurPostProcesses();
  61396. this._applyFilterValues();
  61397. this._light._markMeshesAsLightDirty();
  61398. },
  61399. enumerable: true,
  61400. configurable: true
  61401. });
  61402. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61403. /**
  61404. * Gets if the current filter is set to Poisson Sampling.
  61405. */
  61406. get: function () {
  61407. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61408. },
  61409. /**
  61410. * Sets the current filter to Poisson Sampling.
  61411. */
  61412. set: function (value) {
  61413. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61414. return;
  61415. }
  61416. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61417. },
  61418. enumerable: true,
  61419. configurable: true
  61420. });
  61421. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61422. /**
  61423. * Gets if the current filter is set to VSM.
  61424. * DEPRECATED. Should use useExponentialShadowMap instead.
  61425. */
  61426. get: function () {
  61427. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61428. return this.useExponentialShadowMap;
  61429. },
  61430. /**
  61431. * Sets the current filter is to VSM.
  61432. * DEPRECATED. Should use useExponentialShadowMap instead.
  61433. */
  61434. set: function (value) {
  61435. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61436. this.useExponentialShadowMap = value;
  61437. },
  61438. enumerable: true,
  61439. configurable: true
  61440. });
  61441. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61442. /**
  61443. * Gets if the current filter is set to blurred VSM.
  61444. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61445. */
  61446. get: function () {
  61447. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61448. return this.useBlurExponentialShadowMap;
  61449. },
  61450. /**
  61451. * Sets the current filter is to blurred VSM.
  61452. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61453. */
  61454. set: function (value) {
  61455. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61456. this.useBlurExponentialShadowMap = value;
  61457. },
  61458. enumerable: true,
  61459. configurable: true
  61460. });
  61461. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61462. /**
  61463. * Gets if the current filter is set to ESM.
  61464. */
  61465. get: function () {
  61466. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61467. },
  61468. /**
  61469. * Sets the current filter is to ESM.
  61470. */
  61471. set: function (value) {
  61472. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61473. return;
  61474. }
  61475. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61476. },
  61477. enumerable: true,
  61478. configurable: true
  61479. });
  61480. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61481. /**
  61482. * Gets if the current filter is set to filtered ESM.
  61483. */
  61484. get: function () {
  61485. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61486. },
  61487. /**
  61488. * Gets if the current filter is set to filtered ESM.
  61489. */
  61490. set: function (value) {
  61491. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61492. return;
  61493. }
  61494. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61495. },
  61496. enumerable: true,
  61497. configurable: true
  61498. });
  61499. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61500. /**
  61501. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61502. * exponential to prevent steep falloff artifacts).
  61503. */
  61504. get: function () {
  61505. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61506. },
  61507. /**
  61508. * Sets the current filter to "close ESM" (using the inverse of the
  61509. * exponential to prevent steep falloff artifacts).
  61510. */
  61511. set: function (value) {
  61512. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61513. return;
  61514. }
  61515. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61516. },
  61517. enumerable: true,
  61518. configurable: true
  61519. });
  61520. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61521. /**
  61522. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61523. * exponential to prevent steep falloff artifacts).
  61524. */
  61525. get: function () {
  61526. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61527. },
  61528. /**
  61529. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61530. * exponential to prevent steep falloff artifacts).
  61531. */
  61532. set: function (value) {
  61533. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61534. return;
  61535. }
  61536. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61537. },
  61538. enumerable: true,
  61539. configurable: true
  61540. });
  61541. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61542. /**
  61543. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61544. */
  61545. get: function () {
  61546. return this.filter === ShadowGenerator.FILTER_PCF;
  61547. },
  61548. /**
  61549. * Sets the current filter to "PCF" (percentage closer filtering).
  61550. */
  61551. set: function (value) {
  61552. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61553. return;
  61554. }
  61555. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61556. },
  61557. enumerable: true,
  61558. configurable: true
  61559. });
  61560. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61561. /**
  61562. * Gets the PCF or PCSS Quality.
  61563. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61564. */
  61565. get: function () {
  61566. return this._filteringQuality;
  61567. },
  61568. /**
  61569. * Sets the PCF or PCSS Quality.
  61570. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61571. */
  61572. set: function (filteringQuality) {
  61573. this._filteringQuality = filteringQuality;
  61574. },
  61575. enumerable: true,
  61576. configurable: true
  61577. });
  61578. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61579. /**
  61580. * Gets if the current filter is set to "PCSS" (contact hardening).
  61581. */
  61582. get: function () {
  61583. return this.filter === ShadowGenerator.FILTER_PCSS;
  61584. },
  61585. /**
  61586. * Sets the current filter to "PCSS" (contact hardening).
  61587. */
  61588. set: function (value) {
  61589. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61590. return;
  61591. }
  61592. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61593. },
  61594. enumerable: true,
  61595. configurable: true
  61596. });
  61597. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61598. /**
  61599. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61600. * Using a ratio helps keeping shape stability independently of the map size.
  61601. *
  61602. * It does not account for the light projection as it was having too much
  61603. * instability during the light setup or during light position changes.
  61604. *
  61605. * Only valid if useContactHardeningShadow is true.
  61606. */
  61607. get: function () {
  61608. return this._contactHardeningLightSizeUVRatio;
  61609. },
  61610. /**
  61611. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61612. * Using a ratio helps keeping shape stability independently of the map size.
  61613. *
  61614. * It does not account for the light projection as it was having too much
  61615. * instability during the light setup or during light position changes.
  61616. *
  61617. * Only valid if useContactHardeningShadow is true.
  61618. */
  61619. set: function (contactHardeningLightSizeUVRatio) {
  61620. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61621. },
  61622. enumerable: true,
  61623. configurable: true
  61624. });
  61625. /**
  61626. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61627. * 0 means strongest and 1 would means no shadow.
  61628. * @returns the darkness.
  61629. */
  61630. ShadowGenerator.prototype.getDarkness = function () {
  61631. return this._darkness;
  61632. };
  61633. /**
  61634. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61635. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61636. * @returns the shadow generator allowing fluent coding.
  61637. */
  61638. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61639. if (darkness >= 1.0)
  61640. this._darkness = 1.0;
  61641. else if (darkness <= 0.0)
  61642. this._darkness = 0.0;
  61643. else
  61644. this._darkness = darkness;
  61645. return this;
  61646. };
  61647. /**
  61648. * Sets the ability to have transparent shadow (boolean).
  61649. * @param transparent True if transparent else False
  61650. * @returns the shadow generator allowing fluent coding
  61651. */
  61652. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61653. this._transparencyShadow = transparent;
  61654. return this;
  61655. };
  61656. /**
  61657. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61658. * @returns The render target texture if present otherwise, null
  61659. */
  61660. ShadowGenerator.prototype.getShadowMap = function () {
  61661. return this._shadowMap;
  61662. };
  61663. /**
  61664. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61665. * @returns The render target texture if the shadow map is present otherwise, null
  61666. */
  61667. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61668. if (this._shadowMap2) {
  61669. return this._shadowMap2;
  61670. }
  61671. return this._shadowMap;
  61672. };
  61673. /**
  61674. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61675. * @param mesh Mesh to add
  61676. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61677. * @returns the Shadow Generator itself
  61678. */
  61679. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61680. if (includeDescendants === void 0) { includeDescendants = true; }
  61681. if (!this._shadowMap) {
  61682. return this;
  61683. }
  61684. if (!this._shadowMap.renderList) {
  61685. this._shadowMap.renderList = [];
  61686. }
  61687. this._shadowMap.renderList.push(mesh);
  61688. if (includeDescendants) {
  61689. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61690. }
  61691. return this;
  61692. var _a;
  61693. };
  61694. /**
  61695. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61696. * @param mesh Mesh to remove
  61697. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61698. * @returns the Shadow Generator itself
  61699. */
  61700. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61701. if (includeDescendants === void 0) { includeDescendants = true; }
  61702. if (!this._shadowMap || !this._shadowMap.renderList) {
  61703. return this;
  61704. }
  61705. var index = this._shadowMap.renderList.indexOf(mesh);
  61706. if (index !== -1) {
  61707. this._shadowMap.renderList.splice(index, 1);
  61708. }
  61709. if (includeDescendants) {
  61710. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61711. var child = _a[_i];
  61712. this.removeShadowCaster(child);
  61713. }
  61714. }
  61715. return this;
  61716. };
  61717. /**
  61718. * Returns the associated light object.
  61719. * @returns the light generating the shadow
  61720. */
  61721. ShadowGenerator.prototype.getLight = function () {
  61722. return this._light;
  61723. };
  61724. ShadowGenerator.prototype._initializeGenerator = function () {
  61725. this._light._markMeshesAsLightDirty();
  61726. this._initializeShadowMap();
  61727. };
  61728. ShadowGenerator.prototype._initializeShadowMap = function () {
  61729. var _this = this;
  61730. // Render target
  61731. var engine = this._scene.getEngine();
  61732. if (engine.webGLVersion > 1) {
  61733. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61734. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61735. }
  61736. else {
  61737. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61738. }
  61739. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61740. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61741. this._shadowMap.anisotropicFilteringLevel = 1;
  61742. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61743. this._shadowMap.renderParticles = false;
  61744. this._shadowMap.ignoreCameraViewport = true;
  61745. // Record Face Index before render.
  61746. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61747. _this._currentFaceIndex = faceIndex;
  61748. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61749. engine.setColorWrite(false);
  61750. }
  61751. });
  61752. // Custom render function.
  61753. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61754. // Blur if required afer render.
  61755. this._shadowMap.onAfterUnbindObservable.add(function () {
  61756. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61757. engine.setColorWrite(true);
  61758. }
  61759. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61760. return;
  61761. }
  61762. var shadowMap = _this.getShadowMapForRendering();
  61763. if (shadowMap) {
  61764. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61765. }
  61766. });
  61767. // Clear according to the chosen filter.
  61768. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61769. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61770. this._shadowMap.onClearObservable.add(function (engine) {
  61771. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61772. engine.clear(clearOne, false, true, false);
  61773. }
  61774. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61775. engine.clear(clearZero, true, true, false);
  61776. }
  61777. else {
  61778. engine.clear(clearOne, true, true, false);
  61779. }
  61780. });
  61781. };
  61782. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61783. var _this = this;
  61784. var engine = this._scene.getEngine();
  61785. var targetSize = this._mapSize / this.blurScale;
  61786. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61787. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61788. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61789. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61790. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61791. }
  61792. if (this.useKernelBlur) {
  61793. 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);
  61794. this._kernelBlurXPostprocess.width = targetSize;
  61795. this._kernelBlurXPostprocess.height = targetSize;
  61796. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61797. effect.setTexture("textureSampler", _this._shadowMap);
  61798. });
  61799. 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);
  61800. this._kernelBlurXPostprocess.autoClear = false;
  61801. this._kernelBlurYPostprocess.autoClear = false;
  61802. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61803. this._kernelBlurXPostprocess.packedFloat = true;
  61804. this._kernelBlurYPostprocess.packedFloat = true;
  61805. }
  61806. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61807. }
  61808. else {
  61809. 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);
  61810. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61811. effect.setFloat2("screenSize", targetSize, targetSize);
  61812. effect.setTexture("textureSampler", _this._shadowMap);
  61813. });
  61814. this._boxBlurPostprocess.autoClear = false;
  61815. this._blurPostProcesses = [this._boxBlurPostprocess];
  61816. }
  61817. };
  61818. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61819. var index;
  61820. var engine = this._scene.getEngine();
  61821. if (depthOnlySubMeshes.length) {
  61822. engine.setColorWrite(false);
  61823. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61824. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61825. }
  61826. engine.setColorWrite(true);
  61827. }
  61828. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61829. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61830. }
  61831. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61832. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61833. }
  61834. if (this._transparencyShadow) {
  61835. for (index = 0; index < transparentSubMeshes.length; index++) {
  61836. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61837. }
  61838. }
  61839. };
  61840. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61841. var _this = this;
  61842. var mesh = subMesh.getRenderingMesh();
  61843. var scene = this._scene;
  61844. var engine = scene.getEngine();
  61845. var material = subMesh.getMaterial();
  61846. if (!material) {
  61847. return;
  61848. }
  61849. // Culling
  61850. engine.setState(material.backFaceCulling);
  61851. // Managing instances
  61852. var batch = mesh._getInstancesRenderList(subMesh._id);
  61853. if (batch.mustReturn) {
  61854. return;
  61855. }
  61856. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61857. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61858. engine.enableEffect(this._effect);
  61859. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61860. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61861. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61862. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61863. this._effect.setVector3("lightData", this._cachedDirection);
  61864. }
  61865. else {
  61866. this._effect.setVector3("lightData", this._cachedPosition);
  61867. }
  61868. if (scene.activeCamera) {
  61869. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61870. }
  61871. // Alpha test
  61872. if (material && material.needAlphaTesting()) {
  61873. var alphaTexture = material.getAlphaTestTexture();
  61874. if (alphaTexture) {
  61875. this._effect.setTexture("diffuseSampler", alphaTexture);
  61876. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61877. }
  61878. }
  61879. // Bones
  61880. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61881. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61882. }
  61883. // Morph targets
  61884. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61885. if (this.forceBackFacesOnly) {
  61886. engine.setState(true, 0, false, true);
  61887. }
  61888. // Draw
  61889. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61890. if (this.forceBackFacesOnly) {
  61891. engine.setState(true, 0, false, false);
  61892. }
  61893. }
  61894. else {
  61895. // Need to reset refresh rate of the shadowMap
  61896. if (this._shadowMap) {
  61897. this._shadowMap.resetRefreshCounter();
  61898. }
  61899. }
  61900. };
  61901. ShadowGenerator.prototype._applyFilterValues = function () {
  61902. if (!this._shadowMap) {
  61903. return;
  61904. }
  61905. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61906. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61907. }
  61908. else {
  61909. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61910. }
  61911. };
  61912. /**
  61913. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61914. * @param onCompiled Callback triggered at the and of the effects compilation
  61915. * @param options Sets of optional options forcing the compilation with different modes
  61916. */
  61917. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61918. var _this = this;
  61919. var localOptions = __assign({ useInstances: false }, options);
  61920. var shadowMap = this.getShadowMap();
  61921. if (!shadowMap) {
  61922. if (onCompiled) {
  61923. onCompiled(this);
  61924. }
  61925. return;
  61926. }
  61927. var renderList = shadowMap.renderList;
  61928. if (!renderList) {
  61929. if (onCompiled) {
  61930. onCompiled(this);
  61931. }
  61932. return;
  61933. }
  61934. var subMeshes = new Array();
  61935. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61936. var mesh = renderList_1[_i];
  61937. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61938. }
  61939. if (subMeshes.length === 0) {
  61940. if (onCompiled) {
  61941. onCompiled(this);
  61942. }
  61943. return;
  61944. }
  61945. var currentIndex = 0;
  61946. var checkReady = function () {
  61947. if (!_this._scene || !_this._scene.getEngine()) {
  61948. return;
  61949. }
  61950. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61951. currentIndex++;
  61952. if (currentIndex >= subMeshes.length) {
  61953. if (onCompiled) {
  61954. onCompiled(_this);
  61955. }
  61956. return;
  61957. }
  61958. }
  61959. setTimeout(checkReady, 16);
  61960. };
  61961. checkReady();
  61962. };
  61963. /**
  61964. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61965. * @param options Sets of optional options forcing the compilation with different modes
  61966. * @returns A promise that resolves when the compilation completes
  61967. */
  61968. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61969. var _this = this;
  61970. return new Promise(function (resolve) {
  61971. _this.forceCompilation(function () {
  61972. resolve();
  61973. }, options);
  61974. });
  61975. };
  61976. /**
  61977. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61978. * @param subMesh The submesh we want to render in the shadow map
  61979. * @param useInstances Defines wether will draw in the map using instances
  61980. * @returns true if ready otherwise, false
  61981. */
  61982. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61983. var defines = [];
  61984. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61985. defines.push("#define FLOAT");
  61986. }
  61987. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61988. defines.push("#define ESM");
  61989. }
  61990. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61991. defines.push("#define DEPTHTEXTURE");
  61992. }
  61993. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61994. var mesh = subMesh.getMesh();
  61995. var material = subMesh.getMaterial();
  61996. // Normal bias.
  61997. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61998. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61999. defines.push("#define NORMAL");
  62000. if (mesh.nonUniformScaling) {
  62001. defines.push("#define NONUNIFORMSCALING");
  62002. }
  62003. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62004. defines.push("#define DIRECTIONINLIGHTDATA");
  62005. }
  62006. }
  62007. // Alpha test
  62008. if (material && material.needAlphaTesting()) {
  62009. var alphaTexture = material.getAlphaTestTexture();
  62010. if (alphaTexture) {
  62011. defines.push("#define ALPHATEST");
  62012. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62013. attribs.push(BABYLON.VertexBuffer.UVKind);
  62014. defines.push("#define UV1");
  62015. }
  62016. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62017. if (alphaTexture.coordinatesIndex === 1) {
  62018. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62019. defines.push("#define UV2");
  62020. }
  62021. }
  62022. }
  62023. }
  62024. // Bones
  62025. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62026. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62027. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62028. if (mesh.numBoneInfluencers > 4) {
  62029. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62030. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62031. }
  62032. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62033. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62034. }
  62035. else {
  62036. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62037. }
  62038. // Morph targets
  62039. var manager = mesh.morphTargetManager;
  62040. var morphInfluencers = 0;
  62041. if (manager) {
  62042. if (manager.numInfluencers > 0) {
  62043. defines.push("#define MORPHTARGETS");
  62044. morphInfluencers = manager.numInfluencers;
  62045. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  62046. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  62047. }
  62048. }
  62049. // Instances
  62050. if (useInstances) {
  62051. defines.push("#define INSTANCES");
  62052. attribs.push("world0");
  62053. attribs.push("world1");
  62054. attribs.push("world2");
  62055. attribs.push("world3");
  62056. }
  62057. // Get correct effect
  62058. var join = defines.join("\n");
  62059. if (this._cachedDefines !== join) {
  62060. this._cachedDefines = join;
  62061. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  62062. }
  62063. if (!this._effect.isReady()) {
  62064. return false;
  62065. }
  62066. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62067. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  62068. this._initializeBlurRTTAndPostProcesses();
  62069. }
  62070. }
  62071. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  62072. return false;
  62073. }
  62074. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  62075. return false;
  62076. }
  62077. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  62078. return false;
  62079. }
  62080. return true;
  62081. };
  62082. /**
  62083. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  62084. * @param defines Defines of the material we want to update
  62085. * @param lightIndex Index of the light in the enabled light list of the material
  62086. */
  62087. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  62088. var scene = this._scene;
  62089. var light = this._light;
  62090. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62091. return;
  62092. }
  62093. defines["SHADOW" + lightIndex] = true;
  62094. if (this.useContactHardeningShadow) {
  62095. defines["SHADOWPCSS" + lightIndex] = true;
  62096. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62097. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62098. }
  62099. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62100. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62101. }
  62102. // else default to high.
  62103. }
  62104. if (this.usePercentageCloserFiltering) {
  62105. defines["SHADOWPCF" + lightIndex] = true;
  62106. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62107. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62108. }
  62109. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62110. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62111. }
  62112. // else default to high.
  62113. }
  62114. else if (this.usePoissonSampling) {
  62115. defines["SHADOWPOISSON" + lightIndex] = true;
  62116. }
  62117. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62118. defines["SHADOWESM" + lightIndex] = true;
  62119. }
  62120. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62121. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62122. }
  62123. if (light.needCube()) {
  62124. defines["SHADOWCUBE" + lightIndex] = true;
  62125. }
  62126. };
  62127. /**
  62128. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62129. * defined in the generator but impacting the effect).
  62130. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62131. * @param effect The effect we are binfing the information for
  62132. */
  62133. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62134. var light = this._light;
  62135. var scene = this._scene;
  62136. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62137. return;
  62138. }
  62139. var camera = scene.activeCamera;
  62140. if (!camera) {
  62141. return;
  62142. }
  62143. var shadowMap = this.getShadowMap();
  62144. if (!shadowMap) {
  62145. return;
  62146. }
  62147. if (!light.needCube()) {
  62148. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62149. }
  62150. // Only PCF uses depth stencil texture.
  62151. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62152. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62153. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62154. }
  62155. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62156. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62157. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62158. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62159. }
  62160. else {
  62161. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62162. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62163. }
  62164. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62165. };
  62166. /**
  62167. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62168. * (eq to shadow prjection matrix * light transform matrix)
  62169. * @returns The transform matrix used to create the shadow map
  62170. */
  62171. ShadowGenerator.prototype.getTransformMatrix = function () {
  62172. var scene = this._scene;
  62173. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62174. return this._transformMatrix;
  62175. }
  62176. this._currentRenderID = scene.getRenderId();
  62177. this._currentFaceIndexCache = this._currentFaceIndex;
  62178. var lightPosition = this._light.position;
  62179. if (this._light.computeTransformedInformation()) {
  62180. lightPosition = this._light.transformedPosition;
  62181. }
  62182. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62183. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62184. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62185. }
  62186. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62187. this._cachedPosition.copyFrom(lightPosition);
  62188. this._cachedDirection.copyFrom(this._lightDirection);
  62189. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62190. var shadowMap = this.getShadowMap();
  62191. if (shadowMap) {
  62192. var renderList = shadowMap.renderList;
  62193. if (renderList) {
  62194. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62195. }
  62196. }
  62197. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62198. }
  62199. return this._transformMatrix;
  62200. };
  62201. /**
  62202. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62203. * Cube and 2D textures for instance.
  62204. */
  62205. ShadowGenerator.prototype.recreateShadowMap = function () {
  62206. var shadowMap = this._shadowMap;
  62207. if (!shadowMap) {
  62208. return;
  62209. }
  62210. // Track render list.
  62211. var renderList = shadowMap.renderList;
  62212. // Clean up existing data.
  62213. this._disposeRTTandPostProcesses();
  62214. // Reinitializes.
  62215. this._initializeGenerator();
  62216. // Reaffect the filter to ensure a correct fallback if necessary.
  62217. this.filter = this.filter;
  62218. // Reaffect the filter.
  62219. this._applyFilterValues();
  62220. // Reaffect Render List.
  62221. this._shadowMap.renderList = renderList;
  62222. };
  62223. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62224. if (this._shadowMap2) {
  62225. this._shadowMap2.dispose();
  62226. this._shadowMap2 = null;
  62227. }
  62228. if (this._boxBlurPostprocess) {
  62229. this._boxBlurPostprocess.dispose();
  62230. this._boxBlurPostprocess = null;
  62231. }
  62232. if (this._kernelBlurXPostprocess) {
  62233. this._kernelBlurXPostprocess.dispose();
  62234. this._kernelBlurXPostprocess = null;
  62235. }
  62236. if (this._kernelBlurYPostprocess) {
  62237. this._kernelBlurYPostprocess.dispose();
  62238. this._kernelBlurYPostprocess = null;
  62239. }
  62240. this._blurPostProcesses = [];
  62241. };
  62242. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62243. if (this._shadowMap) {
  62244. this._shadowMap.dispose();
  62245. this._shadowMap = null;
  62246. }
  62247. this._disposeBlurPostProcesses();
  62248. };
  62249. /**
  62250. * Disposes the ShadowGenerator.
  62251. * Returns nothing.
  62252. */
  62253. ShadowGenerator.prototype.dispose = function () {
  62254. this._disposeRTTandPostProcesses();
  62255. if (this._light) {
  62256. this._light._shadowGenerator = null;
  62257. this._light._markMeshesAsLightDirty();
  62258. }
  62259. };
  62260. /**
  62261. * Serializes the shadow generator setup to a json object.
  62262. * @returns The serialized JSON object
  62263. */
  62264. ShadowGenerator.prototype.serialize = function () {
  62265. var serializationObject = {};
  62266. var shadowMap = this.getShadowMap();
  62267. if (!shadowMap) {
  62268. return serializationObject;
  62269. }
  62270. serializationObject.lightId = this._light.id;
  62271. serializationObject.mapSize = shadowMap.getRenderSize();
  62272. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62273. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62274. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62275. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62276. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62277. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62278. serializationObject.depthScale = this.depthScale;
  62279. serializationObject.darkness = this.getDarkness();
  62280. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62281. serializationObject.blurKernel = this.blurKernel;
  62282. serializationObject.blurScale = this.blurScale;
  62283. serializationObject.useKernelBlur = this.useKernelBlur;
  62284. serializationObject.transparencyShadow = this._transparencyShadow;
  62285. serializationObject.bias = this.bias;
  62286. serializationObject.normalBias = this.normalBias;
  62287. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62288. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62289. serializationObject.filteringQuality = this.filteringQuality;
  62290. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62291. serializationObject.renderList = [];
  62292. if (shadowMap.renderList) {
  62293. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62294. var mesh = shadowMap.renderList[meshIndex];
  62295. serializationObject.renderList.push(mesh.id);
  62296. }
  62297. }
  62298. return serializationObject;
  62299. };
  62300. /**
  62301. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62302. * @param parsedShadowGenerator The JSON object to parse
  62303. * @param scene The scene to create the shadow map for
  62304. * @returns The parsed shadow generator
  62305. */
  62306. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62307. //casting to point light, as light is missing the position attr and typescript complains.
  62308. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62309. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62310. var shadowMap = shadowGenerator.getShadowMap();
  62311. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62312. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62313. meshes.forEach(function (mesh) {
  62314. if (!shadowMap) {
  62315. return;
  62316. }
  62317. if (!shadowMap.renderList) {
  62318. shadowMap.renderList = [];
  62319. }
  62320. shadowMap.renderList.push(mesh);
  62321. });
  62322. }
  62323. if (parsedShadowGenerator.usePoissonSampling) {
  62324. shadowGenerator.usePoissonSampling = true;
  62325. }
  62326. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62327. shadowGenerator.useExponentialShadowMap = true;
  62328. }
  62329. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62330. shadowGenerator.useBlurExponentialShadowMap = true;
  62331. }
  62332. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62333. shadowGenerator.useCloseExponentialShadowMap = true;
  62334. }
  62335. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62336. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62337. }
  62338. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62339. shadowGenerator.usePercentageCloserFiltering = true;
  62340. }
  62341. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62342. shadowGenerator.useContactHardeningShadow = true;
  62343. }
  62344. if (parsedShadowGenerator.filteringQuality) {
  62345. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62346. }
  62347. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62348. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62349. }
  62350. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62351. shadowGenerator.useExponentialShadowMap = true;
  62352. }
  62353. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62354. shadowGenerator.useBlurExponentialShadowMap = true;
  62355. }
  62356. if (parsedShadowGenerator.depthScale) {
  62357. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62358. }
  62359. if (parsedShadowGenerator.blurScale) {
  62360. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62361. }
  62362. if (parsedShadowGenerator.blurBoxOffset) {
  62363. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62364. }
  62365. if (parsedShadowGenerator.useKernelBlur) {
  62366. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62367. }
  62368. if (parsedShadowGenerator.blurKernel) {
  62369. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62370. }
  62371. if (parsedShadowGenerator.bias !== undefined) {
  62372. shadowGenerator.bias = parsedShadowGenerator.bias;
  62373. }
  62374. if (parsedShadowGenerator.normalBias !== undefined) {
  62375. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62376. }
  62377. if (parsedShadowGenerator.darkness) {
  62378. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62379. }
  62380. if (parsedShadowGenerator.transparencyShadow) {
  62381. shadowGenerator.setTransparencyShadow(true);
  62382. }
  62383. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62384. return shadowGenerator;
  62385. };
  62386. /**
  62387. * Shadow generator mode None: no filtering applied.
  62388. */
  62389. ShadowGenerator.FILTER_NONE = 0;
  62390. /**
  62391. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62392. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62393. */
  62394. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62395. /**
  62396. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62397. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62398. */
  62399. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62400. /**
  62401. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62402. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62403. */
  62404. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62405. /**
  62406. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62407. * edge artifacts on steep falloff.
  62408. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62409. */
  62410. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62411. /**
  62412. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62413. * edge artifacts on steep falloff.
  62414. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62415. */
  62416. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62417. /**
  62418. * Shadow generator mode PCF: Percentage Closer Filtering
  62419. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62420. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62421. */
  62422. ShadowGenerator.FILTER_PCF = 6;
  62423. /**
  62424. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62425. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62426. * Contact Hardening
  62427. */
  62428. ShadowGenerator.FILTER_PCSS = 7;
  62429. /**
  62430. * Reserved for PCF and PCSS
  62431. * Highest Quality.
  62432. *
  62433. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62434. *
  62435. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62436. */
  62437. ShadowGenerator.QUALITY_HIGH = 0;
  62438. /**
  62439. * Reserved for PCF and PCSS
  62440. * Good tradeoff for quality/perf cross devices
  62441. *
  62442. * Execute PCF on a 3*3 kernel.
  62443. *
  62444. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62445. */
  62446. ShadowGenerator.QUALITY_MEDIUM = 1;
  62447. /**
  62448. * Reserved for PCF and PCSS
  62449. * The lowest quality but the fastest.
  62450. *
  62451. * Execute PCF on a 1*1 kernel.
  62452. *
  62453. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62454. */
  62455. ShadowGenerator.QUALITY_LOW = 2;
  62456. return ShadowGenerator;
  62457. }());
  62458. BABYLON.ShadowGenerator = ShadowGenerator;
  62459. })(BABYLON || (BABYLON = {}));
  62460. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62461. "use strict";
  62462. var BABYLON;
  62463. (function (BABYLON) {
  62464. var DefaultLoadingScreen = /** @class */ (function () {
  62465. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62466. if (_loadingText === void 0) { _loadingText = ""; }
  62467. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62468. var _this = this;
  62469. this._renderingCanvas = _renderingCanvas;
  62470. this._loadingText = _loadingText;
  62471. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62472. // Resize
  62473. this._resizeLoadingUI = function () {
  62474. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62475. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62476. if (!_this._loadingDiv) {
  62477. return;
  62478. }
  62479. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62480. _this._loadingDiv.style.left = canvasRect.left + "px";
  62481. _this._loadingDiv.style.top = canvasRect.top + "px";
  62482. _this._loadingDiv.style.width = canvasRect.width + "px";
  62483. _this._loadingDiv.style.height = canvasRect.height + "px";
  62484. };
  62485. }
  62486. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62487. if (this._loadingDiv) {
  62488. // Do not add a loading screen if there is already one
  62489. return;
  62490. }
  62491. this._loadingDiv = document.createElement("div");
  62492. this._loadingDiv.id = "babylonjsLoadingDiv";
  62493. this._loadingDiv.style.opacity = "0";
  62494. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62495. this._loadingDiv.style.pointerEvents = "none";
  62496. // Loading text
  62497. this._loadingTextDiv = document.createElement("div");
  62498. this._loadingTextDiv.style.position = "absolute";
  62499. this._loadingTextDiv.style.left = "0";
  62500. this._loadingTextDiv.style.top = "50%";
  62501. this._loadingTextDiv.style.marginTop = "80px";
  62502. this._loadingTextDiv.style.width = "100%";
  62503. this._loadingTextDiv.style.height = "20px";
  62504. this._loadingTextDiv.style.fontFamily = "Arial";
  62505. this._loadingTextDiv.style.fontSize = "14px";
  62506. this._loadingTextDiv.style.color = "white";
  62507. this._loadingTextDiv.style.textAlign = "center";
  62508. this._loadingTextDiv.innerHTML = "Loading";
  62509. this._loadingDiv.appendChild(this._loadingTextDiv);
  62510. //set the predefined text
  62511. this._loadingTextDiv.innerHTML = this._loadingText;
  62512. // Generating keyframes
  62513. var style = document.createElement('style');
  62514. style.type = 'text/css';
  62515. 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 }";
  62516. style.innerHTML = keyFrames;
  62517. document.getElementsByTagName('head')[0].appendChild(style);
  62518. // Loading img
  62519. var imgBack = new Image();
  62520. 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";
  62521. imgBack.style.position = "absolute";
  62522. imgBack.style.left = "50%";
  62523. imgBack.style.top = "50%";
  62524. imgBack.style.marginLeft = "-60px";
  62525. imgBack.style.marginTop = "-60px";
  62526. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62527. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62528. imgBack.style.transformOrigin = "50% 50%";
  62529. imgBack.style.webkitTransformOrigin = "50% 50%";
  62530. this._loadingDiv.appendChild(imgBack);
  62531. this._resizeLoadingUI();
  62532. window.addEventListener("resize", this._resizeLoadingUI);
  62533. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62534. document.body.appendChild(this._loadingDiv);
  62535. this._loadingDiv.style.opacity = "1";
  62536. };
  62537. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62538. var _this = this;
  62539. if (!this._loadingDiv) {
  62540. return;
  62541. }
  62542. var onTransitionEnd = function () {
  62543. if (!_this._loadingDiv) {
  62544. return;
  62545. }
  62546. document.body.removeChild(_this._loadingDiv);
  62547. window.removeEventListener("resize", _this._resizeLoadingUI);
  62548. _this._loadingDiv = null;
  62549. };
  62550. this._loadingDiv.style.opacity = "0";
  62551. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62552. };
  62553. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62554. set: function (text) {
  62555. this._loadingText = text;
  62556. if (this._loadingTextDiv) {
  62557. this._loadingTextDiv.innerHTML = this._loadingText;
  62558. }
  62559. },
  62560. enumerable: true,
  62561. configurable: true
  62562. });
  62563. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62564. get: function () {
  62565. return this._loadingDivBackgroundColor;
  62566. },
  62567. set: function (color) {
  62568. this._loadingDivBackgroundColor = color;
  62569. if (!this._loadingDiv) {
  62570. return;
  62571. }
  62572. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62573. },
  62574. enumerable: true,
  62575. configurable: true
  62576. });
  62577. return DefaultLoadingScreen;
  62578. }());
  62579. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62580. })(BABYLON || (BABYLON = {}));
  62581. //# sourceMappingURL=babylon.loadingScreen.js.map
  62582. "use strict";
  62583. var BABYLON;
  62584. (function (BABYLON) {
  62585. var SceneLoaderProgressEvent = /** @class */ (function () {
  62586. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62587. this.lengthComputable = lengthComputable;
  62588. this.loaded = loaded;
  62589. this.total = total;
  62590. }
  62591. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62592. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62593. };
  62594. return SceneLoaderProgressEvent;
  62595. }());
  62596. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62597. var SceneLoader = /** @class */ (function () {
  62598. function SceneLoader() {
  62599. }
  62600. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62601. get: function () {
  62602. return 0;
  62603. },
  62604. enumerable: true,
  62605. configurable: true
  62606. });
  62607. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62608. get: function () {
  62609. return 1;
  62610. },
  62611. enumerable: true,
  62612. configurable: true
  62613. });
  62614. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62615. get: function () {
  62616. return 2;
  62617. },
  62618. enumerable: true,
  62619. configurable: true
  62620. });
  62621. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62622. get: function () {
  62623. return 3;
  62624. },
  62625. enumerable: true,
  62626. configurable: true
  62627. });
  62628. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62629. get: function () {
  62630. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62631. },
  62632. set: function (value) {
  62633. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62634. },
  62635. enumerable: true,
  62636. configurable: true
  62637. });
  62638. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62639. get: function () {
  62640. return SceneLoader._ShowLoadingScreen;
  62641. },
  62642. set: function (value) {
  62643. SceneLoader._ShowLoadingScreen = value;
  62644. },
  62645. enumerable: true,
  62646. configurable: true
  62647. });
  62648. Object.defineProperty(SceneLoader, "loggingLevel", {
  62649. get: function () {
  62650. return SceneLoader._loggingLevel;
  62651. },
  62652. set: function (value) {
  62653. SceneLoader._loggingLevel = value;
  62654. },
  62655. enumerable: true,
  62656. configurable: true
  62657. });
  62658. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62659. get: function () {
  62660. return SceneLoader._CleanBoneMatrixWeights;
  62661. },
  62662. set: function (value) {
  62663. SceneLoader._CleanBoneMatrixWeights = value;
  62664. },
  62665. enumerable: true,
  62666. configurable: true
  62667. });
  62668. SceneLoader._getDefaultPlugin = function () {
  62669. return SceneLoader._registeredPlugins[".babylon"];
  62670. };
  62671. SceneLoader._getPluginForExtension = function (extension) {
  62672. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62673. if (registeredPlugin) {
  62674. return registeredPlugin;
  62675. }
  62676. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62677. return SceneLoader._getDefaultPlugin();
  62678. };
  62679. SceneLoader._getPluginForDirectLoad = function (data) {
  62680. for (var extension in SceneLoader._registeredPlugins) {
  62681. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62682. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62683. return SceneLoader._registeredPlugins[extension];
  62684. }
  62685. }
  62686. return SceneLoader._getDefaultPlugin();
  62687. };
  62688. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62689. if (sceneFilename.name) {
  62690. sceneFilename = sceneFilename.name;
  62691. }
  62692. var queryStringPosition = sceneFilename.indexOf("?");
  62693. if (queryStringPosition !== -1) {
  62694. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62695. }
  62696. var dotPosition = sceneFilename.lastIndexOf(".");
  62697. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62698. return SceneLoader._getPluginForExtension(extension);
  62699. };
  62700. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62701. SceneLoader._getDirectLoad = function (sceneFilename) {
  62702. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62703. return sceneFilename.substr(5);
  62704. }
  62705. return null;
  62706. };
  62707. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62708. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62709. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62710. var plugin;
  62711. if (registeredPlugin.plugin.createPlugin) {
  62712. plugin = registeredPlugin.plugin.createPlugin();
  62713. }
  62714. else {
  62715. plugin = registeredPlugin.plugin;
  62716. }
  62717. var useArrayBuffer = registeredPlugin.isBinary;
  62718. var database;
  62719. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62720. var dataCallback = function (data, responseURL) {
  62721. if (scene.isDisposed) {
  62722. onError("Scene has been disposed");
  62723. return;
  62724. }
  62725. scene.database = database;
  62726. onSuccess(plugin, data, responseURL);
  62727. };
  62728. var request = null;
  62729. var pluginDisposed = false;
  62730. var onDisposeObservable = plugin.onDisposeObservable;
  62731. if (onDisposeObservable) {
  62732. onDisposeObservable.add(function () {
  62733. pluginDisposed = true;
  62734. if (request) {
  62735. request.abort();
  62736. request = null;
  62737. }
  62738. onDispose();
  62739. });
  62740. }
  62741. var manifestChecked = function () {
  62742. if (pluginDisposed) {
  62743. return;
  62744. }
  62745. var url = rootUrl + sceneFilename;
  62746. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62747. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62748. } : undefined, database, useArrayBuffer, function (request, exception) {
  62749. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62750. });
  62751. };
  62752. if (directLoad) {
  62753. dataCallback(directLoad);
  62754. return plugin;
  62755. }
  62756. if (rootUrl.indexOf("file:") === -1) {
  62757. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  62758. if (canUseOfflineSupport) {
  62759. // Also check for exceptions
  62760. var exceptionFound = false;
  62761. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  62762. var regex = _a[_i];
  62763. if (regex.test(rootUrl + sceneFilename)) {
  62764. exceptionFound = true;
  62765. break;
  62766. }
  62767. }
  62768. canUseOfflineSupport = !exceptionFound;
  62769. }
  62770. if (canUseOfflineSupport) {
  62771. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62772. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62773. }
  62774. else {
  62775. manifestChecked();
  62776. }
  62777. }
  62778. else {
  62779. var fileOrString = sceneFilename;
  62780. if (fileOrString.name) {
  62781. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62782. }
  62783. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62784. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62785. }
  62786. else {
  62787. onError("Unable to find file named " + sceneFilename);
  62788. }
  62789. }
  62790. return plugin;
  62791. };
  62792. // Public functions
  62793. SceneLoader.GetPluginForExtension = function (extension) {
  62794. return SceneLoader._getPluginForExtension(extension).plugin;
  62795. };
  62796. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62797. return !!SceneLoader._registeredPlugins[extension];
  62798. };
  62799. SceneLoader.RegisterPlugin = function (plugin) {
  62800. if (typeof plugin.extensions === "string") {
  62801. var extension = plugin.extensions;
  62802. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62803. plugin: plugin,
  62804. isBinary: false
  62805. };
  62806. }
  62807. else {
  62808. var extensions = plugin.extensions;
  62809. Object.keys(extensions).forEach(function (extension) {
  62810. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62811. plugin: plugin,
  62812. isBinary: extensions[extension].isBinary
  62813. };
  62814. });
  62815. }
  62816. };
  62817. /**
  62818. * Import meshes into a scene
  62819. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62820. * @param rootUrl a string that defines the root url for scene and resources
  62821. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62822. * @param scene the instance of BABYLON.Scene to append to
  62823. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62824. * @param onProgress a callback with a progress event for each file being loaded
  62825. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62826. * @param pluginExtension the extension used to determine the plugin
  62827. * @returns The loaded plugin
  62828. */
  62829. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62830. if (onSuccess === void 0) { onSuccess = null; }
  62831. if (onProgress === void 0) { onProgress = null; }
  62832. if (onError === void 0) { onError = null; }
  62833. if (pluginExtension === void 0) { pluginExtension = null; }
  62834. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62835. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62836. return null;
  62837. }
  62838. var loadingToken = {};
  62839. scene._addPendingData(loadingToken);
  62840. var disposeHandler = function () {
  62841. scene._removePendingData(loadingToken);
  62842. };
  62843. var errorHandler = function (message, exception) {
  62844. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62845. if (onError) {
  62846. onError(scene, errorMessage, exception);
  62847. }
  62848. else {
  62849. BABYLON.Tools.Error(errorMessage);
  62850. // should the exception be thrown?
  62851. }
  62852. disposeHandler();
  62853. };
  62854. var progressHandler = onProgress ? function (event) {
  62855. try {
  62856. onProgress(event);
  62857. }
  62858. catch (e) {
  62859. errorHandler("Error in onProgress callback", e);
  62860. }
  62861. } : undefined;
  62862. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  62863. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62864. if (onSuccess) {
  62865. try {
  62866. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  62867. }
  62868. catch (e) {
  62869. errorHandler("Error in onSuccess callback", e);
  62870. }
  62871. }
  62872. scene._removePendingData(loadingToken);
  62873. };
  62874. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62875. if (plugin.rewriteRootURL) {
  62876. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62877. }
  62878. if (sceneFilename === "") {
  62879. if (sceneFilename === "") {
  62880. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62881. }
  62882. }
  62883. if (plugin.importMesh) {
  62884. var syncedPlugin = plugin;
  62885. var meshes = new Array();
  62886. var particleSystems = new Array();
  62887. var skeletons = new Array();
  62888. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62889. return;
  62890. }
  62891. scene.loadingPluginName = plugin.name;
  62892. successHandler(meshes, particleSystems, skeletons, []);
  62893. }
  62894. else {
  62895. var asyncedPlugin = plugin;
  62896. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62897. scene.loadingPluginName = plugin.name;
  62898. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  62899. }).catch(function (error) {
  62900. errorHandler(error.message, error);
  62901. });
  62902. }
  62903. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62904. };
  62905. /**
  62906. * Import meshes into a scene
  62907. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62908. * @param rootUrl a string that defines the root url for scene and resources
  62909. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62910. * @param scene the instance of BABYLON.Scene to append to
  62911. * @param onProgress a callback with a progress event for each file being loaded
  62912. * @param pluginExtension the extension used to determine the plugin
  62913. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  62914. */
  62915. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62916. if (onProgress === void 0) { onProgress = null; }
  62917. if (pluginExtension === void 0) { pluginExtension = null; }
  62918. return new Promise(function (resolve, reject) {
  62919. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  62920. resolve({
  62921. meshes: meshes,
  62922. particleSystems: particleSystems,
  62923. skeletons: skeletons,
  62924. animationGroups: animationGroups
  62925. });
  62926. }, onProgress, function (scene, message, exception) {
  62927. reject(exception || new Error(message));
  62928. });
  62929. });
  62930. };
  62931. /**
  62932. * Load a scene
  62933. * @param rootUrl a string that defines the root url for scene and resources
  62934. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62935. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62936. * @param onSuccess a callback with the scene when import succeeds
  62937. * @param onProgress a callback with a progress event for each file being loaded
  62938. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62939. * @param pluginExtension the extension used to determine the plugin
  62940. * @returns The loaded plugin
  62941. */
  62942. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62943. if (onSuccess === void 0) { onSuccess = null; }
  62944. if (onProgress === void 0) { onProgress = null; }
  62945. if (onError === void 0) { onError = null; }
  62946. if (pluginExtension === void 0) { pluginExtension = null; }
  62947. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62948. };
  62949. /**
  62950. * Load a scene
  62951. * @param rootUrl a string that defines the root url for scene and resources
  62952. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62953. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62954. * @param onProgress a callback with a progress event for each file being loaded
  62955. * @param pluginExtension the extension used to determine the plugin
  62956. * @returns The loaded scene
  62957. */
  62958. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62959. if (onProgress === void 0) { onProgress = null; }
  62960. if (pluginExtension === void 0) { pluginExtension = null; }
  62961. return new Promise(function (resolve, reject) {
  62962. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62963. resolve(scene);
  62964. }, onProgress, function (scene, message, exception) {
  62965. reject(exception || new Error(message));
  62966. }, pluginExtension);
  62967. });
  62968. };
  62969. /**
  62970. * Append a scene
  62971. * @param rootUrl a string that defines the root url for scene and resources
  62972. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62973. * @param scene is the instance of BABYLON.Scene to append to
  62974. * @param onSuccess a callback with the scene when import succeeds
  62975. * @param onProgress a callback with a progress event for each file being loaded
  62976. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62977. * @param pluginExtension the extension used to determine the plugin
  62978. * @returns The loaded plugin
  62979. */
  62980. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62981. if (onSuccess === void 0) { onSuccess = null; }
  62982. if (onProgress === void 0) { onProgress = null; }
  62983. if (onError === void 0) { onError = null; }
  62984. if (pluginExtension === void 0) { pluginExtension = null; }
  62985. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62986. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62987. return null;
  62988. }
  62989. if (SceneLoader.ShowLoadingScreen) {
  62990. scene.getEngine().displayLoadingUI();
  62991. }
  62992. var loadingToken = {};
  62993. scene._addPendingData(loadingToken);
  62994. var disposeHandler = function () {
  62995. scene._removePendingData(loadingToken);
  62996. scene.getEngine().hideLoadingUI();
  62997. };
  62998. var errorHandler = function (message, exception) {
  62999. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63000. if (onError) {
  63001. onError(scene, errorMessage, exception);
  63002. }
  63003. else {
  63004. BABYLON.Tools.Error(errorMessage);
  63005. // should the exception be thrown?
  63006. }
  63007. disposeHandler();
  63008. };
  63009. var progressHandler = onProgress ? function (event) {
  63010. try {
  63011. onProgress(event);
  63012. }
  63013. catch (e) {
  63014. errorHandler("Error in onProgress callback", e);
  63015. }
  63016. } : undefined;
  63017. var successHandler = function () {
  63018. if (onSuccess) {
  63019. try {
  63020. onSuccess(scene);
  63021. }
  63022. catch (e) {
  63023. errorHandler("Error in onSuccess callback", e);
  63024. }
  63025. }
  63026. scene._removePendingData(loadingToken);
  63027. };
  63028. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63029. if (sceneFilename === "") {
  63030. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63031. }
  63032. if (plugin.load) {
  63033. var syncedPlugin = plugin;
  63034. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  63035. return;
  63036. }
  63037. scene.loadingPluginName = plugin.name;
  63038. successHandler();
  63039. }
  63040. else {
  63041. var asyncedPlugin = plugin;
  63042. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  63043. scene.loadingPluginName = plugin.name;
  63044. successHandler();
  63045. }).catch(function (error) {
  63046. errorHandler(error.message, error);
  63047. });
  63048. }
  63049. if (SceneLoader.ShowLoadingScreen) {
  63050. scene.executeWhenReady(function () {
  63051. scene.getEngine().hideLoadingUI();
  63052. });
  63053. }
  63054. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63055. };
  63056. /**
  63057. * Append a scene
  63058. * @param rootUrl a string that defines the root url for scene and resources
  63059. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63060. * @param scene is the instance of BABYLON.Scene to append to
  63061. * @param onProgress a callback with a progress event for each file being loaded
  63062. * @param pluginExtension the extension used to determine the plugin
  63063. * @returns The given scene
  63064. */
  63065. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63066. if (onProgress === void 0) { onProgress = null; }
  63067. if (pluginExtension === void 0) { pluginExtension = null; }
  63068. return new Promise(function (resolve, reject) {
  63069. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  63070. resolve(scene);
  63071. }, onProgress, function (scene, message, exception) {
  63072. reject(exception || new Error(message));
  63073. }, pluginExtension);
  63074. });
  63075. };
  63076. /**
  63077. * Load a scene into an asset container
  63078. * @param rootUrl a string that defines the root url for scene and resources
  63079. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63080. * @param scene is the instance of BABYLON.Scene to append to
  63081. * @param onSuccess a callback with the scene when import succeeds
  63082. * @param onProgress a callback with a progress event for each file being loaded
  63083. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63084. * @param pluginExtension the extension used to determine the plugin
  63085. * @returns The loaded plugin
  63086. */
  63087. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63088. if (onSuccess === void 0) { onSuccess = null; }
  63089. if (onProgress === void 0) { onProgress = null; }
  63090. if (onError === void 0) { onError = null; }
  63091. if (pluginExtension === void 0) { pluginExtension = null; }
  63092. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63093. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63094. return null;
  63095. }
  63096. var loadingToken = {};
  63097. scene._addPendingData(loadingToken);
  63098. var disposeHandler = function () {
  63099. scene._removePendingData(loadingToken);
  63100. };
  63101. var errorHandler = function (message, exception) {
  63102. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63103. if (onError) {
  63104. onError(scene, errorMessage, exception);
  63105. }
  63106. else {
  63107. BABYLON.Tools.Error(errorMessage);
  63108. // should the exception be thrown?
  63109. }
  63110. disposeHandler();
  63111. };
  63112. var progressHandler = onProgress ? function (event) {
  63113. try {
  63114. onProgress(event);
  63115. }
  63116. catch (e) {
  63117. errorHandler("Error in onProgress callback", e);
  63118. }
  63119. } : undefined;
  63120. var successHandler = function (assets) {
  63121. if (onSuccess) {
  63122. try {
  63123. onSuccess(assets);
  63124. }
  63125. catch (e) {
  63126. errorHandler("Error in onSuccess callback", e);
  63127. }
  63128. }
  63129. scene._removePendingData(loadingToken);
  63130. };
  63131. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63132. if (plugin.loadAssetContainer) {
  63133. var syncedPlugin = plugin;
  63134. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63135. if (!assetContainer) {
  63136. return;
  63137. }
  63138. scene.loadingPluginName = plugin.name;
  63139. successHandler(assetContainer);
  63140. }
  63141. else if (plugin.loadAssetContainerAsync) {
  63142. var asyncedPlugin = plugin;
  63143. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63144. scene.loadingPluginName = plugin.name;
  63145. successHandler(assetContainer);
  63146. }).catch(function (error) {
  63147. errorHandler(error.message, error);
  63148. });
  63149. }
  63150. else {
  63151. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63152. }
  63153. if (SceneLoader.ShowLoadingScreen) {
  63154. scene.executeWhenReady(function () {
  63155. scene.getEngine().hideLoadingUI();
  63156. });
  63157. }
  63158. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63159. };
  63160. /**
  63161. * Load a scene into an asset container
  63162. * @param rootUrl a string that defines the root url for scene and resources
  63163. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63164. * @param scene is the instance of BABYLON.Scene to append to
  63165. * @param onProgress a callback with a progress event for each file being loaded
  63166. * @param pluginExtension the extension used to determine the plugin
  63167. * @returns The loaded asset container
  63168. */
  63169. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63170. if (onProgress === void 0) { onProgress = null; }
  63171. if (pluginExtension === void 0) { pluginExtension = null; }
  63172. return new Promise(function (resolve, reject) {
  63173. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63174. resolve(assetContainer);
  63175. }, onProgress, function (scene, message, exception) {
  63176. reject(exception || new Error(message));
  63177. }, pluginExtension);
  63178. });
  63179. };
  63180. // Flags
  63181. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63182. SceneLoader._ShowLoadingScreen = true;
  63183. SceneLoader._CleanBoneMatrixWeights = false;
  63184. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63185. // Members
  63186. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63187. SceneLoader._registeredPlugins = {};
  63188. return SceneLoader;
  63189. }());
  63190. BABYLON.SceneLoader = SceneLoader;
  63191. ;
  63192. })(BABYLON || (BABYLON = {}));
  63193. //# sourceMappingURL=babylon.sceneLoader.js.map
  63194. "use strict";
  63195. var BABYLON;
  63196. (function (BABYLON) {
  63197. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63198. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63199. var parsedMaterial = parsedData.materials[index];
  63200. if (parsedMaterial.id === id) {
  63201. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63202. }
  63203. }
  63204. return null;
  63205. };
  63206. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63207. for (var i in names) {
  63208. if (mesh.name === names[i]) {
  63209. hierarchyIds.push(mesh.id);
  63210. return true;
  63211. }
  63212. }
  63213. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63214. hierarchyIds.push(mesh.id);
  63215. return true;
  63216. }
  63217. return false;
  63218. };
  63219. var logOperation = function (operation, producer) {
  63220. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63221. };
  63222. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63223. if (addToScene === void 0) { addToScene = false; }
  63224. var container = new BABYLON.AssetContainer(scene);
  63225. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63226. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63227. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63228. // and avoid problems with multiple concurrent .babylon loads.
  63229. var log = "importScene has failed JSON parse";
  63230. try {
  63231. var parsedData = JSON.parse(data);
  63232. log = "";
  63233. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63234. var index;
  63235. var cache;
  63236. // Lights
  63237. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63238. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63239. var parsedLight = parsedData.lights[index];
  63240. var light = BABYLON.Light.Parse(parsedLight, scene);
  63241. if (light) {
  63242. container.lights.push(light);
  63243. log += (index === 0 ? "\n\tLights:" : "");
  63244. log += "\n\t\t" + light.toString(fullDetails);
  63245. }
  63246. }
  63247. }
  63248. // Animations
  63249. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63250. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63251. var parsedAnimation = parsedData.animations[index];
  63252. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63253. scene.animations.push(animation);
  63254. container.animations.push(animation);
  63255. log += (index === 0 ? "\n\tAnimations:" : "");
  63256. log += "\n\t\t" + animation.toString(fullDetails);
  63257. }
  63258. }
  63259. // Materials
  63260. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63261. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63262. var parsedMaterial = parsedData.materials[index];
  63263. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63264. container.materials.push(mat);
  63265. log += (index === 0 ? "\n\tMaterials:" : "");
  63266. log += "\n\t\t" + mat.toString(fullDetails);
  63267. }
  63268. }
  63269. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63270. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63271. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63272. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63273. container.multiMaterials.push(mmat);
  63274. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63275. log += "\n\t\t" + mmat.toString(fullDetails);
  63276. }
  63277. }
  63278. // Morph targets
  63279. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63280. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63281. var managerData = _a[_i];
  63282. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63283. }
  63284. }
  63285. // Skeletons
  63286. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63287. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63288. var parsedSkeleton = parsedData.skeletons[index];
  63289. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63290. container.skeletons.push(skeleton);
  63291. log += (index === 0 ? "\n\tSkeletons:" : "");
  63292. log += "\n\t\t" + skeleton.toString(fullDetails);
  63293. }
  63294. }
  63295. // Geometries
  63296. var geometries = parsedData.geometries;
  63297. if (geometries !== undefined && geometries !== null) {
  63298. var addedGeometry = new Array();
  63299. // Boxes
  63300. var boxes = geometries.boxes;
  63301. if (boxes !== undefined && boxes !== null) {
  63302. for (index = 0, cache = boxes.length; index < cache; index++) {
  63303. var parsedBox = boxes[index];
  63304. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63305. }
  63306. }
  63307. // Spheres
  63308. var spheres = geometries.spheres;
  63309. if (spheres !== undefined && spheres !== null) {
  63310. for (index = 0, cache = spheres.length; index < cache; index++) {
  63311. var parsedSphere = spheres[index];
  63312. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63313. }
  63314. }
  63315. // Cylinders
  63316. var cylinders = geometries.cylinders;
  63317. if (cylinders !== undefined && cylinders !== null) {
  63318. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63319. var parsedCylinder = cylinders[index];
  63320. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63321. }
  63322. }
  63323. // Toruses
  63324. var toruses = geometries.toruses;
  63325. if (toruses !== undefined && toruses !== null) {
  63326. for (index = 0, cache = toruses.length; index < cache; index++) {
  63327. var parsedTorus = toruses[index];
  63328. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63329. }
  63330. }
  63331. // Grounds
  63332. var grounds = geometries.grounds;
  63333. if (grounds !== undefined && grounds !== null) {
  63334. for (index = 0, cache = grounds.length; index < cache; index++) {
  63335. var parsedGround = grounds[index];
  63336. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63337. }
  63338. }
  63339. // Planes
  63340. var planes = geometries.planes;
  63341. if (planes !== undefined && planes !== null) {
  63342. for (index = 0, cache = planes.length; index < cache; index++) {
  63343. var parsedPlane = planes[index];
  63344. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63345. }
  63346. }
  63347. // TorusKnots
  63348. var torusKnots = geometries.torusKnots;
  63349. if (torusKnots !== undefined && torusKnots !== null) {
  63350. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63351. var parsedTorusKnot = torusKnots[index];
  63352. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63353. }
  63354. }
  63355. // VertexData
  63356. var vertexData = geometries.vertexData;
  63357. if (vertexData !== undefined && vertexData !== null) {
  63358. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63359. var parsedVertexData = vertexData[index];
  63360. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63361. }
  63362. }
  63363. addedGeometry.forEach(function (g) {
  63364. if (g) {
  63365. container.geometries.push(g);
  63366. }
  63367. });
  63368. }
  63369. // Transform nodes
  63370. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63371. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63372. var parsedTransformNode = parsedData.transformNodes[index];
  63373. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63374. container.transformNodes.push(node);
  63375. }
  63376. }
  63377. // Meshes
  63378. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63379. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63380. var parsedMesh = parsedData.meshes[index];
  63381. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63382. container.meshes.push(mesh);
  63383. log += (index === 0 ? "\n\tMeshes:" : "");
  63384. log += "\n\t\t" + mesh.toString(fullDetails);
  63385. }
  63386. }
  63387. // Cameras
  63388. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63389. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63390. var parsedCamera = parsedData.cameras[index];
  63391. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63392. container.cameras.push(camera);
  63393. log += (index === 0 ? "\n\tCameras:" : "");
  63394. log += "\n\t\t" + camera.toString(fullDetails);
  63395. }
  63396. }
  63397. // Browsing all the graph to connect the dots
  63398. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63399. var camera = scene.cameras[index];
  63400. if (camera._waitingParentId) {
  63401. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63402. camera._waitingParentId = null;
  63403. }
  63404. }
  63405. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63406. var light_1 = scene.lights[index];
  63407. if (light_1 && light_1._waitingParentId) {
  63408. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63409. light_1._waitingParentId = null;
  63410. }
  63411. }
  63412. // Sounds
  63413. // TODO: add sound
  63414. var loadedSounds = [];
  63415. var loadedSound;
  63416. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63417. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63418. var parsedSound = parsedData.sounds[index];
  63419. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63420. if (!parsedSound.url)
  63421. parsedSound.url = parsedSound.name;
  63422. if (!loadedSounds[parsedSound.url]) {
  63423. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63424. loadedSounds[parsedSound.url] = loadedSound;
  63425. container.sounds.push(loadedSound);
  63426. }
  63427. else {
  63428. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63429. }
  63430. }
  63431. else {
  63432. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63433. }
  63434. }
  63435. }
  63436. loadedSounds = [];
  63437. // Connect parents & children and parse actions
  63438. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63439. var transformNode = scene.transformNodes[index];
  63440. if (transformNode._waitingParentId) {
  63441. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63442. transformNode._waitingParentId = null;
  63443. }
  63444. }
  63445. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63446. var mesh = scene.meshes[index];
  63447. if (mesh._waitingParentId) {
  63448. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63449. mesh._waitingParentId = null;
  63450. }
  63451. if (mesh._waitingActions) {
  63452. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63453. mesh._waitingActions = null;
  63454. }
  63455. }
  63456. // freeze world matrix application
  63457. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63458. var currentMesh = scene.meshes[index];
  63459. if (currentMesh._waitingFreezeWorldMatrix) {
  63460. currentMesh.freezeWorldMatrix();
  63461. currentMesh._waitingFreezeWorldMatrix = null;
  63462. }
  63463. else {
  63464. currentMesh.computeWorldMatrix(true);
  63465. }
  63466. }
  63467. // Particles Systems
  63468. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63469. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63470. var parsedParticleSystem = parsedData.particleSystems[index];
  63471. if (parsedParticleSystem.activeParticleCount) {
  63472. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63473. container.particleSystems.push(ps);
  63474. }
  63475. else {
  63476. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63477. container.particleSystems.push(ps);
  63478. }
  63479. }
  63480. }
  63481. // Lens flares
  63482. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63483. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63484. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63485. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63486. container.lensFlareSystems.push(lf);
  63487. }
  63488. }
  63489. // Shadows
  63490. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63491. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63492. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63493. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63494. container.shadowGenerators.push(sg);
  63495. }
  63496. }
  63497. // Lights exclusions / inclusions
  63498. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63499. var light_2 = scene.lights[index];
  63500. // Excluded check
  63501. if (light_2._excludedMeshesIds.length > 0) {
  63502. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63503. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63504. if (excludedMesh) {
  63505. light_2.excludedMeshes.push(excludedMesh);
  63506. }
  63507. }
  63508. light_2._excludedMeshesIds = [];
  63509. }
  63510. // Included check
  63511. if (light_2._includedOnlyMeshesIds.length > 0) {
  63512. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63513. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63514. if (includedOnlyMesh) {
  63515. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63516. }
  63517. }
  63518. light_2._includedOnlyMeshesIds = [];
  63519. }
  63520. }
  63521. // Actions (scene)
  63522. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63523. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63524. }
  63525. if (!addToScene) {
  63526. container.removeAllFromScene();
  63527. }
  63528. }
  63529. catch (err) {
  63530. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63531. if (onError) {
  63532. onError(msg, err);
  63533. }
  63534. else {
  63535. BABYLON.Tools.Log(msg);
  63536. throw err;
  63537. }
  63538. }
  63539. finally {
  63540. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63541. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63542. }
  63543. }
  63544. return container;
  63545. };
  63546. BABYLON.SceneLoader.RegisterPlugin({
  63547. name: "babylon.js",
  63548. extensions: ".babylon",
  63549. canDirectLoad: function (data) {
  63550. if (data.indexOf("babylon") !== -1) {
  63551. return true;
  63552. }
  63553. return false;
  63554. },
  63555. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63556. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63557. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63558. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63559. // and avoid problems with multiple concurrent .babylon loads.
  63560. var log = "importMesh has failed JSON parse";
  63561. try {
  63562. var parsedData = JSON.parse(data);
  63563. log = "";
  63564. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63565. if (!meshesNames) {
  63566. meshesNames = null;
  63567. }
  63568. else if (!Array.isArray(meshesNames)) {
  63569. meshesNames = [meshesNames];
  63570. }
  63571. var hierarchyIds = new Array();
  63572. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63573. var loadedSkeletonsIds = [];
  63574. var loadedMaterialsIds = [];
  63575. var index;
  63576. var cache;
  63577. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63578. var parsedMesh = parsedData.meshes[index];
  63579. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63580. if (meshesNames !== null) {
  63581. // Remove found mesh name from list.
  63582. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63583. }
  63584. //Geometry?
  63585. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63586. //does the file contain geometries?
  63587. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63588. //find the correct geometry and add it to the scene
  63589. var found = false;
  63590. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63591. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63592. return;
  63593. }
  63594. else {
  63595. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63596. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63597. switch (geometryType) {
  63598. case "boxes":
  63599. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63600. break;
  63601. case "spheres":
  63602. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63603. break;
  63604. case "cylinders":
  63605. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63606. break;
  63607. case "toruses":
  63608. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63609. break;
  63610. case "grounds":
  63611. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63612. break;
  63613. case "planes":
  63614. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63615. break;
  63616. case "torusKnots":
  63617. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63618. break;
  63619. case "vertexData":
  63620. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63621. break;
  63622. }
  63623. found = true;
  63624. }
  63625. });
  63626. }
  63627. });
  63628. if (found === false) {
  63629. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63630. }
  63631. }
  63632. }
  63633. // Material ?
  63634. if (parsedMesh.materialId) {
  63635. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63636. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63637. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63638. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63639. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63640. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63641. var subMatId = parsedMultiMaterial.materials[matIndex];
  63642. loadedMaterialsIds.push(subMatId);
  63643. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63644. if (mat) {
  63645. log += "\n\tMaterial " + mat.toString(fullDetails);
  63646. }
  63647. }
  63648. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63649. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63650. if (mmat) {
  63651. materialFound = true;
  63652. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63653. }
  63654. break;
  63655. }
  63656. }
  63657. }
  63658. if (materialFound === false) {
  63659. loadedMaterialsIds.push(parsedMesh.materialId);
  63660. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63661. if (!mat) {
  63662. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63663. }
  63664. else {
  63665. log += "\n\tMaterial " + mat.toString(fullDetails);
  63666. }
  63667. }
  63668. }
  63669. // Skeleton ?
  63670. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63671. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63672. if (skeletonAlreadyLoaded === false) {
  63673. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63674. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63675. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63676. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63677. skeletons.push(skeleton);
  63678. loadedSkeletonsIds.push(parsedSkeleton.id);
  63679. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63680. }
  63681. }
  63682. }
  63683. }
  63684. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63685. meshes.push(mesh);
  63686. log += "\n\tMesh " + mesh.toString(fullDetails);
  63687. }
  63688. }
  63689. // Connecting parents
  63690. var currentMesh;
  63691. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63692. currentMesh = scene.meshes[index];
  63693. if (currentMesh._waitingParentId) {
  63694. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63695. currentMesh._waitingParentId = null;
  63696. }
  63697. }
  63698. // freeze and compute world matrix application
  63699. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63700. currentMesh = scene.meshes[index];
  63701. if (currentMesh._waitingFreezeWorldMatrix) {
  63702. currentMesh.freezeWorldMatrix();
  63703. currentMesh._waitingFreezeWorldMatrix = null;
  63704. }
  63705. else {
  63706. currentMesh.computeWorldMatrix(true);
  63707. }
  63708. }
  63709. }
  63710. // Particles
  63711. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63712. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63713. var parsedParticleSystem = parsedData.particleSystems[index];
  63714. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63715. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63716. }
  63717. }
  63718. }
  63719. return true;
  63720. }
  63721. catch (err) {
  63722. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63723. if (onError) {
  63724. onError(msg, err);
  63725. }
  63726. else {
  63727. BABYLON.Tools.Log(msg);
  63728. throw err;
  63729. }
  63730. }
  63731. finally {
  63732. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63733. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63734. }
  63735. }
  63736. return false;
  63737. },
  63738. load: function (scene, data, rootUrl, onError) {
  63739. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63740. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63741. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63742. // and avoid problems with multiple concurrent .babylon loads.
  63743. var log = "importScene has failed JSON parse";
  63744. try {
  63745. var parsedData = JSON.parse(data);
  63746. log = "";
  63747. // Scene
  63748. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63749. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63750. }
  63751. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63752. scene.autoClear = parsedData.autoClear;
  63753. }
  63754. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63755. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63756. }
  63757. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63758. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63759. }
  63760. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63761. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63762. }
  63763. // Fog
  63764. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63765. scene.fogMode = parsedData.fogMode;
  63766. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63767. scene.fogStart = parsedData.fogStart;
  63768. scene.fogEnd = parsedData.fogEnd;
  63769. scene.fogDensity = parsedData.fogDensity;
  63770. log += "\tFog mode for scene: ";
  63771. switch (scene.fogMode) {
  63772. // getters not compiling, so using hardcoded
  63773. case 1:
  63774. log += "exp\n";
  63775. break;
  63776. case 2:
  63777. log += "exp2\n";
  63778. break;
  63779. case 3:
  63780. log += "linear\n";
  63781. break;
  63782. }
  63783. }
  63784. //Physics
  63785. if (parsedData.physicsEnabled) {
  63786. var physicsPlugin;
  63787. if (parsedData.physicsEngine === "cannon") {
  63788. physicsPlugin = new BABYLON.CannonJSPlugin();
  63789. }
  63790. else if (parsedData.physicsEngine === "oimo") {
  63791. physicsPlugin = new BABYLON.OimoJSPlugin();
  63792. }
  63793. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63794. //else - default engine, which is currently oimo
  63795. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63796. scene.enablePhysics(physicsGravity, physicsPlugin);
  63797. }
  63798. // Metadata
  63799. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63800. scene.metadata = parsedData.metadata;
  63801. }
  63802. //collisions, if defined. otherwise, default is true
  63803. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63804. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63805. }
  63806. scene.workerCollisions = !!parsedData.workerCollisions;
  63807. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63808. if (!container) {
  63809. return false;
  63810. }
  63811. if (parsedData.autoAnimate) {
  63812. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63813. }
  63814. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63815. scene.setActiveCameraByID(parsedData.activeCameraID);
  63816. }
  63817. // Environment texture
  63818. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63819. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63820. if (parsedData.createDefaultSkybox === true) {
  63821. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63822. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63823. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63824. }
  63825. }
  63826. // Finish
  63827. return true;
  63828. }
  63829. catch (err) {
  63830. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63831. if (onError) {
  63832. onError(msg, err);
  63833. }
  63834. else {
  63835. BABYLON.Tools.Log(msg);
  63836. throw err;
  63837. }
  63838. }
  63839. finally {
  63840. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63841. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63842. }
  63843. }
  63844. return false;
  63845. },
  63846. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63847. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63848. return container;
  63849. }
  63850. });
  63851. })(BABYLON || (BABYLON = {}));
  63852. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63853. "use strict";
  63854. var BABYLON;
  63855. (function (BABYLON) {
  63856. var FilesInput = /** @class */ (function () {
  63857. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63858. this.onProcessFileCallback = function () { return true; };
  63859. this._engine = engine;
  63860. this._currentScene = scene;
  63861. this._sceneLoadedCallback = sceneLoadedCallback;
  63862. this._progressCallback = progressCallback;
  63863. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63864. this._textureLoadingCallback = textureLoadingCallback;
  63865. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63866. this._onReloadCallback = onReloadCallback;
  63867. this._errorCallback = errorCallback;
  63868. }
  63869. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63870. var _this = this;
  63871. if (elementToMonitor) {
  63872. this._elementToMonitor = elementToMonitor;
  63873. this._dragEnterHandler = function (e) { _this.drag(e); };
  63874. this._dragOverHandler = function (e) { _this.drag(e); };
  63875. this._dropHandler = function (e) { _this.drop(e); };
  63876. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63877. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63878. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63879. }
  63880. };
  63881. FilesInput.prototype.dispose = function () {
  63882. if (!this._elementToMonitor) {
  63883. return;
  63884. }
  63885. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63886. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63887. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63888. };
  63889. FilesInput.prototype.renderFunction = function () {
  63890. if (this._additionalRenderLoopLogicCallback) {
  63891. this._additionalRenderLoopLogicCallback();
  63892. }
  63893. if (this._currentScene) {
  63894. if (this._textureLoadingCallback) {
  63895. var remaining = this._currentScene.getWaitingItemsCount();
  63896. if (remaining > 0) {
  63897. this._textureLoadingCallback(remaining);
  63898. }
  63899. }
  63900. this._currentScene.render();
  63901. }
  63902. };
  63903. FilesInput.prototype.drag = function (e) {
  63904. e.stopPropagation();
  63905. e.preventDefault();
  63906. };
  63907. FilesInput.prototype.drop = function (eventDrop) {
  63908. eventDrop.stopPropagation();
  63909. eventDrop.preventDefault();
  63910. this.loadFiles(eventDrop);
  63911. };
  63912. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63913. var _this = this;
  63914. var reader = folder.createReader();
  63915. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63916. reader.readEntries(function (entries) {
  63917. remaining.count += entries.length;
  63918. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63919. var entry = entries_1[_i];
  63920. if (entry.isFile) {
  63921. entry.file(function (file) {
  63922. file.correctName = relativePath + file.name;
  63923. files.push(file);
  63924. if (--remaining.count === 0) {
  63925. callback();
  63926. }
  63927. });
  63928. }
  63929. else if (entry.isDirectory) {
  63930. _this._traverseFolder(entry, files, remaining, callback);
  63931. }
  63932. }
  63933. if (--remaining.count) {
  63934. callback();
  63935. }
  63936. });
  63937. };
  63938. FilesInput.prototype._processFiles = function (files) {
  63939. for (var i = 0; i < files.length; i++) {
  63940. var name = files[i].correctName.toLowerCase();
  63941. var extension = name.split('.').pop();
  63942. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63943. continue;
  63944. }
  63945. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63946. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63947. this._sceneFileToLoad = files[i];
  63948. }
  63949. else {
  63950. FilesInput.FilesToLoad[name] = files[i];
  63951. }
  63952. }
  63953. };
  63954. FilesInput.prototype.loadFiles = function (event) {
  63955. var _this = this;
  63956. if (this._startingProcessingFilesCallback)
  63957. this._startingProcessingFilesCallback();
  63958. // Handling data transfer via drag'n'drop
  63959. if (event && event.dataTransfer && event.dataTransfer.files) {
  63960. this._filesToLoad = event.dataTransfer.files;
  63961. }
  63962. // Handling files from input files
  63963. if (event && event.target && event.target.files) {
  63964. this._filesToLoad = event.target.files;
  63965. }
  63966. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63967. var files_1 = new Array();
  63968. var folders = [];
  63969. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63970. for (var i = 0; i < this._filesToLoad.length; i++) {
  63971. var fileToLoad = this._filesToLoad[i];
  63972. var name_1 = fileToLoad.name.toLowerCase();
  63973. var entry = void 0;
  63974. fileToLoad.correctName = name_1;
  63975. if (items) {
  63976. var item = items[i];
  63977. if (item.getAsEntry) {
  63978. entry = item.getAsEntry();
  63979. }
  63980. else if (item.webkitGetAsEntry) {
  63981. entry = item.webkitGetAsEntry();
  63982. }
  63983. }
  63984. if (!entry) {
  63985. files_1.push(fileToLoad);
  63986. }
  63987. else {
  63988. if (entry.isDirectory) {
  63989. folders.push(entry);
  63990. }
  63991. else {
  63992. files_1.push(fileToLoad);
  63993. }
  63994. }
  63995. }
  63996. if (folders.length === 0) {
  63997. this._processFiles(files_1);
  63998. this._processReload();
  63999. }
  64000. else {
  64001. var remaining = { count: folders.length };
  64002. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  64003. var folder = folders_1[_i];
  64004. this._traverseFolder(folder, files_1, remaining, function () {
  64005. _this._processFiles(files_1);
  64006. if (remaining.count === 0) {
  64007. _this._processReload();
  64008. }
  64009. });
  64010. }
  64011. }
  64012. }
  64013. };
  64014. FilesInput.prototype._processReload = function () {
  64015. if (this._onReloadCallback) {
  64016. this._onReloadCallback(this._sceneFileToLoad);
  64017. }
  64018. else {
  64019. this.reload();
  64020. }
  64021. };
  64022. FilesInput.prototype.reload = function () {
  64023. var _this = this;
  64024. // If a scene file has been provided
  64025. if (this._sceneFileToLoad) {
  64026. if (this._currentScene) {
  64027. if (BABYLON.Tools.errorsCount > 0) {
  64028. BABYLON.Tools.ClearLogCache();
  64029. }
  64030. this._engine.stopRenderLoop();
  64031. this._currentScene.dispose();
  64032. }
  64033. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  64034. if (_this._progressCallback) {
  64035. _this._progressCallback(progress);
  64036. }
  64037. }).then(function (scene) {
  64038. _this._currentScene = scene;
  64039. if (_this._sceneLoadedCallback) {
  64040. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  64041. }
  64042. // Wait for textures and shaders to be ready
  64043. _this._currentScene.executeWhenReady(function () {
  64044. _this._engine.runRenderLoop(function () {
  64045. _this.renderFunction();
  64046. });
  64047. });
  64048. }).catch(function (error) {
  64049. if (_this._errorCallback) {
  64050. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  64051. }
  64052. });
  64053. }
  64054. else {
  64055. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  64056. }
  64057. };
  64058. FilesInput.FilesToLoad = {};
  64059. return FilesInput;
  64060. }());
  64061. BABYLON.FilesInput = FilesInput;
  64062. })(BABYLON || (BABYLON = {}));
  64063. //# sourceMappingURL=babylon.filesInput.js.map
  64064. "use strict";
  64065. var BABYLON;
  64066. (function (BABYLON) {
  64067. /**
  64068. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64069. * The underlying implementation relies on an associative array to ensure the best performances.
  64070. * The value can be anything including 'null' but except 'undefined'
  64071. */
  64072. var StringDictionary = /** @class */ (function () {
  64073. function StringDictionary() {
  64074. this._count = 0;
  64075. this._data = {};
  64076. }
  64077. /**
  64078. * This will clear this dictionary and copy the content from the 'source' one.
  64079. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64080. * @param source the dictionary to take the content from and copy to this dictionary
  64081. */
  64082. StringDictionary.prototype.copyFrom = function (source) {
  64083. var _this = this;
  64084. this.clear();
  64085. source.forEach(function (t, v) { return _this.add(t, v); });
  64086. };
  64087. /**
  64088. * Get a value based from its key
  64089. * @param key the given key to get the matching value from
  64090. * @return the value if found, otherwise undefined is returned
  64091. */
  64092. StringDictionary.prototype.get = function (key) {
  64093. var val = this._data[key];
  64094. if (val !== undefined) {
  64095. return val;
  64096. }
  64097. return undefined;
  64098. };
  64099. /**
  64100. * Get a value from its key or add it if it doesn't exist.
  64101. * This method will ensure you that a given key/data will be present in the dictionary.
  64102. * @param key the given key to get the matching value from
  64103. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64104. * The factory will only be invoked if there's no data for the given key.
  64105. * @return the value corresponding to the key.
  64106. */
  64107. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64108. var val = this.get(key);
  64109. if (val !== undefined) {
  64110. return val;
  64111. }
  64112. val = factory(key);
  64113. if (val) {
  64114. this.add(key, val);
  64115. }
  64116. return val;
  64117. };
  64118. /**
  64119. * Get a value from its key if present in the dictionary otherwise add it
  64120. * @param key the key to get the value from
  64121. * @param val if there's no such key/value pair in the dictionary add it with this value
  64122. * @return the value corresponding to the key
  64123. */
  64124. StringDictionary.prototype.getOrAdd = function (key, val) {
  64125. var curVal = this.get(key);
  64126. if (curVal !== undefined) {
  64127. return curVal;
  64128. }
  64129. this.add(key, val);
  64130. return val;
  64131. };
  64132. /**
  64133. * Check if there's a given key in the dictionary
  64134. * @param key the key to check for
  64135. * @return true if the key is present, false otherwise
  64136. */
  64137. StringDictionary.prototype.contains = function (key) {
  64138. return this._data[key] !== undefined;
  64139. };
  64140. /**
  64141. * Add a new key and its corresponding value
  64142. * @param key the key to add
  64143. * @param value the value corresponding to the key
  64144. * @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
  64145. */
  64146. StringDictionary.prototype.add = function (key, value) {
  64147. if (this._data[key] !== undefined) {
  64148. return false;
  64149. }
  64150. this._data[key] = value;
  64151. ++this._count;
  64152. return true;
  64153. };
  64154. StringDictionary.prototype.set = function (key, value) {
  64155. if (this._data[key] === undefined) {
  64156. return false;
  64157. }
  64158. this._data[key] = value;
  64159. return true;
  64160. };
  64161. /**
  64162. * Get the element of the given key and remove it from the dictionary
  64163. * @param key
  64164. */
  64165. StringDictionary.prototype.getAndRemove = function (key) {
  64166. var val = this.get(key);
  64167. if (val !== undefined) {
  64168. delete this._data[key];
  64169. --this._count;
  64170. return val;
  64171. }
  64172. return null;
  64173. };
  64174. /**
  64175. * Remove a key/value from the dictionary.
  64176. * @param key the key to remove
  64177. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64178. */
  64179. StringDictionary.prototype.remove = function (key) {
  64180. if (this.contains(key)) {
  64181. delete this._data[key];
  64182. --this._count;
  64183. return true;
  64184. }
  64185. return false;
  64186. };
  64187. /**
  64188. * Clear the whole content of the dictionary
  64189. */
  64190. StringDictionary.prototype.clear = function () {
  64191. this._data = {};
  64192. this._count = 0;
  64193. };
  64194. Object.defineProperty(StringDictionary.prototype, "count", {
  64195. get: function () {
  64196. return this._count;
  64197. },
  64198. enumerable: true,
  64199. configurable: true
  64200. });
  64201. /**
  64202. * Execute a callback on each key/val of the dictionary.
  64203. * Note that you can remove any element in this dictionary in the callback implementation
  64204. * @param callback the callback to execute on a given key/value pair
  64205. */
  64206. StringDictionary.prototype.forEach = function (callback) {
  64207. for (var cur in this._data) {
  64208. var val = this._data[cur];
  64209. callback(cur, val);
  64210. }
  64211. };
  64212. /**
  64213. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64214. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64215. * Note that you can remove any element in this dictionary in the callback implementation
  64216. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64217. */
  64218. StringDictionary.prototype.first = function (callback) {
  64219. for (var cur in this._data) {
  64220. var val = this._data[cur];
  64221. var res = callback(cur, val);
  64222. if (res) {
  64223. return res;
  64224. }
  64225. }
  64226. return null;
  64227. };
  64228. return StringDictionary;
  64229. }());
  64230. BABYLON.StringDictionary = StringDictionary;
  64231. })(BABYLON || (BABYLON = {}));
  64232. //# sourceMappingURL=babylon.stringDictionary.js.map
  64233. "use strict";
  64234. var BABYLON;
  64235. (function (BABYLON) {
  64236. var Tags = /** @class */ (function () {
  64237. function Tags() {
  64238. }
  64239. Tags.EnableFor = function (obj) {
  64240. obj._tags = obj._tags || {};
  64241. obj.hasTags = function () {
  64242. return Tags.HasTags(obj);
  64243. };
  64244. obj.addTags = function (tagsString) {
  64245. return Tags.AddTagsTo(obj, tagsString);
  64246. };
  64247. obj.removeTags = function (tagsString) {
  64248. return Tags.RemoveTagsFrom(obj, tagsString);
  64249. };
  64250. obj.matchesTagsQuery = function (tagsQuery) {
  64251. return Tags.MatchesQuery(obj, tagsQuery);
  64252. };
  64253. };
  64254. Tags.DisableFor = function (obj) {
  64255. delete obj._tags;
  64256. delete obj.hasTags;
  64257. delete obj.addTags;
  64258. delete obj.removeTags;
  64259. delete obj.matchesTagsQuery;
  64260. };
  64261. Tags.HasTags = function (obj) {
  64262. if (!obj._tags) {
  64263. return false;
  64264. }
  64265. return !BABYLON.Tools.IsEmpty(obj._tags);
  64266. };
  64267. Tags.GetTags = function (obj, asString) {
  64268. if (asString === void 0) { asString = true; }
  64269. if (!obj._tags) {
  64270. return null;
  64271. }
  64272. if (asString) {
  64273. var tagsArray = [];
  64274. for (var tag in obj._tags) {
  64275. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64276. tagsArray.push(tag);
  64277. }
  64278. }
  64279. return tagsArray.join(" ");
  64280. }
  64281. else {
  64282. return obj._tags;
  64283. }
  64284. };
  64285. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64286. // a tag cannot start with '||', '&&', and '!'
  64287. // it cannot contain whitespaces
  64288. Tags.AddTagsTo = function (obj, tagsString) {
  64289. if (!tagsString) {
  64290. return;
  64291. }
  64292. if (typeof tagsString !== "string") {
  64293. return;
  64294. }
  64295. var tags = tagsString.split(" ");
  64296. tags.forEach(function (tag, index, array) {
  64297. Tags._AddTagTo(obj, tag);
  64298. });
  64299. };
  64300. Tags._AddTagTo = function (obj, tag) {
  64301. tag = tag.trim();
  64302. if (tag === "" || tag === "true" || tag === "false") {
  64303. return;
  64304. }
  64305. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64306. return;
  64307. }
  64308. Tags.EnableFor(obj);
  64309. obj._tags[tag] = true;
  64310. };
  64311. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64312. if (!Tags.HasTags(obj)) {
  64313. return;
  64314. }
  64315. var tags = tagsString.split(" ");
  64316. for (var t in tags) {
  64317. Tags._RemoveTagFrom(obj, tags[t]);
  64318. }
  64319. };
  64320. Tags._RemoveTagFrom = function (obj, tag) {
  64321. delete obj._tags[tag];
  64322. };
  64323. Tags.MatchesQuery = function (obj, tagsQuery) {
  64324. if (tagsQuery === undefined) {
  64325. return true;
  64326. }
  64327. if (tagsQuery === "") {
  64328. return Tags.HasTags(obj);
  64329. }
  64330. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64331. };
  64332. return Tags;
  64333. }());
  64334. BABYLON.Tags = Tags;
  64335. })(BABYLON || (BABYLON = {}));
  64336. //# sourceMappingURL=babylon.tags.js.map
  64337. "use strict";
  64338. var BABYLON;
  64339. (function (BABYLON) {
  64340. var AndOrNotEvaluator = /** @class */ (function () {
  64341. function AndOrNotEvaluator() {
  64342. }
  64343. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64344. if (!query.match(/\([^\(\)]*\)/g)) {
  64345. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64346. }
  64347. else {
  64348. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64349. // remove parenthesis
  64350. r = r.slice(1, r.length - 1);
  64351. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64352. });
  64353. }
  64354. if (query === "true") {
  64355. return true;
  64356. }
  64357. if (query === "false") {
  64358. return false;
  64359. }
  64360. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64361. };
  64362. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64363. evaluateCallback = evaluateCallback || (function (r) {
  64364. return r === "true" ? true : false;
  64365. });
  64366. var result;
  64367. var or = parenthesisContent.split("||");
  64368. for (var i in or) {
  64369. if (or.hasOwnProperty(i)) {
  64370. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64371. var and = ori.split("&&");
  64372. if (and.length > 1) {
  64373. for (var j = 0; j < and.length; ++j) {
  64374. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64375. if (andj !== "true" && andj !== "false") {
  64376. if (andj[0] === "!") {
  64377. result = !evaluateCallback(andj.substring(1));
  64378. }
  64379. else {
  64380. result = evaluateCallback(andj);
  64381. }
  64382. }
  64383. else {
  64384. result = andj === "true" ? true : false;
  64385. }
  64386. if (!result) {
  64387. ori = "false";
  64388. break;
  64389. }
  64390. }
  64391. }
  64392. if (result || ori === "true") {
  64393. result = true;
  64394. break;
  64395. }
  64396. // result equals false (or undefined)
  64397. if (ori !== "true" && ori !== "false") {
  64398. if (ori[0] === "!") {
  64399. result = !evaluateCallback(ori.substring(1));
  64400. }
  64401. else {
  64402. result = evaluateCallback(ori);
  64403. }
  64404. }
  64405. else {
  64406. result = ori === "true" ? true : false;
  64407. }
  64408. }
  64409. }
  64410. // the whole parenthesis scope is replaced by 'true' or 'false'
  64411. return result ? "true" : "false";
  64412. };
  64413. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64414. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64415. // remove whitespaces
  64416. r = r.replace(/[\s]/g, function () { return ""; });
  64417. return r.length % 2 ? "!" : "";
  64418. });
  64419. booleanString = booleanString.trim();
  64420. if (booleanString === "!true") {
  64421. booleanString = "false";
  64422. }
  64423. else if (booleanString === "!false") {
  64424. booleanString = "true";
  64425. }
  64426. return booleanString;
  64427. };
  64428. return AndOrNotEvaluator;
  64429. }());
  64430. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64431. })(BABYLON || (BABYLON = {}));
  64432. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64433. "use strict";
  64434. var BABYLON;
  64435. (function (BABYLON) {
  64436. var Database = /** @class */ (function () {
  64437. function Database(urlToScene, callbackManifestChecked) {
  64438. // Handling various flavors of prefixed version of IndexedDB
  64439. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64440. this.callbackManifestChecked = callbackManifestChecked;
  64441. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64442. this.db = null;
  64443. this._enableSceneOffline = false;
  64444. this._enableTexturesOffline = false;
  64445. this.manifestVersionFound = 0;
  64446. this.mustUpdateRessources = false;
  64447. this.hasReachedQuota = false;
  64448. if (!Database.IDBStorageEnabled) {
  64449. this.callbackManifestChecked(true);
  64450. }
  64451. else {
  64452. this.checkManifestFile();
  64453. }
  64454. }
  64455. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64456. get: function () {
  64457. return this._enableSceneOffline;
  64458. },
  64459. enumerable: true,
  64460. configurable: true
  64461. });
  64462. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64463. get: function () {
  64464. return this._enableTexturesOffline;
  64465. },
  64466. enumerable: true,
  64467. configurable: true
  64468. });
  64469. Database.prototype.checkManifestFile = function () {
  64470. var _this = this;
  64471. var noManifestFile = function () {
  64472. _this._enableSceneOffline = false;
  64473. _this._enableTexturesOffline = false;
  64474. _this.callbackManifestChecked(false);
  64475. };
  64476. var timeStampUsed = false;
  64477. var manifestURL = this.currentSceneUrl + ".manifest";
  64478. var xhr = new XMLHttpRequest();
  64479. if (navigator.onLine) {
  64480. // Adding a timestamp to by-pass browsers' cache
  64481. timeStampUsed = true;
  64482. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64483. }
  64484. xhr.open("GET", manifestURL, true);
  64485. xhr.addEventListener("load", function () {
  64486. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64487. try {
  64488. var manifestFile = JSON.parse(xhr.response);
  64489. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64490. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64491. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64492. _this.manifestVersionFound = manifestFile.version;
  64493. }
  64494. if (_this.callbackManifestChecked) {
  64495. _this.callbackManifestChecked(true);
  64496. }
  64497. }
  64498. catch (ex) {
  64499. noManifestFile();
  64500. }
  64501. }
  64502. else {
  64503. noManifestFile();
  64504. }
  64505. }, false);
  64506. xhr.addEventListener("error", function (event) {
  64507. if (timeStampUsed) {
  64508. timeStampUsed = false;
  64509. // Let's retry without the timeStamp
  64510. // It could fail when coupled with HTML5 Offline API
  64511. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64512. xhr.open("GET", retryManifestURL, true);
  64513. xhr.send();
  64514. }
  64515. else {
  64516. noManifestFile();
  64517. }
  64518. }, false);
  64519. try {
  64520. xhr.send();
  64521. }
  64522. catch (ex) {
  64523. BABYLON.Tools.Error("Error on XHR send request.");
  64524. this.callbackManifestChecked(false);
  64525. }
  64526. };
  64527. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64528. var _this = this;
  64529. var handleError = function () {
  64530. _this.isSupported = false;
  64531. if (errorCallback)
  64532. errorCallback();
  64533. };
  64534. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64535. // Your browser doesn't support IndexedDB
  64536. this.isSupported = false;
  64537. if (errorCallback)
  64538. errorCallback();
  64539. }
  64540. else {
  64541. // If the DB hasn't been opened or created yet
  64542. if (!this.db) {
  64543. this.hasReachedQuota = false;
  64544. this.isSupported = true;
  64545. var request = this.idbFactory.open("babylonjs", 1);
  64546. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64547. request.onerror = function (event) {
  64548. handleError();
  64549. };
  64550. // executes when a version change transaction cannot complete due to other active transactions
  64551. request.onblocked = function (event) {
  64552. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64553. handleError();
  64554. };
  64555. // DB has been opened successfully
  64556. request.onsuccess = function (event) {
  64557. _this.db = request.result;
  64558. successCallback();
  64559. };
  64560. // Initialization of the DB. Creating Scenes & Textures stores
  64561. request.onupgradeneeded = function (event) {
  64562. _this.db = (event.target).result;
  64563. if (_this.db) {
  64564. try {
  64565. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64566. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64567. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64568. }
  64569. catch (ex) {
  64570. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64571. handleError();
  64572. }
  64573. }
  64574. };
  64575. }
  64576. else {
  64577. if (successCallback)
  64578. successCallback();
  64579. }
  64580. }
  64581. };
  64582. Database.prototype.loadImageFromDB = function (url, image) {
  64583. var _this = this;
  64584. var completeURL = Database.ReturnFullUrlLocation(url);
  64585. var saveAndLoadImage = function () {
  64586. if (!_this.hasReachedQuota && _this.db !== null) {
  64587. // the texture is not yet in the DB, let's try to save it
  64588. _this._saveImageIntoDBAsync(completeURL, image);
  64589. }
  64590. else {
  64591. image.src = url;
  64592. }
  64593. };
  64594. if (!this.mustUpdateRessources) {
  64595. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64596. }
  64597. else {
  64598. saveAndLoadImage();
  64599. }
  64600. };
  64601. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64602. if (this.isSupported && this.db !== null) {
  64603. var texture;
  64604. var transaction = this.db.transaction(["textures"]);
  64605. transaction.onabort = function (event) {
  64606. image.src = url;
  64607. };
  64608. transaction.oncomplete = function (event) {
  64609. var blobTextureURL;
  64610. if (texture) {
  64611. var URL = window.URL || window.webkitURL;
  64612. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64613. image.onerror = function () {
  64614. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64615. image.src = url;
  64616. };
  64617. image.src = blobTextureURL;
  64618. }
  64619. else {
  64620. notInDBCallback();
  64621. }
  64622. };
  64623. var getRequest = transaction.objectStore("textures").get(url);
  64624. getRequest.onsuccess = function (event) {
  64625. texture = (event.target).result;
  64626. };
  64627. getRequest.onerror = function (event) {
  64628. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64629. image.src = url;
  64630. };
  64631. }
  64632. else {
  64633. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64634. image.src = url;
  64635. }
  64636. };
  64637. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64638. var _this = this;
  64639. if (this.isSupported) {
  64640. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64641. var generateBlobUrl = function () {
  64642. var blobTextureURL;
  64643. if (blob) {
  64644. var URL = window.URL || window.webkitURL;
  64645. try {
  64646. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64647. }
  64648. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64649. catch (ex) {
  64650. blobTextureURL = URL.createObjectURL(blob);
  64651. }
  64652. }
  64653. if (blobTextureURL) {
  64654. image.src = blobTextureURL;
  64655. }
  64656. };
  64657. if (Database.IsUASupportingBlobStorage) {
  64658. var xhr = new XMLHttpRequest(), blob;
  64659. xhr.open("GET", url, true);
  64660. xhr.responseType = "blob";
  64661. xhr.addEventListener("load", function () {
  64662. if (xhr.status === 200 && _this.db) {
  64663. // Blob as response (XHR2)
  64664. blob = xhr.response;
  64665. var transaction = _this.db.transaction(["textures"], "readwrite");
  64666. // the transaction could abort because of a QuotaExceededError error
  64667. transaction.onabort = function (event) {
  64668. try {
  64669. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64670. var srcElement = (event.srcElement || event.target);
  64671. var error = srcElement.error;
  64672. if (error && error.name === "QuotaExceededError") {
  64673. _this.hasReachedQuota = true;
  64674. }
  64675. }
  64676. catch (ex) { }
  64677. generateBlobUrl();
  64678. };
  64679. transaction.oncomplete = function (event) {
  64680. generateBlobUrl();
  64681. };
  64682. var newTexture = { textureUrl: url, data: blob };
  64683. try {
  64684. // Put the blob into the dabase
  64685. var addRequest = transaction.objectStore("textures").put(newTexture);
  64686. addRequest.onsuccess = function (event) {
  64687. };
  64688. addRequest.onerror = function (event) {
  64689. generateBlobUrl();
  64690. };
  64691. }
  64692. catch (ex) {
  64693. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64694. if (ex.code === 25) {
  64695. Database.IsUASupportingBlobStorage = false;
  64696. }
  64697. image.src = url;
  64698. }
  64699. }
  64700. else {
  64701. image.src = url;
  64702. }
  64703. }, false);
  64704. xhr.addEventListener("error", function (event) {
  64705. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64706. image.src = url;
  64707. }, false);
  64708. xhr.send();
  64709. }
  64710. else {
  64711. image.src = url;
  64712. }
  64713. }
  64714. else {
  64715. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64716. image.src = url;
  64717. }
  64718. };
  64719. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64720. var _this = this;
  64721. var updateVersion = function () {
  64722. // the version is not yet in the DB or we need to update it
  64723. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64724. };
  64725. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64726. };
  64727. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64728. var _this = this;
  64729. if (this.isSupported && this.db) {
  64730. var version;
  64731. try {
  64732. var transaction = this.db.transaction(["versions"]);
  64733. transaction.oncomplete = function (event) {
  64734. if (version) {
  64735. // If the version in the JSON file is > than the version in DB
  64736. if (_this.manifestVersionFound > version.data) {
  64737. _this.mustUpdateRessources = true;
  64738. updateInDBCallback();
  64739. }
  64740. else {
  64741. callback(version.data);
  64742. }
  64743. }
  64744. else {
  64745. _this.mustUpdateRessources = true;
  64746. updateInDBCallback();
  64747. }
  64748. };
  64749. transaction.onabort = function (event) {
  64750. callback(-1);
  64751. };
  64752. var getRequest = transaction.objectStore("versions").get(url);
  64753. getRequest.onsuccess = function (event) {
  64754. version = (event.target).result;
  64755. };
  64756. getRequest.onerror = function (event) {
  64757. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64758. callback(-1);
  64759. };
  64760. }
  64761. catch (ex) {
  64762. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64763. callback(-1);
  64764. }
  64765. }
  64766. else {
  64767. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64768. callback(-1);
  64769. }
  64770. };
  64771. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64772. var _this = this;
  64773. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64774. try {
  64775. // Open a transaction to the database
  64776. var transaction = this.db.transaction(["versions"], "readwrite");
  64777. // the transaction could abort because of a QuotaExceededError error
  64778. transaction.onabort = function (event) {
  64779. try {
  64780. var error = event.srcElement['error'];
  64781. if (error && error.name === "QuotaExceededError") {
  64782. _this.hasReachedQuota = true;
  64783. }
  64784. }
  64785. catch (ex) { }
  64786. callback(-1);
  64787. };
  64788. transaction.oncomplete = function (event) {
  64789. callback(_this.manifestVersionFound);
  64790. };
  64791. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64792. // Put the scene into the database
  64793. var addRequest = transaction.objectStore("versions").put(newVersion);
  64794. addRequest.onsuccess = function (event) {
  64795. };
  64796. addRequest.onerror = function (event) {
  64797. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64798. };
  64799. }
  64800. catch (ex) {
  64801. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64802. callback(-1);
  64803. }
  64804. }
  64805. else {
  64806. callback(-1);
  64807. }
  64808. };
  64809. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64810. var _this = this;
  64811. var completeUrl = Database.ReturnFullUrlLocation(url);
  64812. var saveAndLoadFile = function () {
  64813. // the scene is not yet in the DB, let's try to save it
  64814. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64815. };
  64816. this._checkVersionFromDB(completeUrl, function (version) {
  64817. if (version !== -1) {
  64818. if (!_this.mustUpdateRessources) {
  64819. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64820. }
  64821. else {
  64822. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64823. }
  64824. }
  64825. else {
  64826. if (errorCallback) {
  64827. errorCallback();
  64828. }
  64829. }
  64830. });
  64831. };
  64832. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64833. if (this.isSupported && this.db) {
  64834. var targetStore;
  64835. if (url.indexOf(".babylon") !== -1) {
  64836. targetStore = "scenes";
  64837. }
  64838. else {
  64839. targetStore = "textures";
  64840. }
  64841. var file;
  64842. var transaction = this.db.transaction([targetStore]);
  64843. transaction.oncomplete = function (event) {
  64844. if (file) {
  64845. callback(file.data);
  64846. }
  64847. else {
  64848. notInDBCallback();
  64849. }
  64850. };
  64851. transaction.onabort = function (event) {
  64852. notInDBCallback();
  64853. };
  64854. var getRequest = transaction.objectStore(targetStore).get(url);
  64855. getRequest.onsuccess = function (event) {
  64856. file = (event.target).result;
  64857. };
  64858. getRequest.onerror = function (event) {
  64859. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64860. notInDBCallback();
  64861. };
  64862. }
  64863. else {
  64864. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64865. callback();
  64866. }
  64867. };
  64868. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64869. var _this = this;
  64870. if (this.isSupported) {
  64871. var targetStore;
  64872. if (url.indexOf(".babylon") !== -1) {
  64873. targetStore = "scenes";
  64874. }
  64875. else {
  64876. targetStore = "textures";
  64877. }
  64878. // Create XHR
  64879. var xhr = new XMLHttpRequest();
  64880. var fileData;
  64881. xhr.open("GET", url, true);
  64882. if (useArrayBuffer) {
  64883. xhr.responseType = "arraybuffer";
  64884. }
  64885. if (progressCallback) {
  64886. xhr.onprogress = progressCallback;
  64887. }
  64888. xhr.addEventListener("load", function () {
  64889. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64890. // Blob as response (XHR2)
  64891. //fileData = xhr.responseText;
  64892. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64893. if (!_this.hasReachedQuota && _this.db) {
  64894. // Open a transaction to the database
  64895. var transaction = _this.db.transaction([targetStore], "readwrite");
  64896. // the transaction could abort because of a QuotaExceededError error
  64897. transaction.onabort = function (event) {
  64898. try {
  64899. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64900. var error = event.srcElement['error'];
  64901. if (error && error.name === "QuotaExceededError") {
  64902. _this.hasReachedQuota = true;
  64903. }
  64904. }
  64905. catch (ex) { }
  64906. callback(fileData);
  64907. };
  64908. transaction.oncomplete = function (event) {
  64909. callback(fileData);
  64910. };
  64911. var newFile;
  64912. if (targetStore === "scenes") {
  64913. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64914. }
  64915. else {
  64916. newFile = { textureUrl: url, data: fileData };
  64917. }
  64918. try {
  64919. // Put the scene into the database
  64920. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64921. addRequest.onsuccess = function (event) {
  64922. };
  64923. addRequest.onerror = function (event) {
  64924. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64925. };
  64926. }
  64927. catch (ex) {
  64928. callback(fileData);
  64929. }
  64930. }
  64931. else {
  64932. callback(fileData);
  64933. }
  64934. }
  64935. else {
  64936. callback();
  64937. }
  64938. }, false);
  64939. xhr.addEventListener("error", function (event) {
  64940. BABYLON.Tools.Error("error on XHR request.");
  64941. callback();
  64942. }, false);
  64943. xhr.send();
  64944. }
  64945. else {
  64946. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64947. callback();
  64948. }
  64949. };
  64950. Database.IsUASupportingBlobStorage = true;
  64951. Database.IDBStorageEnabled = true;
  64952. Database.parseURL = function (url) {
  64953. var a = document.createElement('a');
  64954. a.href = url;
  64955. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64956. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64957. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64958. return absLocation;
  64959. };
  64960. Database.ReturnFullUrlLocation = function (url) {
  64961. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64962. return (Database.parseURL(window.location.href) + url);
  64963. }
  64964. else {
  64965. return url;
  64966. }
  64967. };
  64968. return Database;
  64969. }());
  64970. BABYLON.Database = Database;
  64971. })(BABYLON || (BABYLON = {}));
  64972. //# sourceMappingURL=babylon.database.js.map
  64973. "use strict";
  64974. var BABYLON;
  64975. (function (BABYLON) {
  64976. var FresnelParameters = /** @class */ (function () {
  64977. function FresnelParameters() {
  64978. this._isEnabled = true;
  64979. this.leftColor = BABYLON.Color3.White();
  64980. this.rightColor = BABYLON.Color3.Black();
  64981. this.bias = 0;
  64982. this.power = 1;
  64983. }
  64984. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64985. get: function () {
  64986. return this._isEnabled;
  64987. },
  64988. set: function (value) {
  64989. if (this._isEnabled === value) {
  64990. return;
  64991. }
  64992. this._isEnabled = value;
  64993. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64994. },
  64995. enumerable: true,
  64996. configurable: true
  64997. });
  64998. FresnelParameters.prototype.clone = function () {
  64999. var newFresnelParameters = new FresnelParameters();
  65000. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  65001. return newFresnelParameters;
  65002. };
  65003. FresnelParameters.prototype.serialize = function () {
  65004. var serializationObject = {};
  65005. serializationObject.isEnabled = this.isEnabled;
  65006. serializationObject.leftColor = this.leftColor.asArray();
  65007. serializationObject.rightColor = this.rightColor.asArray();
  65008. serializationObject.bias = this.bias;
  65009. serializationObject.power = this.power;
  65010. return serializationObject;
  65011. };
  65012. FresnelParameters.Parse = function (parsedFresnelParameters) {
  65013. var fresnelParameters = new FresnelParameters();
  65014. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  65015. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  65016. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  65017. fresnelParameters.bias = parsedFresnelParameters.bias;
  65018. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  65019. return fresnelParameters;
  65020. };
  65021. return FresnelParameters;
  65022. }());
  65023. BABYLON.FresnelParameters = FresnelParameters;
  65024. })(BABYLON || (BABYLON = {}));
  65025. //# sourceMappingURL=babylon.fresnelParameters.js.map
  65026. "use strict";
  65027. var BABYLON;
  65028. (function (BABYLON) {
  65029. var MultiMaterial = /** @class */ (function (_super) {
  65030. __extends(MultiMaterial, _super);
  65031. function MultiMaterial(name, scene) {
  65032. var _this = _super.call(this, name, scene, true) || this;
  65033. scene.multiMaterials.push(_this);
  65034. _this.subMaterials = new Array();
  65035. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  65036. return _this;
  65037. }
  65038. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  65039. get: function () {
  65040. return this._subMaterials;
  65041. },
  65042. set: function (value) {
  65043. this._subMaterials = value;
  65044. this._hookArray(value);
  65045. },
  65046. enumerable: true,
  65047. configurable: true
  65048. });
  65049. MultiMaterial.prototype._hookArray = function (array) {
  65050. var _this = this;
  65051. var oldPush = array.push;
  65052. array.push = function () {
  65053. var items = [];
  65054. for (var _i = 0; _i < arguments.length; _i++) {
  65055. items[_i] = arguments[_i];
  65056. }
  65057. var result = oldPush.apply(array, items);
  65058. _this._markAllSubMeshesAsTexturesDirty();
  65059. return result;
  65060. };
  65061. var oldSplice = array.splice;
  65062. array.splice = function (index, deleteCount) {
  65063. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65064. _this._markAllSubMeshesAsTexturesDirty();
  65065. return deleted;
  65066. };
  65067. };
  65068. // Properties
  65069. MultiMaterial.prototype.getSubMaterial = function (index) {
  65070. if (index < 0 || index >= this.subMaterials.length) {
  65071. return this.getScene().defaultMaterial;
  65072. }
  65073. return this.subMaterials[index];
  65074. };
  65075. MultiMaterial.prototype.getActiveTextures = function () {
  65076. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  65077. if (subMaterial) {
  65078. return subMaterial.getActiveTextures();
  65079. }
  65080. else {
  65081. return [];
  65082. }
  65083. }));
  65084. var _a;
  65085. };
  65086. // Methods
  65087. MultiMaterial.prototype.getClassName = function () {
  65088. return "MultiMaterial";
  65089. };
  65090. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  65091. for (var index = 0; index < this.subMaterials.length; index++) {
  65092. var subMaterial = this.subMaterials[index];
  65093. if (subMaterial) {
  65094. if (subMaterial.storeEffectOnSubMeshes) {
  65095. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  65096. return false;
  65097. }
  65098. continue;
  65099. }
  65100. if (!subMaterial.isReady(mesh)) {
  65101. return false;
  65102. }
  65103. }
  65104. }
  65105. return true;
  65106. };
  65107. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65108. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65109. for (var index = 0; index < this.subMaterials.length; index++) {
  65110. var subMaterial = null;
  65111. var current = this.subMaterials[index];
  65112. if (cloneChildren && current) {
  65113. subMaterial = current.clone(name + "-" + current.name);
  65114. }
  65115. else {
  65116. subMaterial = this.subMaterials[index];
  65117. }
  65118. newMultiMaterial.subMaterials.push(subMaterial);
  65119. }
  65120. return newMultiMaterial;
  65121. };
  65122. MultiMaterial.prototype.serialize = function () {
  65123. var serializationObject = {};
  65124. serializationObject.name = this.name;
  65125. serializationObject.id = this.id;
  65126. if (BABYLON.Tags) {
  65127. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65128. }
  65129. serializationObject.materials = [];
  65130. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65131. var subMat = this.subMaterials[matIndex];
  65132. if (subMat) {
  65133. serializationObject.materials.push(subMat.id);
  65134. }
  65135. else {
  65136. serializationObject.materials.push(null);
  65137. }
  65138. }
  65139. return serializationObject;
  65140. };
  65141. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65142. var scene = this.getScene();
  65143. if (!scene) {
  65144. return;
  65145. }
  65146. var index = scene.multiMaterials.indexOf(this);
  65147. if (index >= 0) {
  65148. scene.multiMaterials.splice(index, 1);
  65149. }
  65150. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65151. };
  65152. return MultiMaterial;
  65153. }(BABYLON.Material));
  65154. BABYLON.MultiMaterial = MultiMaterial;
  65155. })(BABYLON || (BABYLON = {}));
  65156. //# sourceMappingURL=babylon.multiMaterial.js.map
  65157. "use strict";
  65158. var BABYLON;
  65159. (function (BABYLON) {
  65160. var FreeCameraTouchInput = /** @class */ (function () {
  65161. function FreeCameraTouchInput() {
  65162. this._offsetX = null;
  65163. this._offsetY = null;
  65164. this._pointerPressed = new Array();
  65165. this.touchAngularSensibility = 200000.0;
  65166. this.touchMoveSensibility = 250.0;
  65167. }
  65168. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65169. var _this = this;
  65170. var previousPosition = null;
  65171. if (this._pointerInput === undefined) {
  65172. this._onLostFocus = function (evt) {
  65173. _this._offsetX = null;
  65174. _this._offsetY = null;
  65175. };
  65176. this._pointerInput = function (p, s) {
  65177. var evt = p.event;
  65178. if (evt.pointerType === "mouse") {
  65179. return;
  65180. }
  65181. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65182. if (!noPreventDefault) {
  65183. evt.preventDefault();
  65184. }
  65185. _this._pointerPressed.push(evt.pointerId);
  65186. if (_this._pointerPressed.length !== 1) {
  65187. return;
  65188. }
  65189. previousPosition = {
  65190. x: evt.clientX,
  65191. y: evt.clientY
  65192. };
  65193. }
  65194. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65195. if (!noPreventDefault) {
  65196. evt.preventDefault();
  65197. }
  65198. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65199. if (index === -1) {
  65200. return;
  65201. }
  65202. _this._pointerPressed.splice(index, 1);
  65203. if (index != 0) {
  65204. return;
  65205. }
  65206. previousPosition = null;
  65207. _this._offsetX = null;
  65208. _this._offsetY = null;
  65209. }
  65210. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65211. if (!noPreventDefault) {
  65212. evt.preventDefault();
  65213. }
  65214. if (!previousPosition) {
  65215. return;
  65216. }
  65217. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65218. if (index != 0) {
  65219. return;
  65220. }
  65221. _this._offsetX = evt.clientX - previousPosition.x;
  65222. _this._offsetY = -(evt.clientY - previousPosition.y);
  65223. }
  65224. };
  65225. }
  65226. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65227. if (this._onLostFocus) {
  65228. element.addEventListener("blur", this._onLostFocus);
  65229. }
  65230. };
  65231. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65232. if (this._pointerInput && element) {
  65233. if (this._observer) {
  65234. this.camera.getScene().onPointerObservable.remove(this._observer);
  65235. this._observer = null;
  65236. }
  65237. if (this._onLostFocus) {
  65238. element.removeEventListener("blur", this._onLostFocus);
  65239. this._onLostFocus = null;
  65240. }
  65241. this._pointerPressed = [];
  65242. this._offsetX = null;
  65243. this._offsetY = null;
  65244. }
  65245. };
  65246. FreeCameraTouchInput.prototype.checkInputs = function () {
  65247. if (this._offsetX && this._offsetY) {
  65248. var camera = this.camera;
  65249. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65250. if (this._pointerPressed.length > 1) {
  65251. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65252. }
  65253. else {
  65254. var speed = camera._computeLocalCameraSpeed();
  65255. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65256. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65257. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65258. }
  65259. }
  65260. };
  65261. FreeCameraTouchInput.prototype.getClassName = function () {
  65262. return "FreeCameraTouchInput";
  65263. };
  65264. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65265. return "touch";
  65266. };
  65267. __decorate([
  65268. BABYLON.serialize()
  65269. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65270. __decorate([
  65271. BABYLON.serialize()
  65272. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65273. return FreeCameraTouchInput;
  65274. }());
  65275. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65276. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65277. })(BABYLON || (BABYLON = {}));
  65278. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65279. "use strict";
  65280. var BABYLON;
  65281. (function (BABYLON) {
  65282. // We're mainly based on the logic defined into the FreeCamera code
  65283. var TouchCamera = /** @class */ (function (_super) {
  65284. __extends(TouchCamera, _super);
  65285. //-- end properties for backward compatibility for inputs
  65286. function TouchCamera(name, position, scene) {
  65287. var _this = _super.call(this, name, position, scene) || this;
  65288. _this.inputs.addTouch();
  65289. _this._setupInputs();
  65290. return _this;
  65291. }
  65292. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65293. //-- Begin properties for backward compatibility for inputs
  65294. get: function () {
  65295. var touch = this.inputs.attached["touch"];
  65296. if (touch)
  65297. return touch.touchAngularSensibility;
  65298. return 0;
  65299. },
  65300. set: function (value) {
  65301. var touch = this.inputs.attached["touch"];
  65302. if (touch)
  65303. touch.touchAngularSensibility = value;
  65304. },
  65305. enumerable: true,
  65306. configurable: true
  65307. });
  65308. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65309. get: function () {
  65310. var touch = this.inputs.attached["touch"];
  65311. if (touch)
  65312. return touch.touchMoveSensibility;
  65313. return 0;
  65314. },
  65315. set: function (value) {
  65316. var touch = this.inputs.attached["touch"];
  65317. if (touch)
  65318. touch.touchMoveSensibility = value;
  65319. },
  65320. enumerable: true,
  65321. configurable: true
  65322. });
  65323. TouchCamera.prototype.getClassName = function () {
  65324. return "TouchCamera";
  65325. };
  65326. TouchCamera.prototype._setupInputs = function () {
  65327. var mouse = this.inputs.attached["mouse"];
  65328. if (mouse) {
  65329. mouse.touchEnabled = false;
  65330. }
  65331. };
  65332. return TouchCamera;
  65333. }(BABYLON.FreeCamera));
  65334. BABYLON.TouchCamera = TouchCamera;
  65335. })(BABYLON || (BABYLON = {}));
  65336. //# sourceMappingURL=babylon.touchCamera.js.map
  65337. "use strict";
  65338. var BABYLON;
  65339. (function (BABYLON) {
  65340. var ProceduralTexture = /** @class */ (function (_super) {
  65341. __extends(ProceduralTexture, _super);
  65342. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65343. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65344. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65345. if (isCube === void 0) { isCube = false; }
  65346. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65347. _this.isCube = isCube;
  65348. _this.isEnabled = true;
  65349. _this._currentRefreshId = -1;
  65350. _this._refreshRate = 1;
  65351. _this._vertexBuffers = {};
  65352. _this._uniforms = new Array();
  65353. _this._samplers = new Array();
  65354. _this._textures = {};
  65355. _this._floats = {};
  65356. _this._floatsArrays = {};
  65357. _this._colors3 = {};
  65358. _this._colors4 = {};
  65359. _this._vectors2 = {};
  65360. _this._vectors3 = {};
  65361. _this._matrices = {};
  65362. _this._fallbackTextureUsed = false;
  65363. scene._proceduralTextures.push(_this);
  65364. _this._engine = scene.getEngine();
  65365. _this.name = name;
  65366. _this.isRenderTarget = true;
  65367. _this._size = size;
  65368. _this._generateMipMaps = generateMipMaps;
  65369. _this.setFragment(fragment);
  65370. _this._fallbackTexture = fallbackTexture;
  65371. if (isCube) {
  65372. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65373. _this.setFloat("face", 0);
  65374. }
  65375. else {
  65376. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65377. }
  65378. // VBO
  65379. var vertices = [];
  65380. vertices.push(1, 1);
  65381. vertices.push(-1, 1);
  65382. vertices.push(-1, -1);
  65383. vertices.push(1, -1);
  65384. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65385. _this._createIndexBuffer();
  65386. return _this;
  65387. }
  65388. ProceduralTexture.prototype._createIndexBuffer = function () {
  65389. var engine = this._engine;
  65390. // Indices
  65391. var indices = [];
  65392. indices.push(0);
  65393. indices.push(1);
  65394. indices.push(2);
  65395. indices.push(0);
  65396. indices.push(2);
  65397. indices.push(3);
  65398. this._indexBuffer = engine.createIndexBuffer(indices);
  65399. };
  65400. ProceduralTexture.prototype._rebuild = function () {
  65401. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65402. if (vb) {
  65403. vb._rebuild();
  65404. }
  65405. this._createIndexBuffer();
  65406. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65407. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65408. }
  65409. };
  65410. ProceduralTexture.prototype.reset = function () {
  65411. if (this._effect === undefined) {
  65412. return;
  65413. }
  65414. var engine = this._engine;
  65415. engine._releaseEffect(this._effect);
  65416. };
  65417. ProceduralTexture.prototype.isReady = function () {
  65418. var _this = this;
  65419. var engine = this._engine;
  65420. var shaders;
  65421. if (!this._fragment) {
  65422. return false;
  65423. }
  65424. if (this._fallbackTextureUsed) {
  65425. return true;
  65426. }
  65427. if (this._fragment.fragmentElement !== undefined) {
  65428. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65429. }
  65430. else {
  65431. shaders = { vertex: "procedural", fragment: this._fragment };
  65432. }
  65433. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65434. _this.releaseInternalTexture();
  65435. if (_this._fallbackTexture) {
  65436. _this._texture = _this._fallbackTexture._texture;
  65437. if (_this._texture) {
  65438. _this._texture.incrementReferences();
  65439. }
  65440. }
  65441. _this._fallbackTextureUsed = true;
  65442. });
  65443. return this._effect.isReady();
  65444. };
  65445. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65446. this._currentRefreshId = -1;
  65447. };
  65448. ProceduralTexture.prototype.setFragment = function (fragment) {
  65449. this._fragment = fragment;
  65450. };
  65451. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65452. get: function () {
  65453. return this._refreshRate;
  65454. },
  65455. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65456. set: function (value) {
  65457. this._refreshRate = value;
  65458. this.resetRefreshCounter();
  65459. },
  65460. enumerable: true,
  65461. configurable: true
  65462. });
  65463. ProceduralTexture.prototype._shouldRender = function () {
  65464. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65465. return false;
  65466. }
  65467. if (this._fallbackTextureUsed) {
  65468. return false;
  65469. }
  65470. if (this._currentRefreshId === -1) {
  65471. this._currentRefreshId = 1;
  65472. return true;
  65473. }
  65474. if (this.refreshRate === this._currentRefreshId) {
  65475. this._currentRefreshId = 1;
  65476. return true;
  65477. }
  65478. this._currentRefreshId++;
  65479. return false;
  65480. };
  65481. ProceduralTexture.prototype.getRenderSize = function () {
  65482. return this._size;
  65483. };
  65484. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65485. if (this._fallbackTextureUsed) {
  65486. return;
  65487. }
  65488. this.releaseInternalTexture();
  65489. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65490. };
  65491. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65492. if (this._uniforms.indexOf(uniformName) === -1) {
  65493. this._uniforms.push(uniformName);
  65494. }
  65495. };
  65496. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65497. if (this._samplers.indexOf(name) === -1) {
  65498. this._samplers.push(name);
  65499. }
  65500. this._textures[name] = texture;
  65501. return this;
  65502. };
  65503. ProceduralTexture.prototype.setFloat = function (name, value) {
  65504. this._checkUniform(name);
  65505. this._floats[name] = value;
  65506. return this;
  65507. };
  65508. ProceduralTexture.prototype.setFloats = function (name, value) {
  65509. this._checkUniform(name);
  65510. this._floatsArrays[name] = value;
  65511. return this;
  65512. };
  65513. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65514. this._checkUniform(name);
  65515. this._colors3[name] = value;
  65516. return this;
  65517. };
  65518. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65519. this._checkUniform(name);
  65520. this._colors4[name] = value;
  65521. return this;
  65522. };
  65523. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65524. this._checkUniform(name);
  65525. this._vectors2[name] = value;
  65526. return this;
  65527. };
  65528. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65529. this._checkUniform(name);
  65530. this._vectors3[name] = value;
  65531. return this;
  65532. };
  65533. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65534. this._checkUniform(name);
  65535. this._matrices[name] = value;
  65536. return this;
  65537. };
  65538. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65539. var scene = this.getScene();
  65540. if (!scene) {
  65541. return;
  65542. }
  65543. var engine = this._engine;
  65544. // Render
  65545. engine.enableEffect(this._effect);
  65546. engine.setState(false);
  65547. // Texture
  65548. for (var name in this._textures) {
  65549. this._effect.setTexture(name, this._textures[name]);
  65550. }
  65551. // Float
  65552. for (name in this._floats) {
  65553. this._effect.setFloat(name, this._floats[name]);
  65554. }
  65555. // Floats
  65556. for (name in this._floatsArrays) {
  65557. this._effect.setArray(name, this._floatsArrays[name]);
  65558. }
  65559. // Color3
  65560. for (name in this._colors3) {
  65561. this._effect.setColor3(name, this._colors3[name]);
  65562. }
  65563. // Color4
  65564. for (name in this._colors4) {
  65565. var color = this._colors4[name];
  65566. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65567. }
  65568. // Vector2
  65569. for (name in this._vectors2) {
  65570. this._effect.setVector2(name, this._vectors2[name]);
  65571. }
  65572. // Vector3
  65573. for (name in this._vectors3) {
  65574. this._effect.setVector3(name, this._vectors3[name]);
  65575. }
  65576. // Matrix
  65577. for (name in this._matrices) {
  65578. this._effect.setMatrix(name, this._matrices[name]);
  65579. }
  65580. if (!this._texture) {
  65581. return;
  65582. }
  65583. if (this.isCube) {
  65584. for (var face = 0; face < 6; face++) {
  65585. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65586. // VBOs
  65587. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65588. this._effect.setFloat("face", face);
  65589. // Clear
  65590. engine.clear(scene.clearColor, true, true, true);
  65591. // Draw order
  65592. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65593. // Mipmaps
  65594. if (face === 5) {
  65595. engine.generateMipMapsForCubemap(this._texture);
  65596. }
  65597. }
  65598. }
  65599. else {
  65600. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65601. // VBOs
  65602. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65603. // Clear
  65604. engine.clear(scene.clearColor, true, true, true);
  65605. // Draw order
  65606. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65607. }
  65608. // Unbind
  65609. engine.unBindFramebuffer(this._texture, this.isCube);
  65610. if (this.onGenerated) {
  65611. this.onGenerated();
  65612. }
  65613. };
  65614. ProceduralTexture.prototype.clone = function () {
  65615. var textureSize = this.getSize();
  65616. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65617. // Base texture
  65618. newTexture.hasAlpha = this.hasAlpha;
  65619. newTexture.level = this.level;
  65620. // RenderTarget Texture
  65621. newTexture.coordinatesMode = this.coordinatesMode;
  65622. return newTexture;
  65623. };
  65624. ProceduralTexture.prototype.dispose = function () {
  65625. var scene = this.getScene();
  65626. if (!scene) {
  65627. return;
  65628. }
  65629. var index = scene._proceduralTextures.indexOf(this);
  65630. if (index >= 0) {
  65631. scene._proceduralTextures.splice(index, 1);
  65632. }
  65633. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65634. if (vertexBuffer) {
  65635. vertexBuffer.dispose();
  65636. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65637. }
  65638. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65639. this._indexBuffer = null;
  65640. }
  65641. _super.prototype.dispose.call(this);
  65642. };
  65643. return ProceduralTexture;
  65644. }(BABYLON.Texture));
  65645. BABYLON.ProceduralTexture = ProceduralTexture;
  65646. })(BABYLON || (BABYLON = {}));
  65647. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65648. "use strict";
  65649. var BABYLON;
  65650. (function (BABYLON) {
  65651. var CustomProceduralTexture = /** @class */ (function (_super) {
  65652. __extends(CustomProceduralTexture, _super);
  65653. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65654. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65655. _this._animate = true;
  65656. _this._time = 0;
  65657. _this._texturePath = texturePath;
  65658. //Try to load json
  65659. _this.loadJson(texturePath);
  65660. _this.refreshRate = 1;
  65661. return _this;
  65662. }
  65663. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65664. var _this = this;
  65665. var noConfigFile = function () {
  65666. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65667. try {
  65668. _this.setFragment(_this._texturePath);
  65669. }
  65670. catch (ex) {
  65671. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65672. }
  65673. };
  65674. var configFileUrl = jsonUrl + "/config.json";
  65675. var xhr = new XMLHttpRequest();
  65676. xhr.open("GET", configFileUrl, true);
  65677. xhr.addEventListener("load", function () {
  65678. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65679. try {
  65680. _this._config = JSON.parse(xhr.response);
  65681. _this.updateShaderUniforms();
  65682. _this.updateTextures();
  65683. _this.setFragment(_this._texturePath + "/custom");
  65684. _this._animate = _this._config.animate;
  65685. _this.refreshRate = _this._config.refreshrate;
  65686. }
  65687. catch (ex) {
  65688. noConfigFile();
  65689. }
  65690. }
  65691. else {
  65692. noConfigFile();
  65693. }
  65694. }, false);
  65695. xhr.addEventListener("error", function () {
  65696. noConfigFile();
  65697. }, false);
  65698. try {
  65699. xhr.send();
  65700. }
  65701. catch (ex) {
  65702. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65703. }
  65704. };
  65705. CustomProceduralTexture.prototype.isReady = function () {
  65706. if (!_super.prototype.isReady.call(this)) {
  65707. return false;
  65708. }
  65709. for (var name in this._textures) {
  65710. var texture = this._textures[name];
  65711. if (!texture.isReady()) {
  65712. return false;
  65713. }
  65714. }
  65715. return true;
  65716. };
  65717. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65718. var scene = this.getScene();
  65719. if (this._animate && scene) {
  65720. this._time += scene.getAnimationRatio() * 0.03;
  65721. this.updateShaderUniforms();
  65722. }
  65723. _super.prototype.render.call(this, useCameraPostProcess);
  65724. };
  65725. CustomProceduralTexture.prototype.updateTextures = function () {
  65726. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65727. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65728. }
  65729. };
  65730. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65731. if (this._config) {
  65732. for (var j = 0; j < this._config.uniforms.length; j++) {
  65733. var uniform = this._config.uniforms[j];
  65734. switch (uniform.type) {
  65735. case "float":
  65736. this.setFloat(uniform.name, uniform.value);
  65737. break;
  65738. case "color3":
  65739. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65740. break;
  65741. case "color4":
  65742. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65743. break;
  65744. case "vector2":
  65745. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65746. break;
  65747. case "vector3":
  65748. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65749. break;
  65750. }
  65751. }
  65752. }
  65753. this.setFloat("time", this._time);
  65754. };
  65755. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65756. get: function () {
  65757. return this._animate;
  65758. },
  65759. set: function (value) {
  65760. this._animate = value;
  65761. },
  65762. enumerable: true,
  65763. configurable: true
  65764. });
  65765. return CustomProceduralTexture;
  65766. }(BABYLON.ProceduralTexture));
  65767. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65768. })(BABYLON || (BABYLON = {}));
  65769. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65770. "use strict";
  65771. var BABYLON;
  65772. (function (BABYLON) {
  65773. var FreeCameraGamepadInput = /** @class */ (function () {
  65774. function FreeCameraGamepadInput() {
  65775. this.gamepadAngularSensibility = 200;
  65776. this.gamepadMoveSensibility = 40;
  65777. // private members
  65778. this._cameraTransform = BABYLON.Matrix.Identity();
  65779. this._deltaTransform = BABYLON.Vector3.Zero();
  65780. this._vector3 = BABYLON.Vector3.Zero();
  65781. this._vector2 = BABYLON.Vector2.Zero();
  65782. }
  65783. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65784. var _this = this;
  65785. var manager = this.camera.getScene().gamepadManager;
  65786. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65787. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65788. // prioritize XBOX gamepads.
  65789. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65790. _this.gamepad = gamepad;
  65791. }
  65792. }
  65793. });
  65794. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65795. if (_this.gamepad === gamepad) {
  65796. _this.gamepad = null;
  65797. }
  65798. });
  65799. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65800. };
  65801. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65802. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65803. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65804. this.gamepad = null;
  65805. };
  65806. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65807. if (this.gamepad && this.gamepad.leftStick) {
  65808. var camera = this.camera;
  65809. var LSValues = this.gamepad.leftStick;
  65810. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65811. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65812. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65813. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65814. var RSValues = this.gamepad.rightStick;
  65815. if (RSValues) {
  65816. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65817. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65818. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65819. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65820. }
  65821. else {
  65822. RSValues = { x: 0, y: 0 };
  65823. }
  65824. if (!camera.rotationQuaternion) {
  65825. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65826. }
  65827. else {
  65828. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65829. }
  65830. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65831. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65832. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65833. camera.cameraDirection.addInPlace(this._deltaTransform);
  65834. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65835. camera.cameraRotation.addInPlace(this._vector2);
  65836. }
  65837. };
  65838. FreeCameraGamepadInput.prototype.getClassName = function () {
  65839. return "FreeCameraGamepadInput";
  65840. };
  65841. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65842. return "gamepad";
  65843. };
  65844. __decorate([
  65845. BABYLON.serialize()
  65846. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65847. __decorate([
  65848. BABYLON.serialize()
  65849. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65850. return FreeCameraGamepadInput;
  65851. }());
  65852. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65853. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65854. })(BABYLON || (BABYLON = {}));
  65855. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65856. "use strict";
  65857. var BABYLON;
  65858. (function (BABYLON) {
  65859. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65860. function ArcRotateCameraGamepadInput() {
  65861. this.gamepadRotationSensibility = 80;
  65862. this.gamepadMoveSensibility = 40;
  65863. }
  65864. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65865. var _this = this;
  65866. var manager = this.camera.getScene().gamepadManager;
  65867. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65868. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65869. // prioritize XBOX gamepads.
  65870. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65871. _this.gamepad = gamepad;
  65872. }
  65873. }
  65874. });
  65875. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65876. if (_this.gamepad === gamepad) {
  65877. _this.gamepad = null;
  65878. }
  65879. });
  65880. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65881. };
  65882. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65883. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65884. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65885. this.gamepad = null;
  65886. };
  65887. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65888. if (this.gamepad) {
  65889. var camera = this.camera;
  65890. var RSValues = this.gamepad.rightStick;
  65891. if (RSValues) {
  65892. if (RSValues.x != 0) {
  65893. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65894. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65895. camera.inertialAlphaOffset += normalizedRX;
  65896. }
  65897. }
  65898. if (RSValues.y != 0) {
  65899. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65900. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65901. camera.inertialBetaOffset += normalizedRY;
  65902. }
  65903. }
  65904. }
  65905. var LSValues = this.gamepad.leftStick;
  65906. if (LSValues && LSValues.y != 0) {
  65907. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65908. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65909. this.camera.inertialRadiusOffset -= normalizedLY;
  65910. }
  65911. }
  65912. }
  65913. };
  65914. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65915. return "ArcRotateCameraGamepadInput";
  65916. };
  65917. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65918. return "gamepad";
  65919. };
  65920. __decorate([
  65921. BABYLON.serialize()
  65922. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65923. __decorate([
  65924. BABYLON.serialize()
  65925. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65926. return ArcRotateCameraGamepadInput;
  65927. }());
  65928. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65929. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65930. })(BABYLON || (BABYLON = {}));
  65931. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65932. "use strict";
  65933. var BABYLON;
  65934. (function (BABYLON) {
  65935. var GamepadManager = /** @class */ (function () {
  65936. function GamepadManager(_scene) {
  65937. var _this = this;
  65938. this._scene = _scene;
  65939. this._babylonGamepads = [];
  65940. this._oneGamepadConnected = false;
  65941. this._isMonitoring = false;
  65942. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65943. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65944. this._gamepadEventSupported = false;
  65945. }
  65946. else {
  65947. this._gamepadEventSupported = 'GamepadEvent' in window;
  65948. this._gamepadSupport = (navigator.getGamepads ||
  65949. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65950. }
  65951. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65952. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65953. for (var i in _this._babylonGamepads) {
  65954. var gamepad = _this._babylonGamepads[i];
  65955. if (gamepad && gamepad._isConnected) {
  65956. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65957. }
  65958. }
  65959. });
  65960. this._onGamepadConnectedEvent = function (evt) {
  65961. var gamepad = evt.gamepad;
  65962. if (gamepad.index in _this._babylonGamepads) {
  65963. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65964. return;
  65965. }
  65966. }
  65967. var newGamepad;
  65968. if (_this._babylonGamepads[gamepad.index]) {
  65969. newGamepad = _this._babylonGamepads[gamepad.index];
  65970. newGamepad.browserGamepad = gamepad;
  65971. newGamepad._isConnected = true;
  65972. }
  65973. else {
  65974. newGamepad = _this._addNewGamepad(gamepad);
  65975. }
  65976. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65977. _this._startMonitoringGamepads();
  65978. };
  65979. this._onGamepadDisconnectedEvent = function (evt) {
  65980. var gamepad = evt.gamepad;
  65981. // Remove the gamepad from the list of gamepads to monitor.
  65982. for (var i in _this._babylonGamepads) {
  65983. if (_this._babylonGamepads[i].index === gamepad.index) {
  65984. var disconnectedGamepad = _this._babylonGamepads[i];
  65985. disconnectedGamepad._isConnected = false;
  65986. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65987. break;
  65988. }
  65989. }
  65990. };
  65991. if (this._gamepadSupport) {
  65992. //first add already-connected gamepads
  65993. this._updateGamepadObjects();
  65994. if (this._babylonGamepads.length) {
  65995. this._startMonitoringGamepads();
  65996. }
  65997. // Checking if the gamepad connected event is supported (like in Firefox)
  65998. if (this._gamepadEventSupported) {
  65999. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  66000. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  66001. }
  66002. else {
  66003. this._startMonitoringGamepads();
  66004. }
  66005. }
  66006. }
  66007. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  66008. get: function () {
  66009. return this._babylonGamepads;
  66010. },
  66011. enumerable: true,
  66012. configurable: true
  66013. });
  66014. GamepadManager.prototype.getGamepadByType = function (type) {
  66015. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  66016. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  66017. var gamepad = _a[_i];
  66018. if (gamepad && gamepad.type === type) {
  66019. return gamepad;
  66020. }
  66021. }
  66022. return null;
  66023. };
  66024. GamepadManager.prototype.dispose = function () {
  66025. if (this._gamepadEventSupported) {
  66026. if (this._onGamepadConnectedEvent) {
  66027. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  66028. }
  66029. if (this._onGamepadDisconnectedEvent) {
  66030. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  66031. }
  66032. this._onGamepadConnectedEvent = null;
  66033. this._onGamepadDisconnectedEvent = null;
  66034. }
  66035. this._babylonGamepads.forEach(function (gamepad) {
  66036. gamepad.dispose();
  66037. });
  66038. this.onGamepadConnectedObservable.clear();
  66039. this.onGamepadDisconnectedObservable.clear();
  66040. this._oneGamepadConnected = false;
  66041. this._stopMonitoringGamepads();
  66042. this._babylonGamepads = [];
  66043. };
  66044. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  66045. if (!this._oneGamepadConnected) {
  66046. this._oneGamepadConnected = true;
  66047. }
  66048. var newGamepad;
  66049. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  66050. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  66051. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  66052. }
  66053. else if (gamepad.pose) {
  66054. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  66055. }
  66056. else {
  66057. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  66058. }
  66059. this._babylonGamepads[newGamepad.index] = newGamepad;
  66060. return newGamepad;
  66061. };
  66062. GamepadManager.prototype._startMonitoringGamepads = function () {
  66063. if (!this._isMonitoring) {
  66064. this._isMonitoring = true;
  66065. //back-comp
  66066. if (!this._scene) {
  66067. this._checkGamepadsStatus();
  66068. }
  66069. }
  66070. };
  66071. GamepadManager.prototype._stopMonitoringGamepads = function () {
  66072. this._isMonitoring = false;
  66073. };
  66074. GamepadManager.prototype._checkGamepadsStatus = function () {
  66075. var _this = this;
  66076. // Hack to be compatible Chrome
  66077. this._updateGamepadObjects();
  66078. for (var i in this._babylonGamepads) {
  66079. var gamepad = this._babylonGamepads[i];
  66080. if (!gamepad || !gamepad.isConnected) {
  66081. continue;
  66082. }
  66083. gamepad.update();
  66084. }
  66085. if (this._isMonitoring && !this._scene) {
  66086. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  66087. }
  66088. };
  66089. // This function is called only on Chrome, which does not properly support
  66090. // connection/disconnection events and forces you to recopy again the gamepad object
  66091. GamepadManager.prototype._updateGamepadObjects = function () {
  66092. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  66093. for (var i = 0; i < gamepads.length; i++) {
  66094. if (gamepads[i]) {
  66095. if (!this._babylonGamepads[gamepads[i].index]) {
  66096. var newGamepad = this._addNewGamepad(gamepads[i]);
  66097. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66098. }
  66099. else {
  66100. // Forced to copy again this object for Chrome for unknown reason
  66101. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66102. if (!this._babylonGamepads[i].isConnected) {
  66103. this._babylonGamepads[i]._isConnected = true;
  66104. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66105. }
  66106. }
  66107. }
  66108. }
  66109. };
  66110. return GamepadManager;
  66111. }());
  66112. BABYLON.GamepadManager = GamepadManager;
  66113. })(BABYLON || (BABYLON = {}));
  66114. //# sourceMappingURL=babylon.gamepadManager.js.map
  66115. "use strict";
  66116. var BABYLON;
  66117. (function (BABYLON) {
  66118. var StickValues = /** @class */ (function () {
  66119. function StickValues(x, y) {
  66120. this.x = x;
  66121. this.y = y;
  66122. }
  66123. return StickValues;
  66124. }());
  66125. BABYLON.StickValues = StickValues;
  66126. var Gamepad = /** @class */ (function () {
  66127. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66128. if (leftStickX === void 0) { leftStickX = 0; }
  66129. if (leftStickY === void 0) { leftStickY = 1; }
  66130. if (rightStickX === void 0) { rightStickX = 2; }
  66131. if (rightStickY === void 0) { rightStickY = 3; }
  66132. this.id = id;
  66133. this.index = index;
  66134. this.browserGamepad = browserGamepad;
  66135. this._isConnected = true;
  66136. this._invertLeftStickY = false;
  66137. this.type = Gamepad.GAMEPAD;
  66138. this._leftStickAxisX = leftStickX;
  66139. this._leftStickAxisY = leftStickY;
  66140. this._rightStickAxisX = rightStickX;
  66141. this._rightStickAxisY = rightStickY;
  66142. if (this.browserGamepad.axes.length >= 2) {
  66143. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66144. }
  66145. if (this.browserGamepad.axes.length >= 4) {
  66146. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66147. }
  66148. }
  66149. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66150. get: function () {
  66151. return this._isConnected;
  66152. },
  66153. enumerable: true,
  66154. configurable: true
  66155. });
  66156. Gamepad.prototype.onleftstickchanged = function (callback) {
  66157. this._onleftstickchanged = callback;
  66158. };
  66159. Gamepad.prototype.onrightstickchanged = function (callback) {
  66160. this._onrightstickchanged = callback;
  66161. };
  66162. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66163. get: function () {
  66164. return this._leftStick;
  66165. },
  66166. set: function (newValues) {
  66167. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66168. this._onleftstickchanged(newValues);
  66169. }
  66170. this._leftStick = newValues;
  66171. },
  66172. enumerable: true,
  66173. configurable: true
  66174. });
  66175. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66176. get: function () {
  66177. return this._rightStick;
  66178. },
  66179. set: function (newValues) {
  66180. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66181. this._onrightstickchanged(newValues);
  66182. }
  66183. this._rightStick = newValues;
  66184. },
  66185. enumerable: true,
  66186. configurable: true
  66187. });
  66188. Gamepad.prototype.update = function () {
  66189. if (this._leftStick) {
  66190. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66191. if (this._invertLeftStickY) {
  66192. this.leftStick.y *= -1;
  66193. }
  66194. }
  66195. if (this._rightStick) {
  66196. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66197. }
  66198. };
  66199. Gamepad.prototype.dispose = function () {
  66200. };
  66201. Gamepad.GAMEPAD = 0;
  66202. Gamepad.GENERIC = 1;
  66203. Gamepad.XBOX = 2;
  66204. Gamepad.POSE_ENABLED = 3;
  66205. return Gamepad;
  66206. }());
  66207. BABYLON.Gamepad = Gamepad;
  66208. var GenericPad = /** @class */ (function (_super) {
  66209. __extends(GenericPad, _super);
  66210. function GenericPad(id, index, browserGamepad) {
  66211. var _this = _super.call(this, id, index, browserGamepad) || this;
  66212. _this.onButtonDownObservable = new BABYLON.Observable();
  66213. _this.onButtonUpObservable = new BABYLON.Observable();
  66214. _this.type = Gamepad.GENERIC;
  66215. _this._buttons = new Array(browserGamepad.buttons.length);
  66216. return _this;
  66217. }
  66218. GenericPad.prototype.onbuttondown = function (callback) {
  66219. this._onbuttondown = callback;
  66220. };
  66221. GenericPad.prototype.onbuttonup = function (callback) {
  66222. this._onbuttonup = callback;
  66223. };
  66224. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66225. if (newValue !== currentValue) {
  66226. if (newValue === 1) {
  66227. if (this._onbuttondown) {
  66228. this._onbuttondown(buttonIndex);
  66229. }
  66230. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66231. }
  66232. if (newValue === 0) {
  66233. if (this._onbuttonup) {
  66234. this._onbuttonup(buttonIndex);
  66235. }
  66236. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66237. }
  66238. }
  66239. return newValue;
  66240. };
  66241. GenericPad.prototype.update = function () {
  66242. _super.prototype.update.call(this);
  66243. for (var index = 0; index < this._buttons.length; index++) {
  66244. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66245. }
  66246. };
  66247. GenericPad.prototype.dispose = function () {
  66248. _super.prototype.dispose.call(this);
  66249. this.onButtonDownObservable.clear();
  66250. this.onButtonUpObservable.clear();
  66251. };
  66252. return GenericPad;
  66253. }(Gamepad));
  66254. BABYLON.GenericPad = GenericPad;
  66255. })(BABYLON || (BABYLON = {}));
  66256. //# sourceMappingURL=babylon.gamepad.js.map
  66257. "use strict";
  66258. var BABYLON;
  66259. (function (BABYLON) {
  66260. var Xbox360Button;
  66261. (function (Xbox360Button) {
  66262. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66263. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66264. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66265. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66266. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66267. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66268. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66269. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66270. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66271. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66272. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66273. var Xbox360Dpad;
  66274. (function (Xbox360Dpad) {
  66275. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66276. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66277. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66278. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66279. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66280. var Xbox360Pad = /** @class */ (function (_super) {
  66281. __extends(Xbox360Pad, _super);
  66282. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66283. if (xboxOne === void 0) { xboxOne = false; }
  66284. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66285. _this._leftTrigger = 0;
  66286. _this._rightTrigger = 0;
  66287. _this.onButtonDownObservable = new BABYLON.Observable();
  66288. _this.onButtonUpObservable = new BABYLON.Observable();
  66289. _this.onPadDownObservable = new BABYLON.Observable();
  66290. _this.onPadUpObservable = new BABYLON.Observable();
  66291. _this._buttonA = 0;
  66292. _this._buttonB = 0;
  66293. _this._buttonX = 0;
  66294. _this._buttonY = 0;
  66295. _this._buttonBack = 0;
  66296. _this._buttonStart = 0;
  66297. _this._buttonLB = 0;
  66298. _this._buttonRB = 0;
  66299. _this._buttonLeftStick = 0;
  66300. _this._buttonRightStick = 0;
  66301. _this._dPadUp = 0;
  66302. _this._dPadDown = 0;
  66303. _this._dPadLeft = 0;
  66304. _this._dPadRight = 0;
  66305. _this._isXboxOnePad = false;
  66306. _this.type = BABYLON.Gamepad.XBOX;
  66307. _this._isXboxOnePad = xboxOne;
  66308. return _this;
  66309. }
  66310. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66311. this._onlefttriggerchanged = callback;
  66312. };
  66313. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66314. this._onrighttriggerchanged = callback;
  66315. };
  66316. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66317. get: function () {
  66318. return this._leftTrigger;
  66319. },
  66320. set: function (newValue) {
  66321. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66322. this._onlefttriggerchanged(newValue);
  66323. }
  66324. this._leftTrigger = newValue;
  66325. },
  66326. enumerable: true,
  66327. configurable: true
  66328. });
  66329. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66330. get: function () {
  66331. return this._rightTrigger;
  66332. },
  66333. set: function (newValue) {
  66334. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66335. this._onrighttriggerchanged(newValue);
  66336. }
  66337. this._rightTrigger = newValue;
  66338. },
  66339. enumerable: true,
  66340. configurable: true
  66341. });
  66342. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66343. this._onbuttondown = callback;
  66344. };
  66345. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66346. this._onbuttonup = callback;
  66347. };
  66348. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66349. this._ondpaddown = callback;
  66350. };
  66351. Xbox360Pad.prototype.ondpadup = function (callback) {
  66352. this._ondpadup = callback;
  66353. };
  66354. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66355. if (newValue !== currentValue) {
  66356. if (newValue === 1) {
  66357. if (this._onbuttondown) {
  66358. this._onbuttondown(buttonType);
  66359. }
  66360. this.onButtonDownObservable.notifyObservers(buttonType);
  66361. }
  66362. if (newValue === 0) {
  66363. if (this._onbuttonup) {
  66364. this._onbuttonup(buttonType);
  66365. }
  66366. this.onButtonUpObservable.notifyObservers(buttonType);
  66367. }
  66368. }
  66369. return newValue;
  66370. };
  66371. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66372. if (newValue !== currentValue) {
  66373. if (newValue === 1) {
  66374. if (this._ondpaddown) {
  66375. this._ondpaddown(buttonType);
  66376. }
  66377. this.onPadDownObservable.notifyObservers(buttonType);
  66378. }
  66379. if (newValue === 0) {
  66380. if (this._ondpadup) {
  66381. this._ondpadup(buttonType);
  66382. }
  66383. this.onPadUpObservable.notifyObservers(buttonType);
  66384. }
  66385. }
  66386. return newValue;
  66387. };
  66388. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66389. get: function () {
  66390. return this._buttonA;
  66391. },
  66392. set: function (value) {
  66393. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66394. },
  66395. enumerable: true,
  66396. configurable: true
  66397. });
  66398. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66399. get: function () {
  66400. return this._buttonB;
  66401. },
  66402. set: function (value) {
  66403. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66404. },
  66405. enumerable: true,
  66406. configurable: true
  66407. });
  66408. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66409. get: function () {
  66410. return this._buttonX;
  66411. },
  66412. set: function (value) {
  66413. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66414. },
  66415. enumerable: true,
  66416. configurable: true
  66417. });
  66418. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66419. get: function () {
  66420. return this._buttonY;
  66421. },
  66422. set: function (value) {
  66423. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66424. },
  66425. enumerable: true,
  66426. configurable: true
  66427. });
  66428. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66429. get: function () {
  66430. return this._buttonStart;
  66431. },
  66432. set: function (value) {
  66433. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66434. },
  66435. enumerable: true,
  66436. configurable: true
  66437. });
  66438. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66439. get: function () {
  66440. return this._buttonBack;
  66441. },
  66442. set: function (value) {
  66443. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66444. },
  66445. enumerable: true,
  66446. configurable: true
  66447. });
  66448. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66449. get: function () {
  66450. return this._buttonLB;
  66451. },
  66452. set: function (value) {
  66453. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66454. },
  66455. enumerable: true,
  66456. configurable: true
  66457. });
  66458. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66459. get: function () {
  66460. return this._buttonRB;
  66461. },
  66462. set: function (value) {
  66463. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66464. },
  66465. enumerable: true,
  66466. configurable: true
  66467. });
  66468. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66469. get: function () {
  66470. return this._buttonLeftStick;
  66471. },
  66472. set: function (value) {
  66473. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66474. },
  66475. enumerable: true,
  66476. configurable: true
  66477. });
  66478. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66479. get: function () {
  66480. return this._buttonRightStick;
  66481. },
  66482. set: function (value) {
  66483. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66484. },
  66485. enumerable: true,
  66486. configurable: true
  66487. });
  66488. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66489. get: function () {
  66490. return this._dPadUp;
  66491. },
  66492. set: function (value) {
  66493. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66494. },
  66495. enumerable: true,
  66496. configurable: true
  66497. });
  66498. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66499. get: function () {
  66500. return this._dPadDown;
  66501. },
  66502. set: function (value) {
  66503. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66504. },
  66505. enumerable: true,
  66506. configurable: true
  66507. });
  66508. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66509. get: function () {
  66510. return this._dPadLeft;
  66511. },
  66512. set: function (value) {
  66513. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66514. },
  66515. enumerable: true,
  66516. configurable: true
  66517. });
  66518. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66519. get: function () {
  66520. return this._dPadRight;
  66521. },
  66522. set: function (value) {
  66523. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66524. },
  66525. enumerable: true,
  66526. configurable: true
  66527. });
  66528. Xbox360Pad.prototype.update = function () {
  66529. _super.prototype.update.call(this);
  66530. if (this._isXboxOnePad) {
  66531. this.buttonA = this.browserGamepad.buttons[0].value;
  66532. this.buttonB = this.browserGamepad.buttons[1].value;
  66533. this.buttonX = this.browserGamepad.buttons[2].value;
  66534. this.buttonY = this.browserGamepad.buttons[3].value;
  66535. this.buttonLB = this.browserGamepad.buttons[4].value;
  66536. this.buttonRB = this.browserGamepad.buttons[5].value;
  66537. this.leftTrigger = this.browserGamepad.axes[2];
  66538. this.rightTrigger = this.browserGamepad.axes[5];
  66539. this.buttonBack = this.browserGamepad.buttons[9].value;
  66540. this.buttonStart = this.browserGamepad.buttons[8].value;
  66541. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66542. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66543. this.dPadUp = this.browserGamepad.buttons[11].value;
  66544. this.dPadDown = this.browserGamepad.buttons[12].value;
  66545. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66546. this.dPadRight = this.browserGamepad.buttons[14].value;
  66547. }
  66548. else {
  66549. this.buttonA = this.browserGamepad.buttons[0].value;
  66550. this.buttonB = this.browserGamepad.buttons[1].value;
  66551. this.buttonX = this.browserGamepad.buttons[2].value;
  66552. this.buttonY = this.browserGamepad.buttons[3].value;
  66553. this.buttonLB = this.browserGamepad.buttons[4].value;
  66554. this.buttonRB = this.browserGamepad.buttons[5].value;
  66555. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66556. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66557. this.buttonBack = this.browserGamepad.buttons[8].value;
  66558. this.buttonStart = this.browserGamepad.buttons[9].value;
  66559. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66560. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66561. this.dPadUp = this.browserGamepad.buttons[12].value;
  66562. this.dPadDown = this.browserGamepad.buttons[13].value;
  66563. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66564. this.dPadRight = this.browserGamepad.buttons[15].value;
  66565. }
  66566. };
  66567. Xbox360Pad.prototype.dispose = function () {
  66568. _super.prototype.dispose.call(this);
  66569. this.onButtonDownObservable.clear();
  66570. this.onButtonUpObservable.clear();
  66571. this.onPadDownObservable.clear();
  66572. this.onPadUpObservable.clear();
  66573. };
  66574. return Xbox360Pad;
  66575. }(BABYLON.Gamepad));
  66576. BABYLON.Xbox360Pad = Xbox360Pad;
  66577. })(BABYLON || (BABYLON = {}));
  66578. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66579. "use strict";
  66580. var BABYLON;
  66581. (function (BABYLON) {
  66582. var PoseEnabledControllerType;
  66583. (function (PoseEnabledControllerType) {
  66584. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66585. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66586. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66587. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66588. /**
  66589. * Google Daydream
  66590. */
  66591. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66592. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66593. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66594. var PoseEnabledControllerHelper = /** @class */ (function () {
  66595. function PoseEnabledControllerHelper() {
  66596. }
  66597. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66598. // Oculus Touch
  66599. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66600. return new BABYLON.OculusTouchController(vrGamepad);
  66601. }
  66602. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66603. return new BABYLON.WindowsMotionController(vrGamepad);
  66604. }
  66605. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66606. return new BABYLON.ViveController(vrGamepad);
  66607. }
  66608. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66609. return new BABYLON.GearVRController(vrGamepad);
  66610. }
  66611. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66612. return new BABYLON.DaydreamController(vrGamepad);
  66613. }
  66614. else {
  66615. return new BABYLON.GenericController(vrGamepad);
  66616. }
  66617. };
  66618. return PoseEnabledControllerHelper;
  66619. }());
  66620. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66621. var PoseEnabledController = /** @class */ (function (_super) {
  66622. __extends(PoseEnabledController, _super);
  66623. function PoseEnabledController(browserGamepad) {
  66624. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66625. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66626. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66627. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66628. // Represents device position and rotation in babylon space
  66629. _this.devicePosition = BABYLON.Vector3.Zero();
  66630. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66631. _this.deviceScaleFactor = 1;
  66632. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66633. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66634. /**
  66635. * Node to be used when casting a ray from the controller
  66636. */
  66637. _this._pointingPoseNode = null;
  66638. _this._workingMatrix = BABYLON.Matrix.Identity();
  66639. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66640. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66641. _this.position = BABYLON.Vector3.Zero();
  66642. _this.rotationQuaternion = new BABYLON.Quaternion();
  66643. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66644. _this._calculatedRotation = new BABYLON.Quaternion();
  66645. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66646. return _this;
  66647. }
  66648. PoseEnabledController.prototype.update = function () {
  66649. _super.prototype.update.call(this);
  66650. var pose = this.browserGamepad.pose;
  66651. this.updateFromDevice(pose);
  66652. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66653. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66654. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66655. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66656. if (this._mesh) {
  66657. this._mesh.position.copyFrom(this.devicePosition);
  66658. if (this._mesh.rotationQuaternion) {
  66659. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66660. }
  66661. }
  66662. };
  66663. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66664. if (poseData) {
  66665. this.rawPose = poseData;
  66666. if (poseData.position) {
  66667. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66668. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66669. this._deviceRoomPosition.z *= -1;
  66670. }
  66671. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66672. this._calculatedPosition.addInPlace(this.position);
  66673. }
  66674. var pose = this.rawPose;
  66675. if (poseData.orientation && pose.orientation) {
  66676. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66677. if (this._mesh) {
  66678. if (this._mesh.getScene().useRightHandedSystem) {
  66679. this._deviceRoomRotationQuaternion.z *= -1;
  66680. this._deviceRoomRotationQuaternion.w *= -1;
  66681. }
  66682. else {
  66683. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66684. }
  66685. }
  66686. // if the camera is set, rotate to the camera's rotation
  66687. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66688. }
  66689. }
  66690. };
  66691. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66692. if (this._mesh) {
  66693. this._mesh.parent = null;
  66694. }
  66695. this._mesh = mesh;
  66696. if (this._poseControlledCamera) {
  66697. this._mesh.parent = this._poseControlledCamera;
  66698. }
  66699. if (!this._mesh.rotationQuaternion) {
  66700. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66701. }
  66702. };
  66703. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66704. this._poseControlledCamera = camera;
  66705. if (this._mesh) {
  66706. this._mesh.parent = this._poseControlledCamera;
  66707. }
  66708. };
  66709. PoseEnabledController.prototype.dispose = function () {
  66710. if (this._mesh) {
  66711. this._mesh.dispose();
  66712. }
  66713. this._mesh = null;
  66714. _super.prototype.dispose.call(this);
  66715. };
  66716. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66717. get: function () {
  66718. return this._mesh;
  66719. },
  66720. enumerable: true,
  66721. configurable: true
  66722. });
  66723. PoseEnabledController.prototype.getForwardRay = function (length) {
  66724. if (length === void 0) { length = 100; }
  66725. if (!this.mesh) {
  66726. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66727. }
  66728. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66729. var origin = m.getTranslation();
  66730. var forward = new BABYLON.Vector3(0, 0, -1);
  66731. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66732. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66733. return new BABYLON.Ray(origin, direction, length);
  66734. };
  66735. /**
  66736. * Name of the child mesh that can be used to cast a ray from the controller
  66737. */
  66738. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66739. return PoseEnabledController;
  66740. }(BABYLON.Gamepad));
  66741. BABYLON.PoseEnabledController = PoseEnabledController;
  66742. })(BABYLON || (BABYLON = {}));
  66743. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66744. "use strict";
  66745. var BABYLON;
  66746. (function (BABYLON) {
  66747. var WebVRController = /** @class */ (function (_super) {
  66748. __extends(WebVRController, _super);
  66749. function WebVRController(vrGamepad) {
  66750. var _this = _super.call(this, vrGamepad) || this;
  66751. // Observables
  66752. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66753. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66754. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66755. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66756. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66757. _this.pad = { x: 0, y: 0 };
  66758. // avoid GC, store state in a tmp object
  66759. _this._changes = {
  66760. pressChanged: false,
  66761. touchChanged: false,
  66762. valueChanged: false,
  66763. changed: false
  66764. };
  66765. _this._buttons = new Array(vrGamepad.buttons.length);
  66766. _this.hand = vrGamepad.hand;
  66767. return _this;
  66768. }
  66769. WebVRController.prototype.onButtonStateChange = function (callback) {
  66770. this._onButtonStateChange = callback;
  66771. };
  66772. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66773. get: function () {
  66774. return this._defaultModel;
  66775. },
  66776. enumerable: true,
  66777. configurable: true
  66778. });
  66779. WebVRController.prototype.update = function () {
  66780. _super.prototype.update.call(this);
  66781. for (var index = 0; index < this._buttons.length; index++) {
  66782. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66783. }
  66784. ;
  66785. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66786. this.pad.x = this.leftStick.x;
  66787. this.pad.y = this.leftStick.y;
  66788. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66789. }
  66790. };
  66791. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66792. if (!newState) {
  66793. newState = {
  66794. pressed: false,
  66795. touched: false,
  66796. value: 0
  66797. };
  66798. }
  66799. if (!currentState) {
  66800. this._buttons[buttonIndex] = {
  66801. pressed: newState.pressed,
  66802. touched: newState.touched,
  66803. value: newState.value
  66804. };
  66805. return;
  66806. }
  66807. this._checkChanges(newState, currentState);
  66808. if (this._changes.changed) {
  66809. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66810. this._handleButtonChange(buttonIndex, newState, this._changes);
  66811. }
  66812. this._buttons[buttonIndex].pressed = newState.pressed;
  66813. this._buttons[buttonIndex].touched = newState.touched;
  66814. // oculus triggers are never 0, thou not touched.
  66815. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66816. };
  66817. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66818. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66819. this._changes.touchChanged = newState.touched !== currentState.touched;
  66820. this._changes.valueChanged = newState.value !== currentState.value;
  66821. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66822. return this._changes;
  66823. };
  66824. WebVRController.prototype.dispose = function () {
  66825. _super.prototype.dispose.call(this);
  66826. this.onTriggerStateChangedObservable.clear();
  66827. this.onMainButtonStateChangedObservable.clear();
  66828. this.onSecondaryButtonStateChangedObservable.clear();
  66829. this.onPadStateChangedObservable.clear();
  66830. this.onPadValuesChangedObservable.clear();
  66831. };
  66832. return WebVRController;
  66833. }(BABYLON.PoseEnabledController));
  66834. BABYLON.WebVRController = WebVRController;
  66835. })(BABYLON || (BABYLON = {}));
  66836. //# sourceMappingURL=babylon.webVRController.js.map
  66837. "use strict";
  66838. var BABYLON;
  66839. (function (BABYLON) {
  66840. var OculusTouchController = /** @class */ (function (_super) {
  66841. __extends(OculusTouchController, _super);
  66842. function OculusTouchController(vrGamepad) {
  66843. var _this = _super.call(this, vrGamepad) || this;
  66844. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66845. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66846. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66847. return _this;
  66848. }
  66849. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66850. var _this = this;
  66851. var meshName;
  66852. // Hand
  66853. if (this.hand === 'left') {
  66854. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66855. }
  66856. else {
  66857. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66858. }
  66859. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66860. /*
  66861. Parent Mesh name: oculus_touch_left
  66862. - body
  66863. - trigger
  66864. - thumbstick
  66865. - grip
  66866. - button_y
  66867. - button_x
  66868. - button_enter
  66869. */
  66870. _this._defaultModel = newMeshes[1];
  66871. _this.attachToMesh(_this._defaultModel);
  66872. if (meshLoaded) {
  66873. meshLoaded(_this._defaultModel);
  66874. }
  66875. });
  66876. };
  66877. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66878. // helper getters for left and right hand.
  66879. get: function () {
  66880. if (this.hand === 'right') {
  66881. return this.onMainButtonStateChangedObservable;
  66882. }
  66883. else {
  66884. throw new Error('No A button on left hand');
  66885. }
  66886. },
  66887. enumerable: true,
  66888. configurable: true
  66889. });
  66890. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66891. get: function () {
  66892. if (this.hand === 'right') {
  66893. return this.onSecondaryButtonStateChangedObservable;
  66894. }
  66895. else {
  66896. throw new Error('No B button on left hand');
  66897. }
  66898. },
  66899. enumerable: true,
  66900. configurable: true
  66901. });
  66902. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66903. get: function () {
  66904. if (this.hand === 'left') {
  66905. return this.onMainButtonStateChangedObservable;
  66906. }
  66907. else {
  66908. throw new Error('No X button on right hand');
  66909. }
  66910. },
  66911. enumerable: true,
  66912. configurable: true
  66913. });
  66914. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66915. get: function () {
  66916. if (this.hand === 'left') {
  66917. return this.onSecondaryButtonStateChangedObservable;
  66918. }
  66919. else {
  66920. throw new Error('No Y button on right hand');
  66921. }
  66922. },
  66923. enumerable: true,
  66924. configurable: true
  66925. });
  66926. /*
  66927. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66928. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66929. 2) secondary trigger (same)
  66930. 3) A (right) X (left), touch, pressed = value
  66931. 4) B / Y
  66932. 5) thumb rest
  66933. */
  66934. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66935. var notifyObject = state; //{ state: state, changes: changes };
  66936. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66937. switch (buttonIdx) {
  66938. case 0:
  66939. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66940. return;
  66941. case 1:// index trigger
  66942. if (this._defaultModel) {
  66943. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66944. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66945. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66946. }
  66947. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66948. return;
  66949. case 2:// secondary trigger
  66950. if (this._defaultModel) {
  66951. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66952. }
  66953. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66954. return;
  66955. case 3:
  66956. if (this._defaultModel) {
  66957. if (notifyObject.pressed) {
  66958. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66959. }
  66960. else {
  66961. (this._defaultModel.getChildren()[1]).position.y = 0;
  66962. }
  66963. }
  66964. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66965. return;
  66966. case 4:
  66967. if (this._defaultModel) {
  66968. if (notifyObject.pressed) {
  66969. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66970. }
  66971. else {
  66972. (this._defaultModel.getChildren()[2]).position.y = 0;
  66973. }
  66974. }
  66975. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66976. return;
  66977. case 5:
  66978. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66979. return;
  66980. }
  66981. };
  66982. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66983. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66984. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66985. return OculusTouchController;
  66986. }(BABYLON.WebVRController));
  66987. BABYLON.OculusTouchController = OculusTouchController;
  66988. })(BABYLON || (BABYLON = {}));
  66989. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66990. "use strict";
  66991. var BABYLON;
  66992. (function (BABYLON) {
  66993. var ViveController = /** @class */ (function (_super) {
  66994. __extends(ViveController, _super);
  66995. function ViveController(vrGamepad) {
  66996. var _this = _super.call(this, vrGamepad) || this;
  66997. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66998. _this._invertLeftStickY = true;
  66999. return _this;
  67000. }
  67001. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67002. var _this = this;
  67003. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  67004. /*
  67005. Parent Mesh name: ViveWand
  67006. - body
  67007. - r_gripper
  67008. - l_gripper
  67009. - menu_button
  67010. - system_button
  67011. - trackpad
  67012. - trigger
  67013. - LED
  67014. */
  67015. _this._defaultModel = newMeshes[1];
  67016. _this.attachToMesh(_this._defaultModel);
  67017. if (meshLoaded) {
  67018. meshLoaded(_this._defaultModel);
  67019. }
  67020. });
  67021. };
  67022. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  67023. get: function () {
  67024. return this.onMainButtonStateChangedObservable;
  67025. },
  67026. enumerable: true,
  67027. configurable: true
  67028. });
  67029. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  67030. get: function () {
  67031. return this.onMainButtonStateChangedObservable;
  67032. },
  67033. enumerable: true,
  67034. configurable: true
  67035. });
  67036. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  67037. get: function () {
  67038. return this.onSecondaryButtonStateChangedObservable;
  67039. },
  67040. enumerable: true,
  67041. configurable: true
  67042. });
  67043. /**
  67044. * Vive mapping:
  67045. * 0: touchpad
  67046. * 1: trigger
  67047. * 2: left AND right buttons
  67048. * 3: menu button
  67049. */
  67050. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67051. var notifyObject = state; //{ state: state, changes: changes };
  67052. switch (buttonIdx) {
  67053. case 0:
  67054. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67055. return;
  67056. case 1:// index trigger
  67057. if (this._defaultModel) {
  67058. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  67059. }
  67060. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67061. return;
  67062. case 2:// left AND right button
  67063. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67064. return;
  67065. case 3:
  67066. if (this._defaultModel) {
  67067. if (notifyObject.pressed) {
  67068. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67069. }
  67070. else {
  67071. (this._defaultModel.getChildren()[2]).position.y = 0;
  67072. }
  67073. }
  67074. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67075. return;
  67076. }
  67077. };
  67078. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  67079. ViveController.MODEL_FILENAME = 'wand.babylon';
  67080. return ViveController;
  67081. }(BABYLON.WebVRController));
  67082. BABYLON.ViveController = ViveController;
  67083. })(BABYLON || (BABYLON = {}));
  67084. //# sourceMappingURL=babylon.viveController.js.map
  67085. "use strict";
  67086. var BABYLON;
  67087. (function (BABYLON) {
  67088. var GenericController = /** @class */ (function (_super) {
  67089. __extends(GenericController, _super);
  67090. function GenericController(vrGamepad) {
  67091. return _super.call(this, vrGamepad) || this;
  67092. }
  67093. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67094. var _this = this;
  67095. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  67096. _this._defaultModel = newMeshes[1];
  67097. _this.attachToMesh(_this._defaultModel);
  67098. if (meshLoaded) {
  67099. meshLoaded(_this._defaultModel);
  67100. }
  67101. });
  67102. };
  67103. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67104. console.log("Button id: " + buttonIdx + "state: ");
  67105. console.dir(state);
  67106. };
  67107. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67108. GenericController.MODEL_FILENAME = 'generic.babylon';
  67109. return GenericController;
  67110. }(BABYLON.WebVRController));
  67111. BABYLON.GenericController = GenericController;
  67112. })(BABYLON || (BABYLON = {}));
  67113. //# sourceMappingURL=babylon.genericController.js.map
  67114. "use strict";
  67115. var BABYLON;
  67116. (function (BABYLON) {
  67117. var LoadedMeshInfo = /** @class */ (function () {
  67118. function LoadedMeshInfo() {
  67119. this.buttonMeshes = {};
  67120. this.axisMeshes = {};
  67121. }
  67122. return LoadedMeshInfo;
  67123. }());
  67124. var WindowsMotionController = /** @class */ (function (_super) {
  67125. __extends(WindowsMotionController, _super);
  67126. function WindowsMotionController(vrGamepad) {
  67127. var _this = _super.call(this, vrGamepad) || this;
  67128. _this._mapping = {
  67129. // Semantic button names
  67130. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67131. // A mapping of the button name to glTF model node name
  67132. // that should be transformed by button value.
  67133. buttonMeshNames: {
  67134. 'trigger': 'SELECT',
  67135. 'menu': 'MENU',
  67136. 'grip': 'GRASP',
  67137. 'thumbstick': 'THUMBSTICK_PRESS',
  67138. 'trackpad': 'TOUCHPAD_PRESS'
  67139. },
  67140. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67141. buttonObservableNames: {
  67142. 'trigger': 'onTriggerStateChangedObservable',
  67143. 'menu': 'onSecondaryButtonStateChangedObservable',
  67144. 'grip': 'onMainButtonStateChangedObservable',
  67145. 'thumbstick': 'onPadStateChangedObservable',
  67146. 'trackpad': 'onTrackpadChangedObservable'
  67147. },
  67148. // A mapping of the axis name to glTF model node name
  67149. // that should be transformed by axis value.
  67150. // This array mirrors the browserGamepad.axes array, such that
  67151. // the mesh corresponding to axis 0 is in this array index 0.
  67152. axisMeshNames: [
  67153. 'THUMBSTICK_X',
  67154. 'THUMBSTICK_Y',
  67155. 'TOUCHPAD_TOUCH_X',
  67156. 'TOUCHPAD_TOUCH_Y'
  67157. ],
  67158. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67159. };
  67160. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67161. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67162. _this.trackpad = { x: 0, y: 0 };
  67163. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67164. _this._loadedMeshInfo = null;
  67165. return _this;
  67166. }
  67167. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67168. get: function () {
  67169. return this.onTriggerStateChangedObservable;
  67170. },
  67171. enumerable: true,
  67172. configurable: true
  67173. });
  67174. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67175. get: function () {
  67176. return this.onSecondaryButtonStateChangedObservable;
  67177. },
  67178. enumerable: true,
  67179. configurable: true
  67180. });
  67181. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67182. get: function () {
  67183. return this.onMainButtonStateChangedObservable;
  67184. },
  67185. enumerable: true,
  67186. configurable: true
  67187. });
  67188. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67189. get: function () {
  67190. return this.onPadStateChangedObservable;
  67191. },
  67192. enumerable: true,
  67193. configurable: true
  67194. });
  67195. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67196. get: function () {
  67197. return this.onTrackpadChangedObservable;
  67198. },
  67199. enumerable: true,
  67200. configurable: true
  67201. });
  67202. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67203. get: function () {
  67204. return this.onTrackpadValuesChangedObservable;
  67205. },
  67206. enumerable: true,
  67207. configurable: true
  67208. });
  67209. /**
  67210. * Called once per frame by the engine.
  67211. */
  67212. WindowsMotionController.prototype.update = function () {
  67213. _super.prototype.update.call(this);
  67214. if (this.browserGamepad.axes) {
  67215. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67216. this.trackpad.x = this.browserGamepad["axes"][2];
  67217. this.trackpad.y = this.browserGamepad["axes"][3];
  67218. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67219. }
  67220. // Only need to animate axes if there is a loaded mesh
  67221. if (this._loadedMeshInfo) {
  67222. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67223. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67224. }
  67225. }
  67226. }
  67227. };
  67228. /**
  67229. * Called once for each button that changed state since the last frame
  67230. * @param buttonIdx Which button index changed
  67231. * @param state New state of the button
  67232. * @param changes Which properties on the state changed since last frame
  67233. */
  67234. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67235. var buttonName = this._mapping.buttons[buttonIdx];
  67236. if (!buttonName) {
  67237. return;
  67238. }
  67239. // Only emit events for buttons that we know how to map from index to name
  67240. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67241. if (observable) {
  67242. observable.notifyObservers(state);
  67243. }
  67244. this.lerpButtonTransform(buttonName, state.value);
  67245. };
  67246. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67247. // If there is no loaded mesh, there is nothing to transform.
  67248. if (!this._loadedMeshInfo) {
  67249. return;
  67250. }
  67251. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67252. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67253. return;
  67254. }
  67255. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67256. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67257. };
  67258. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67259. if (!this._loadedMeshInfo) {
  67260. return;
  67261. }
  67262. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67263. if (!meshInfo) {
  67264. return;
  67265. }
  67266. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67267. return;
  67268. }
  67269. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67270. var lerpValue = axisValue * 0.5 + 0.5;
  67271. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67272. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67273. };
  67274. /**
  67275. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67276. * @param scene scene in which to add meshes
  67277. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67278. */
  67279. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67280. var _this = this;
  67281. if (forceDefault === void 0) { forceDefault = false; }
  67282. var path;
  67283. var filename;
  67284. // Checking if GLB loader is present
  67285. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67286. // Determine the device specific folder based on the ID suffix
  67287. var device = 'default';
  67288. if (this.id && !forceDefault) {
  67289. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67290. device = ((match && match[0]) || device);
  67291. }
  67292. // Hand
  67293. if (this.hand === 'left') {
  67294. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67295. }
  67296. else {
  67297. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67298. }
  67299. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67300. }
  67301. else {
  67302. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67303. path = BABYLON.GenericController.MODEL_BASE_URL;
  67304. filename = BABYLON.GenericController.MODEL_FILENAME;
  67305. }
  67306. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67307. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67308. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67309. if (!_this._loadedMeshInfo) {
  67310. return;
  67311. }
  67312. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67313. _this.attachToMesh(_this._defaultModel);
  67314. if (meshLoaded) {
  67315. meshLoaded(_this._defaultModel);
  67316. }
  67317. }, null, function (scene, message) {
  67318. BABYLON.Tools.Log(message);
  67319. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67320. if (!forceDefault) {
  67321. _this.initControllerMesh(scene, meshLoaded, true);
  67322. }
  67323. });
  67324. };
  67325. /**
  67326. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67327. * can be transformed by button presses and axes values, based on this._mapping.
  67328. *
  67329. * @param scene scene in which the meshes exist
  67330. * @param meshes list of meshes that make up the controller model to process
  67331. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67332. */
  67333. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67334. var loadedMeshInfo = null;
  67335. // Create a new mesh to contain the glTF hierarchy
  67336. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67337. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67338. var childMesh = null;
  67339. for (var i = 0; i < meshes.length; i++) {
  67340. var mesh = meshes[i];
  67341. if (!mesh.parent) {
  67342. // Exclude controller meshes from picking results
  67343. mesh.isPickable = false;
  67344. // Handle root node, attach to the new parentMesh
  67345. childMesh = mesh;
  67346. break;
  67347. }
  67348. }
  67349. if (childMesh) {
  67350. childMesh.setParent(parentMesh);
  67351. // Create our mesh info. Note that this method will always return non-null.
  67352. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67353. }
  67354. else {
  67355. BABYLON.Tools.Warn('Could not find root node in model file.');
  67356. }
  67357. return loadedMeshInfo;
  67358. };
  67359. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67360. var loadedMeshInfo = new LoadedMeshInfo();
  67361. var i;
  67362. loadedMeshInfo.rootNode = rootNode;
  67363. // Reset the caches
  67364. loadedMeshInfo.buttonMeshes = {};
  67365. loadedMeshInfo.axisMeshes = {};
  67366. // Button Meshes
  67367. for (i = 0; i < this._mapping.buttons.length; i++) {
  67368. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67369. if (!buttonMeshName) {
  67370. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67371. continue;
  67372. }
  67373. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67374. if (!buttonMesh) {
  67375. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67376. continue;
  67377. }
  67378. var buttonMeshInfo = {
  67379. index: i,
  67380. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67381. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67382. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67383. };
  67384. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67385. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67386. }
  67387. else {
  67388. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67389. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67390. '(VALUE: ' + !!buttonMeshInfo.value +
  67391. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67392. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67393. ')');
  67394. }
  67395. }
  67396. // Axis Meshes
  67397. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67398. var axisMeshName = this._mapping.axisMeshNames[i];
  67399. if (!axisMeshName) {
  67400. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67401. continue;
  67402. }
  67403. var axisMesh = getChildByName(rootNode, axisMeshName);
  67404. if (!axisMesh) {
  67405. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67406. continue;
  67407. }
  67408. var axisMeshInfo = {
  67409. index: i,
  67410. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67411. min: getImmediateChildByName(axisMesh, 'MIN'),
  67412. max: getImmediateChildByName(axisMesh, 'MAX')
  67413. };
  67414. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67415. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67416. }
  67417. else {
  67418. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67419. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67420. '(VALUE: ' + !!axisMeshInfo.value +
  67421. ', MIN: ' + !!axisMeshInfo.min +
  67422. ', MAX:' + !!axisMeshInfo.max +
  67423. ')');
  67424. }
  67425. }
  67426. // Pointing Ray
  67427. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67428. if (!loadedMeshInfo.pointingPoseNode) {
  67429. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67430. }
  67431. return loadedMeshInfo;
  67432. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67433. function getChildByName(node, name) {
  67434. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67435. }
  67436. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67437. function getImmediateChildByName(node, name) {
  67438. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67439. }
  67440. };
  67441. WindowsMotionController.prototype.getForwardRay = function (length) {
  67442. if (length === void 0) { length = 100; }
  67443. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67444. return _super.prototype.getForwardRay.call(this, length);
  67445. }
  67446. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67447. var origin = m.getTranslation();
  67448. var forward = new BABYLON.Vector3(0, 0, -1);
  67449. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67450. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67451. return new BABYLON.Ray(origin, direction, length);
  67452. };
  67453. WindowsMotionController.prototype.dispose = function () {
  67454. _super.prototype.dispose.call(this);
  67455. this.onTrackpadChangedObservable.clear();
  67456. };
  67457. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67458. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67459. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67460. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67461. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67462. return WindowsMotionController;
  67463. }(BABYLON.WebVRController));
  67464. BABYLON.WindowsMotionController = WindowsMotionController;
  67465. })(BABYLON || (BABYLON = {}));
  67466. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67467. "use strict";
  67468. var BABYLON;
  67469. (function (BABYLON) {
  67470. var GearVRController = /** @class */ (function (_super) {
  67471. __extends(GearVRController, _super);
  67472. function GearVRController(vrGamepad) {
  67473. var _this = _super.call(this, vrGamepad) || this;
  67474. _this._buttonIndexToObservableNameMap = [
  67475. 'onTrackpadChangedObservable',
  67476. 'onTriggerStateChangedObservable' // Trigger
  67477. ];
  67478. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67479. return _this;
  67480. }
  67481. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67482. var _this = this;
  67483. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67484. _this._defaultModel = newMeshes[1];
  67485. _this.attachToMesh(_this._defaultModel);
  67486. if (meshLoaded) {
  67487. meshLoaded(_this._defaultModel);
  67488. }
  67489. });
  67490. };
  67491. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67492. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67493. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67494. // Only emit events for buttons that we know how to map from index to observable
  67495. var observable = this[observableName];
  67496. if (observable) {
  67497. observable.notifyObservers(state);
  67498. }
  67499. }
  67500. };
  67501. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67502. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67503. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67504. return GearVRController;
  67505. }(BABYLON.WebVRController));
  67506. BABYLON.GearVRController = GearVRController;
  67507. })(BABYLON || (BABYLON = {}));
  67508. //# sourceMappingURL=babylon.gearVRController.js.map
  67509. "use strict";
  67510. var BABYLON;
  67511. (function (BABYLON) {
  67512. /**
  67513. * Google Daydream controller
  67514. */
  67515. var DaydreamController = /** @class */ (function (_super) {
  67516. __extends(DaydreamController, _super);
  67517. function DaydreamController(vrGamepad) {
  67518. var _this = _super.call(this, vrGamepad) || this;
  67519. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67520. return _this;
  67521. }
  67522. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67523. var _this = this;
  67524. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67525. _this._defaultModel = newMeshes[1];
  67526. _this.attachToMesh(_this._defaultModel);
  67527. if (meshLoaded) {
  67528. meshLoaded(_this._defaultModel);
  67529. }
  67530. });
  67531. };
  67532. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67533. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67534. if (buttonIdx === 0) {
  67535. var observable = this.onTriggerStateChangedObservable;
  67536. if (observable) {
  67537. observable.notifyObservers(state);
  67538. }
  67539. }
  67540. else {
  67541. // If the app or home buttons are ever made available
  67542. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67543. }
  67544. };
  67545. /**
  67546. * Base Url for the controller model.
  67547. */
  67548. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67549. /**
  67550. * File name for the controller model.
  67551. */
  67552. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67553. /**
  67554. * Gamepad Id prefix used to identify Daydream Controller.
  67555. */
  67556. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67557. return DaydreamController;
  67558. }(BABYLON.WebVRController));
  67559. BABYLON.DaydreamController = DaydreamController;
  67560. })(BABYLON || (BABYLON = {}));
  67561. //# sourceMappingURL=babylon.daydreamController.js.map
  67562. "use strict";
  67563. var BABYLON;
  67564. (function (BABYLON) {
  67565. var FollowCamera = /** @class */ (function (_super) {
  67566. __extends(FollowCamera, _super);
  67567. function FollowCamera(name, position, scene, lockedTarget) {
  67568. if (lockedTarget === void 0) { lockedTarget = null; }
  67569. var _this = _super.call(this, name, position, scene) || this;
  67570. _this.radius = 12;
  67571. _this.rotationOffset = 0;
  67572. _this.heightOffset = 4;
  67573. _this.cameraAcceleration = 0.05;
  67574. _this.maxCameraSpeed = 20;
  67575. _this.lockedTarget = lockedTarget;
  67576. return _this;
  67577. }
  67578. FollowCamera.prototype.getRadians = function (degrees) {
  67579. return degrees * Math.PI / 180;
  67580. };
  67581. FollowCamera.prototype.follow = function (cameraTarget) {
  67582. if (!cameraTarget)
  67583. return;
  67584. var yRotation;
  67585. if (cameraTarget.rotationQuaternion) {
  67586. var rotMatrix = new BABYLON.Matrix();
  67587. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67588. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67589. }
  67590. else {
  67591. yRotation = cameraTarget.rotation.y;
  67592. }
  67593. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67594. var targetPosition = cameraTarget.getAbsolutePosition();
  67595. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67596. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67597. var dx = targetX - this.position.x;
  67598. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67599. var dz = (targetZ) - this.position.z;
  67600. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67601. var vy = dy * this.cameraAcceleration;
  67602. var vz = dz * this.cameraAcceleration * 2;
  67603. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67604. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67605. }
  67606. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67607. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67608. }
  67609. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67610. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67611. }
  67612. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67613. this.setTarget(targetPosition);
  67614. };
  67615. FollowCamera.prototype._checkInputs = function () {
  67616. _super.prototype._checkInputs.call(this);
  67617. if (this.lockedTarget) {
  67618. this.follow(this.lockedTarget);
  67619. }
  67620. };
  67621. FollowCamera.prototype.getClassName = function () {
  67622. return "FollowCamera";
  67623. };
  67624. __decorate([
  67625. BABYLON.serialize()
  67626. ], FollowCamera.prototype, "radius", void 0);
  67627. __decorate([
  67628. BABYLON.serialize()
  67629. ], FollowCamera.prototype, "rotationOffset", void 0);
  67630. __decorate([
  67631. BABYLON.serialize()
  67632. ], FollowCamera.prototype, "heightOffset", void 0);
  67633. __decorate([
  67634. BABYLON.serialize()
  67635. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67636. __decorate([
  67637. BABYLON.serialize()
  67638. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67639. __decorate([
  67640. BABYLON.serializeAsMeshReference("lockedTargetId")
  67641. ], FollowCamera.prototype, "lockedTarget", void 0);
  67642. return FollowCamera;
  67643. }(BABYLON.TargetCamera));
  67644. BABYLON.FollowCamera = FollowCamera;
  67645. var ArcFollowCamera = /** @class */ (function (_super) {
  67646. __extends(ArcFollowCamera, _super);
  67647. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67648. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67649. _this.alpha = alpha;
  67650. _this.beta = beta;
  67651. _this.radius = radius;
  67652. _this.target = target;
  67653. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67654. _this.follow();
  67655. return _this;
  67656. }
  67657. ArcFollowCamera.prototype.follow = function () {
  67658. if (!this.target) {
  67659. return;
  67660. }
  67661. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67662. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67663. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67664. var targetPosition = this.target.getAbsolutePosition();
  67665. this.position = targetPosition.add(this._cartesianCoordinates);
  67666. this.setTarget(targetPosition);
  67667. };
  67668. ArcFollowCamera.prototype._checkInputs = function () {
  67669. _super.prototype._checkInputs.call(this);
  67670. this.follow();
  67671. };
  67672. ArcFollowCamera.prototype.getClassName = function () {
  67673. return "ArcFollowCamera";
  67674. };
  67675. return ArcFollowCamera;
  67676. }(BABYLON.TargetCamera));
  67677. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67678. })(BABYLON || (BABYLON = {}));
  67679. //# sourceMappingURL=babylon.followCamera.js.map
  67680. "use strict";
  67681. var BABYLON;
  67682. (function (BABYLON) {
  67683. // We're mainly based on the logic defined into the FreeCamera code
  67684. var UniversalCamera = /** @class */ (function (_super) {
  67685. __extends(UniversalCamera, _super);
  67686. //-- end properties for backward compatibility for inputs
  67687. function UniversalCamera(name, position, scene) {
  67688. var _this = _super.call(this, name, position, scene) || this;
  67689. _this.inputs.addGamepad();
  67690. return _this;
  67691. }
  67692. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67693. //-- Begin properties for backward compatibility for inputs
  67694. get: function () {
  67695. var gamepad = this.inputs.attached["gamepad"];
  67696. if (gamepad)
  67697. return gamepad.gamepadAngularSensibility;
  67698. return 0;
  67699. },
  67700. set: function (value) {
  67701. var gamepad = this.inputs.attached["gamepad"];
  67702. if (gamepad)
  67703. gamepad.gamepadAngularSensibility = value;
  67704. },
  67705. enumerable: true,
  67706. configurable: true
  67707. });
  67708. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67709. get: function () {
  67710. var gamepad = this.inputs.attached["gamepad"];
  67711. if (gamepad)
  67712. return gamepad.gamepadMoveSensibility;
  67713. return 0;
  67714. },
  67715. set: function (value) {
  67716. var gamepad = this.inputs.attached["gamepad"];
  67717. if (gamepad)
  67718. gamepad.gamepadMoveSensibility = value;
  67719. },
  67720. enumerable: true,
  67721. configurable: true
  67722. });
  67723. UniversalCamera.prototype.getClassName = function () {
  67724. return "UniversalCamera";
  67725. };
  67726. return UniversalCamera;
  67727. }(BABYLON.TouchCamera));
  67728. BABYLON.UniversalCamera = UniversalCamera;
  67729. })(BABYLON || (BABYLON = {}));
  67730. //# sourceMappingURL=babylon.universalCamera.js.map
  67731. "use strict";
  67732. var BABYLON;
  67733. (function (BABYLON) {
  67734. // We're mainly based on the logic defined into the FreeCamera code
  67735. var GamepadCamera = /** @class */ (function (_super) {
  67736. __extends(GamepadCamera, _super);
  67737. //-- end properties for backward compatibility for inputs
  67738. function GamepadCamera(name, position, scene) {
  67739. return _super.call(this, name, position, scene) || this;
  67740. }
  67741. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67742. //-- Begin properties for backward compatibility for inputs
  67743. get: function () {
  67744. var gamepad = this.inputs.attached["gamepad"];
  67745. if (gamepad)
  67746. return gamepad.gamepadAngularSensibility;
  67747. return 0;
  67748. },
  67749. set: function (value) {
  67750. var gamepad = this.inputs.attached["gamepad"];
  67751. if (gamepad)
  67752. gamepad.gamepadAngularSensibility = value;
  67753. },
  67754. enumerable: true,
  67755. configurable: true
  67756. });
  67757. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67758. get: function () {
  67759. var gamepad = this.inputs.attached["gamepad"];
  67760. if (gamepad)
  67761. return gamepad.gamepadMoveSensibility;
  67762. return 0;
  67763. },
  67764. set: function (value) {
  67765. var gamepad = this.inputs.attached["gamepad"];
  67766. if (gamepad)
  67767. gamepad.gamepadMoveSensibility = value;
  67768. },
  67769. enumerable: true,
  67770. configurable: true
  67771. });
  67772. GamepadCamera.prototype.getClassName = function () {
  67773. return "GamepadCamera";
  67774. };
  67775. return GamepadCamera;
  67776. }(BABYLON.UniversalCamera));
  67777. BABYLON.GamepadCamera = GamepadCamera;
  67778. })(BABYLON || (BABYLON = {}));
  67779. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67780. "use strict";
  67781. var BABYLON;
  67782. (function (BABYLON) {
  67783. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67784. function PostProcessRenderPipelineManager() {
  67785. this._renderPipelines = {};
  67786. }
  67787. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67788. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67789. };
  67790. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67791. if (unique === void 0) { unique = false; }
  67792. var renderPipeline = this._renderPipelines[renderPipelineName];
  67793. if (!renderPipeline) {
  67794. return;
  67795. }
  67796. renderPipeline._attachCameras(cameras, unique);
  67797. };
  67798. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67799. var renderPipeline = this._renderPipelines[renderPipelineName];
  67800. if (!renderPipeline) {
  67801. return;
  67802. }
  67803. renderPipeline._detachCameras(cameras);
  67804. };
  67805. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67806. var renderPipeline = this._renderPipelines[renderPipelineName];
  67807. if (!renderPipeline) {
  67808. return;
  67809. }
  67810. renderPipeline._enableEffect(renderEffectName, cameras);
  67811. };
  67812. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67813. var renderPipeline = this._renderPipelines[renderPipelineName];
  67814. if (!renderPipeline) {
  67815. return;
  67816. }
  67817. renderPipeline._disableEffect(renderEffectName, cameras);
  67818. };
  67819. PostProcessRenderPipelineManager.prototype.update = function () {
  67820. for (var renderPipelineName in this._renderPipelines) {
  67821. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67822. var pipeline = this._renderPipelines[renderPipelineName];
  67823. if (!pipeline.isSupported) {
  67824. pipeline.dispose();
  67825. delete this._renderPipelines[renderPipelineName];
  67826. }
  67827. else {
  67828. pipeline._update();
  67829. }
  67830. }
  67831. }
  67832. };
  67833. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67834. for (var renderPipelineName in this._renderPipelines) {
  67835. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67836. var pipeline = this._renderPipelines[renderPipelineName];
  67837. pipeline._rebuild();
  67838. }
  67839. }
  67840. };
  67841. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67842. for (var renderPipelineName in this._renderPipelines) {
  67843. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67844. var pipeline = this._renderPipelines[renderPipelineName];
  67845. pipeline.dispose();
  67846. }
  67847. }
  67848. };
  67849. return PostProcessRenderPipelineManager;
  67850. }());
  67851. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67852. })(BABYLON || (BABYLON = {}));
  67853. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67854. "use strict";
  67855. var BABYLON;
  67856. (function (BABYLON) {
  67857. /**
  67858. * This represents a set of one or more post processes in Babylon.
  67859. * A post process can be used to apply a shader to a texture after it is rendered.
  67860. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67861. */
  67862. var PostProcessRenderEffect = /** @class */ (function () {
  67863. /**
  67864. * Instantiates a post process render effect.
  67865. * A post process can be used to apply a shader to a texture after it is rendered.
  67866. * @param engine The engine the effect is tied to
  67867. * @param name The name of the effect
  67868. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67869. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67870. */
  67871. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67872. this._name = name;
  67873. this._singleInstance = singleInstance || true;
  67874. this._getPostProcesses = getPostProcesses;
  67875. this._cameras = {};
  67876. this._indicesForCamera = {};
  67877. this._postProcesses = {};
  67878. }
  67879. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67880. /**
  67881. * Checks if all the post processes in the effect are supported.
  67882. */
  67883. get: function () {
  67884. for (var index in this._postProcesses) {
  67885. for (var ppIndex in this._postProcesses[index]) {
  67886. if (!this._postProcesses[index][ppIndex].isSupported) {
  67887. return false;
  67888. }
  67889. }
  67890. }
  67891. return true;
  67892. },
  67893. enumerable: true,
  67894. configurable: true
  67895. });
  67896. /**
  67897. * Updates the current state of the effect
  67898. */
  67899. PostProcessRenderEffect.prototype._update = function () {
  67900. };
  67901. /**
  67902. * Attaches the effect on cameras
  67903. * @param cameras The camera to attach to.
  67904. */
  67905. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67906. var _this = this;
  67907. var cameraKey;
  67908. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67909. if (!cams) {
  67910. return;
  67911. }
  67912. for (var i = 0; i < cams.length; i++) {
  67913. var camera = cams[i];
  67914. var cameraName = camera.name;
  67915. if (this._singleInstance) {
  67916. cameraKey = 0;
  67917. }
  67918. else {
  67919. cameraKey = cameraName;
  67920. }
  67921. if (!this._postProcesses[cameraKey]) {
  67922. var postProcess = this._getPostProcesses();
  67923. if (postProcess) {
  67924. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67925. }
  67926. }
  67927. if (!this._indicesForCamera[cameraName]) {
  67928. this._indicesForCamera[cameraName] = [];
  67929. }
  67930. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67931. var index = camera.attachPostProcess(postProcess);
  67932. _this._indicesForCamera[cameraName].push(index);
  67933. });
  67934. if (!this._cameras[cameraName]) {
  67935. this._cameras[cameraName] = camera;
  67936. }
  67937. }
  67938. };
  67939. /**
  67940. * Detatches the effect on cameras
  67941. * @param cameras The camera to detatch from.
  67942. */
  67943. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67944. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67945. if (!cams) {
  67946. return;
  67947. }
  67948. for (var i = 0; i < cams.length; i++) {
  67949. var camera = cams[i];
  67950. var cameraName = camera.name;
  67951. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67952. camera.detachPostProcess(postProcess);
  67953. });
  67954. if (this._cameras[cameraName]) {
  67955. //this._indicesForCamera.splice(index, 1);
  67956. this._cameras[cameraName] = null;
  67957. }
  67958. }
  67959. };
  67960. /**
  67961. * Enables the effect on given cameras
  67962. * @param cameras The camera to enable.
  67963. */
  67964. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67965. var _this = this;
  67966. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67967. if (!cams) {
  67968. return;
  67969. }
  67970. for (var i = 0; i < cams.length; i++) {
  67971. var camera = cams[i];
  67972. var cameraName = camera.name;
  67973. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67974. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67975. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67976. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67977. });
  67978. }
  67979. }
  67980. }
  67981. };
  67982. /**
  67983. * Disables the effect on the given cameras
  67984. * @param cameras The camera to disable.
  67985. */
  67986. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67987. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67988. if (!cams) {
  67989. return;
  67990. }
  67991. for (var i = 0; i < cams.length; i++) {
  67992. var camera = cams[i];
  67993. var cameraName = camera.name;
  67994. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67995. camera.detachPostProcess(postProcess);
  67996. });
  67997. }
  67998. };
  67999. /**
  68000. * Gets a list of the post processes contained in the effect.
  68001. * @param camera The camera to get the post processes on.
  68002. * @returns The list of the post processes in the effect.
  68003. */
  68004. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  68005. if (this._singleInstance) {
  68006. return this._postProcesses[0];
  68007. }
  68008. else {
  68009. if (!camera) {
  68010. return null;
  68011. }
  68012. return this._postProcesses[camera.name];
  68013. }
  68014. };
  68015. return PostProcessRenderEffect;
  68016. }());
  68017. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  68018. })(BABYLON || (BABYLON = {}));
  68019. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  68020. "use strict";
  68021. var BABYLON;
  68022. (function (BABYLON) {
  68023. var PostProcessRenderPipeline = /** @class */ (function () {
  68024. function PostProcessRenderPipeline(engine, name) {
  68025. this.engine = engine;
  68026. this._name = name;
  68027. this._renderEffects = {};
  68028. this._renderEffectsForIsolatedPass = new Array();
  68029. this._cameras = [];
  68030. }
  68031. PostProcessRenderPipeline.prototype.getClassName = function () {
  68032. return "PostProcessRenderPipeline";
  68033. };
  68034. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  68035. get: function () {
  68036. for (var renderEffectName in this._renderEffects) {
  68037. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68038. if (!this._renderEffects[renderEffectName].isSupported) {
  68039. return false;
  68040. }
  68041. }
  68042. }
  68043. return true;
  68044. },
  68045. enumerable: true,
  68046. configurable: true
  68047. });
  68048. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  68049. this._renderEffects[renderEffect._name] = renderEffect;
  68050. };
  68051. // private
  68052. PostProcessRenderPipeline.prototype._rebuild = function () {
  68053. };
  68054. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  68055. var renderEffects = this._renderEffects[renderEffectName];
  68056. if (!renderEffects) {
  68057. return;
  68058. }
  68059. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68060. };
  68061. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  68062. var renderEffects = this._renderEffects[renderEffectName];
  68063. if (!renderEffects) {
  68064. return;
  68065. }
  68066. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68067. };
  68068. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  68069. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68070. if (!cams) {
  68071. return;
  68072. }
  68073. var indicesToDelete = [];
  68074. var i;
  68075. for (i = 0; i < cams.length; i++) {
  68076. var camera = cams[i];
  68077. var cameraName = camera.name;
  68078. if (this._cameras.indexOf(camera) === -1) {
  68079. this._cameras[cameraName] = camera;
  68080. }
  68081. else if (unique) {
  68082. indicesToDelete.push(i);
  68083. }
  68084. }
  68085. for (i = 0; i < indicesToDelete.length; i++) {
  68086. cameras.splice(indicesToDelete[i], 1);
  68087. }
  68088. for (var renderEffectName in this._renderEffects) {
  68089. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68090. this._renderEffects[renderEffectName]._attachCameras(cams);
  68091. }
  68092. }
  68093. };
  68094. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  68095. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68096. if (!cams) {
  68097. return;
  68098. }
  68099. for (var renderEffectName in this._renderEffects) {
  68100. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68101. this._renderEffects[renderEffectName]._detachCameras(cams);
  68102. }
  68103. }
  68104. for (var i = 0; i < cams.length; i++) {
  68105. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68106. }
  68107. };
  68108. PostProcessRenderPipeline.prototype._update = function () {
  68109. for (var renderEffectName in this._renderEffects) {
  68110. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68111. this._renderEffects[renderEffectName]._update();
  68112. }
  68113. }
  68114. for (var i = 0; i < this._cameras.length; i++) {
  68115. var cameraName = this._cameras[i].name;
  68116. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68117. this._renderEffectsForIsolatedPass[cameraName]._update();
  68118. }
  68119. }
  68120. };
  68121. PostProcessRenderPipeline.prototype._reset = function () {
  68122. this._renderEffects = {};
  68123. this._renderEffectsForIsolatedPass = new Array();
  68124. };
  68125. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  68126. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  68127. var effectKeys = Object.keys(this._renderEffects);
  68128. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68129. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68130. if (postProcesses) {
  68131. postProcesses[0].samples = sampleCount;
  68132. return true;
  68133. }
  68134. }
  68135. return false;
  68136. };
  68137. PostProcessRenderPipeline.prototype.dispose = function () {
  68138. // Must be implemented by children
  68139. };
  68140. __decorate([
  68141. BABYLON.serialize()
  68142. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68143. return PostProcessRenderPipeline;
  68144. }());
  68145. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68146. })(BABYLON || (BABYLON = {}));
  68147. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68148. "use strict";
  68149. var BABYLON;
  68150. (function (BABYLON) {
  68151. /**
  68152. * This represents a depth renderer in Babylon.
  68153. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68154. */
  68155. var DepthRenderer = /** @class */ (function () {
  68156. /**
  68157. * Instantiates a depth renderer
  68158. * @param scene The scene the renderer belongs to
  68159. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68160. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68161. */
  68162. function DepthRenderer(scene, type, camera) {
  68163. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68164. if (camera === void 0) { camera = null; }
  68165. var _this = this;
  68166. this._scene = scene;
  68167. this._camera = camera;
  68168. var engine = scene.getEngine();
  68169. // Render target
  68170. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68171. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68172. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68173. this._depthMap.refreshRate = 1;
  68174. this._depthMap.renderParticles = false;
  68175. this._depthMap.renderList = null;
  68176. // Camera to get depth map from to support multiple concurrent cameras
  68177. this._depthMap.activeCamera = this._camera;
  68178. this._depthMap.ignoreCameraViewport = true;
  68179. this._depthMap.useCameraPostProcesses = false;
  68180. // set default depth value to 1.0 (far away)
  68181. this._depthMap.onClearObservable.add(function (engine) {
  68182. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68183. });
  68184. // Custom render function
  68185. var renderSubMesh = function (subMesh) {
  68186. var mesh = subMesh.getRenderingMesh();
  68187. var scene = _this._scene;
  68188. var engine = scene.getEngine();
  68189. var material = subMesh.getMaterial();
  68190. if (!material) {
  68191. return;
  68192. }
  68193. // Culling and reverse (right handed system)
  68194. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68195. // Managing instances
  68196. var batch = mesh._getInstancesRenderList(subMesh._id);
  68197. if (batch.mustReturn) {
  68198. return;
  68199. }
  68200. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68201. var camera = _this._camera || scene.activeCamera;
  68202. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68203. engine.enableEffect(_this._effect);
  68204. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68205. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68206. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68207. // Alpha test
  68208. if (material && material.needAlphaTesting()) {
  68209. var alphaTexture = material.getAlphaTestTexture();
  68210. if (alphaTexture) {
  68211. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68212. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68213. }
  68214. }
  68215. // Bones
  68216. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68217. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68218. }
  68219. // Draw
  68220. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68221. }
  68222. };
  68223. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68224. var index;
  68225. if (depthOnlySubMeshes.length) {
  68226. engine.setColorWrite(false);
  68227. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68228. renderSubMesh(depthOnlySubMeshes.data[index]);
  68229. }
  68230. engine.setColorWrite(true);
  68231. }
  68232. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68233. renderSubMesh(opaqueSubMeshes.data[index]);
  68234. }
  68235. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68236. renderSubMesh(alphaTestSubMeshes.data[index]);
  68237. }
  68238. };
  68239. }
  68240. /**
  68241. * Creates the depth rendering effect and checks if the effect is ready.
  68242. * @param subMesh The submesh to be used to render the depth map of
  68243. * @param useInstances If multiple world instances should be used
  68244. * @returns if the depth renderer is ready to render the depth map
  68245. */
  68246. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68247. var material = subMesh.getMaterial();
  68248. if (material.disableDepthWrite) {
  68249. return false;
  68250. }
  68251. var defines = [];
  68252. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68253. var mesh = subMesh.getMesh();
  68254. // Alpha test
  68255. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68256. defines.push("#define ALPHATEST");
  68257. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68258. attribs.push(BABYLON.VertexBuffer.UVKind);
  68259. defines.push("#define UV1");
  68260. }
  68261. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68262. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68263. defines.push("#define UV2");
  68264. }
  68265. }
  68266. // Bones
  68267. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68268. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68269. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68270. if (mesh.numBoneInfluencers > 4) {
  68271. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68272. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68273. }
  68274. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68275. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68276. }
  68277. else {
  68278. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68279. }
  68280. // Instances
  68281. if (useInstances) {
  68282. defines.push("#define INSTANCES");
  68283. attribs.push("world0");
  68284. attribs.push("world1");
  68285. attribs.push("world2");
  68286. attribs.push("world3");
  68287. }
  68288. // Get correct effect
  68289. var join = defines.join("\n");
  68290. if (this._cachedDefines !== join) {
  68291. this._cachedDefines = join;
  68292. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68293. }
  68294. return this._effect.isReady();
  68295. };
  68296. /**
  68297. * Gets the texture which the depth map will be written to.
  68298. * @returns The depth map texture
  68299. */
  68300. DepthRenderer.prototype.getDepthMap = function () {
  68301. return this._depthMap;
  68302. };
  68303. /**
  68304. * Disposes of the depth renderer.
  68305. */
  68306. DepthRenderer.prototype.dispose = function () {
  68307. this._depthMap.dispose();
  68308. };
  68309. return DepthRenderer;
  68310. }());
  68311. BABYLON.DepthRenderer = DepthRenderer;
  68312. })(BABYLON || (BABYLON = {}));
  68313. //# sourceMappingURL=babylon.depthRenderer.js.map
  68314. "use strict";
  68315. var BABYLON;
  68316. (function (BABYLON) {
  68317. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68318. __extends(SSAORenderingPipeline, _super);
  68319. /**
  68320. * @constructor
  68321. * @param {string} name - The rendering pipeline name
  68322. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68323. * @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 }
  68324. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68325. */
  68326. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68327. var _this = _super.call(this, scene.getEngine(), name) || this;
  68328. // Members
  68329. /**
  68330. * The PassPostProcess id in the pipeline that contains the original scene color
  68331. */
  68332. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68333. /**
  68334. * The SSAO PostProcess id in the pipeline
  68335. */
  68336. _this.SSAORenderEffect = "SSAORenderEffect";
  68337. /**
  68338. * The horizontal blur PostProcess id in the pipeline
  68339. */
  68340. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68341. /**
  68342. * The vertical blur PostProcess id in the pipeline
  68343. */
  68344. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68345. /**
  68346. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68347. */
  68348. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68349. /**
  68350. * The output strength of the SSAO post-process. Default value is 1.0.
  68351. */
  68352. _this.totalStrength = 1.0;
  68353. /**
  68354. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68355. */
  68356. _this.radius = 0.0001;
  68357. /**
  68358. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68359. * Must not be equal to fallOff and superior to fallOff.
  68360. * Default value is 0.975
  68361. */
  68362. _this.area = 0.0075;
  68363. /**
  68364. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68365. * Must not be equal to area and inferior to area.
  68366. * Default value is 0.0
  68367. */
  68368. _this.fallOff = 0.000001;
  68369. /**
  68370. * The base color of the SSAO post-process
  68371. * The final result is "base + ssao" between [0, 1]
  68372. */
  68373. _this.base = 0.5;
  68374. _this._firstUpdate = true;
  68375. _this._scene = scene;
  68376. // Set up assets
  68377. _this._createRandomTexture();
  68378. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68379. var ssaoRatio = ratio.ssaoRatio || ratio;
  68380. var combineRatio = ratio.combineRatio || ratio;
  68381. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68382. _this._createSSAOPostProcess(ssaoRatio);
  68383. _this._createBlurPostProcess(ssaoRatio);
  68384. _this._createSSAOCombinePostProcess(combineRatio);
  68385. // Set up pipeline
  68386. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68387. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68388. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68389. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68390. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68391. // Finish
  68392. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68393. if (cameras)
  68394. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68395. return _this;
  68396. }
  68397. // Public Methods
  68398. /**
  68399. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68400. */
  68401. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68402. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68403. for (var i = 0; i < this._scene.cameras.length; i++) {
  68404. var camera = this._scene.cameras[i];
  68405. this._originalColorPostProcess.dispose(camera);
  68406. this._ssaoPostProcess.dispose(camera);
  68407. this._blurHPostProcess.dispose(camera);
  68408. this._blurVPostProcess.dispose(camera);
  68409. this._ssaoCombinePostProcess.dispose(camera);
  68410. }
  68411. this._randomTexture.dispose();
  68412. if (disableDepthRender)
  68413. this._scene.disableDepthRenderer();
  68414. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68415. _super.prototype.dispose.call(this);
  68416. };
  68417. // Private Methods
  68418. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68419. var _this = this;
  68420. var size = 16;
  68421. 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);
  68422. 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);
  68423. this._blurHPostProcess.onActivateObservable.add(function () {
  68424. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68425. _this._blurHPostProcess.kernel = size * dw;
  68426. });
  68427. this._blurVPostProcess.onActivateObservable.add(function () {
  68428. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68429. _this._blurVPostProcess.kernel = size * dw;
  68430. });
  68431. };
  68432. SSAORenderingPipeline.prototype._rebuild = function () {
  68433. this._firstUpdate = true;
  68434. _super.prototype._rebuild.call(this);
  68435. };
  68436. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68437. var _this = this;
  68438. var numSamples = 16;
  68439. var sampleSphere = [
  68440. 0.5381, 0.1856, -0.4319,
  68441. 0.1379, 0.2486, 0.4430,
  68442. 0.3371, 0.5679, -0.0057,
  68443. -0.6999, -0.0451, -0.0019,
  68444. 0.0689, -0.1598, -0.8547,
  68445. 0.0560, 0.0069, -0.1843,
  68446. -0.0146, 0.1402, 0.0762,
  68447. 0.0100, -0.1924, -0.0344,
  68448. -0.3577, -0.5301, -0.4358,
  68449. -0.3169, 0.1063, 0.0158,
  68450. 0.0103, -0.5869, 0.0046,
  68451. -0.0897, -0.4940, 0.3287,
  68452. 0.7119, -0.0154, -0.0918,
  68453. -0.0533, 0.0596, -0.5411,
  68454. 0.0352, -0.0631, 0.5460,
  68455. -0.4776, 0.2847, -0.0271
  68456. ];
  68457. var samplesFactor = 1.0 / numSamples;
  68458. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68459. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68460. "area", "fallOff", "base", "range", "viewport"
  68461. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68462. this._ssaoPostProcess.onApply = function (effect) {
  68463. if (_this._firstUpdate) {
  68464. effect.setArray3("sampleSphere", sampleSphere);
  68465. effect.setFloat("samplesFactor", samplesFactor);
  68466. effect.setFloat("randTextureTiles", 4.0);
  68467. }
  68468. effect.setFloat("totalStrength", _this.totalStrength);
  68469. effect.setFloat("radius", _this.radius);
  68470. effect.setFloat("area", _this.area);
  68471. effect.setFloat("fallOff", _this.fallOff);
  68472. effect.setFloat("base", _this.base);
  68473. effect.setTexture("textureSampler", _this._depthTexture);
  68474. effect.setTexture("randomSampler", _this._randomTexture);
  68475. };
  68476. };
  68477. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68478. var _this = this;
  68479. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68480. this._ssaoCombinePostProcess.onApply = function (effect) {
  68481. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68482. };
  68483. };
  68484. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68485. var size = 512;
  68486. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68487. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68488. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68489. var context = this._randomTexture.getContext();
  68490. var rand = function (min, max) {
  68491. return Math.random() * (max - min) + min;
  68492. };
  68493. var randVector = BABYLON.Vector3.Zero();
  68494. for (var x = 0; x < size; x++) {
  68495. for (var y = 0; y < size; y++) {
  68496. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68497. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68498. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68499. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68500. context.fillRect(x, y, 1, 1);
  68501. }
  68502. }
  68503. this._randomTexture.update(false);
  68504. };
  68505. __decorate([
  68506. BABYLON.serialize()
  68507. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68508. __decorate([
  68509. BABYLON.serialize()
  68510. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68511. __decorate([
  68512. BABYLON.serialize()
  68513. ], SSAORenderingPipeline.prototype, "area", void 0);
  68514. __decorate([
  68515. BABYLON.serialize()
  68516. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68517. __decorate([
  68518. BABYLON.serialize()
  68519. ], SSAORenderingPipeline.prototype, "base", void 0);
  68520. return SSAORenderingPipeline;
  68521. }(BABYLON.PostProcessRenderPipeline));
  68522. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68523. })(BABYLON || (BABYLON = {}));
  68524. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68525. "use strict";
  68526. var BABYLON;
  68527. (function (BABYLON) {
  68528. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68529. __extends(SSAO2RenderingPipeline, _super);
  68530. /**
  68531. * @constructor
  68532. * @param {string} name - The rendering pipeline name
  68533. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68534. * @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 }
  68535. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68536. */
  68537. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68538. var _this = _super.call(this, scene.getEngine(), name) || this;
  68539. // Members
  68540. /**
  68541. * The PassPostProcess id in the pipeline that contains the original scene color
  68542. */
  68543. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68544. /**
  68545. * The SSAO PostProcess id in the pipeline
  68546. */
  68547. _this.SSAORenderEffect = "SSAORenderEffect";
  68548. /**
  68549. * The horizontal blur PostProcess id in the pipeline
  68550. */
  68551. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68552. /**
  68553. * The vertical blur PostProcess id in the pipeline
  68554. */
  68555. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68556. /**
  68557. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68558. */
  68559. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68560. /**
  68561. * The output strength of the SSAO post-process. Default value is 1.0.
  68562. */
  68563. _this.totalStrength = 1.0;
  68564. /**
  68565. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68566. */
  68567. _this.maxZ = 100.0;
  68568. /**
  68569. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68570. */
  68571. _this.minZAspect = 0.2;
  68572. /**
  68573. * Number of samples used for the SSAO calculations. Default value is 8
  68574. */
  68575. _this._samples = 8;
  68576. /**
  68577. * Are we using bilateral blur ?
  68578. */
  68579. _this._expensiveBlur = true;
  68580. /**
  68581. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68582. */
  68583. _this.radius = 2.0;
  68584. /**
  68585. * The base color of the SSAO post-process
  68586. * The final result is "base + ssao" between [0, 1]
  68587. */
  68588. _this.base = 0.1;
  68589. _this._firstUpdate = true;
  68590. _this._scene = scene;
  68591. if (!_this.isSupported) {
  68592. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68593. return _this;
  68594. }
  68595. var ssaoRatio = ratio.ssaoRatio || ratio;
  68596. var blurRatio = ratio.blurRatio || ratio;
  68597. // Set up assets
  68598. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68599. _this._createRandomTexture();
  68600. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68601. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68602. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68603. _this._createSSAOPostProcess(1.0);
  68604. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68605. _this._createSSAOCombinePostProcess(blurRatio);
  68606. // Set up pipeline
  68607. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68608. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68609. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68610. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68611. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68612. // Finish
  68613. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68614. if (cameras)
  68615. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68616. return _this;
  68617. }
  68618. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68619. get: function () {
  68620. return this._samples;
  68621. },
  68622. set: function (n) {
  68623. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68624. this._samples = n;
  68625. this._sampleSphere = this._generateHemisphere();
  68626. this._firstUpdate = true;
  68627. },
  68628. enumerable: true,
  68629. configurable: true
  68630. });
  68631. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68632. get: function () {
  68633. return this._expensiveBlur;
  68634. },
  68635. set: function (b) {
  68636. 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"]);
  68637. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68638. this._expensiveBlur = b;
  68639. this._firstUpdate = true;
  68640. },
  68641. enumerable: true,
  68642. configurable: true
  68643. });
  68644. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68645. /**
  68646. * Support test.
  68647. */
  68648. get: function () {
  68649. var engine = BABYLON.Engine.LastCreatedEngine;
  68650. if (!engine) {
  68651. return false;
  68652. }
  68653. return engine.getCaps().drawBuffersExtension;
  68654. },
  68655. enumerable: true,
  68656. configurable: true
  68657. });
  68658. // Public Methods
  68659. /**
  68660. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68661. */
  68662. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68663. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68664. for (var i = 0; i < this._scene.cameras.length; i++) {
  68665. var camera = this._scene.cameras[i];
  68666. this._originalColorPostProcess.dispose(camera);
  68667. this._ssaoPostProcess.dispose(camera);
  68668. this._blurHPostProcess.dispose(camera);
  68669. this._blurVPostProcess.dispose(camera);
  68670. this._ssaoCombinePostProcess.dispose(camera);
  68671. }
  68672. this._randomTexture.dispose();
  68673. if (disableGeometryBufferRenderer)
  68674. this._scene.disableGeometryBufferRenderer();
  68675. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68676. _super.prototype.dispose.call(this);
  68677. };
  68678. // Private Methods
  68679. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68680. var _this = this;
  68681. this._samplerOffsets = [];
  68682. var expensive = this.expensiveBlur;
  68683. for (var i = -8; i < 8; i++) {
  68684. this._samplerOffsets.push(i * 2 + 0.5);
  68685. }
  68686. 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");
  68687. this._blurHPostProcess.onApply = function (effect) {
  68688. if (!_this._scene.activeCamera) {
  68689. return;
  68690. }
  68691. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68692. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68693. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68694. effect.setFloat("radius", _this.radius);
  68695. effect.setTexture("depthSampler", _this._depthTexture);
  68696. if (_this._firstUpdate) {
  68697. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68698. }
  68699. };
  68700. 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");
  68701. this._blurVPostProcess.onApply = function (effect) {
  68702. if (!_this._scene.activeCamera) {
  68703. return;
  68704. }
  68705. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68706. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68707. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68708. effect.setFloat("radius", _this.radius);
  68709. effect.setTexture("depthSampler", _this._depthTexture);
  68710. if (_this._firstUpdate) {
  68711. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68712. _this._firstUpdate = false;
  68713. }
  68714. };
  68715. };
  68716. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68717. this._firstUpdate = true;
  68718. _super.prototype._rebuild.call(this);
  68719. };
  68720. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68721. var numSamples = this.samples;
  68722. var result = [];
  68723. var vector, scale;
  68724. var rand = function (min, max) {
  68725. return Math.random() * (max - min) + min;
  68726. };
  68727. var i = 0;
  68728. while (i < numSamples) {
  68729. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68730. vector.normalize();
  68731. scale = i / numSamples;
  68732. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68733. vector.scaleInPlace(scale);
  68734. result.push(vector.x, vector.y, vector.z);
  68735. i++;
  68736. }
  68737. return result;
  68738. };
  68739. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68740. var _this = this;
  68741. var numSamples = this.samples;
  68742. this._sampleSphere = this._generateHemisphere();
  68743. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68744. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68745. "base", "range", "projection", "near", "far", "texelSize",
  68746. "xViewport", "yViewport", "maxZ", "minZAspect"
  68747. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68748. this._ssaoPostProcess.onApply = function (effect) {
  68749. if (_this._firstUpdate) {
  68750. effect.setArray3("sampleSphere", _this._sampleSphere);
  68751. effect.setFloat("randTextureTiles", 4.0);
  68752. }
  68753. if (!_this._scene.activeCamera) {
  68754. return;
  68755. }
  68756. effect.setFloat("samplesFactor", 1 / _this.samples);
  68757. effect.setFloat("totalStrength", _this.totalStrength);
  68758. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68759. effect.setFloat("radius", _this.radius);
  68760. effect.setFloat("maxZ", _this.maxZ);
  68761. effect.setFloat("minZAspect", _this.minZAspect);
  68762. effect.setFloat("base", _this.base);
  68763. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68764. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68765. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68766. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68767. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68768. effect.setTexture("textureSampler", _this._depthTexture);
  68769. effect.setTexture("normalSampler", _this._normalTexture);
  68770. effect.setTexture("randomSampler", _this._randomTexture);
  68771. };
  68772. };
  68773. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68774. var _this = this;
  68775. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68776. this._ssaoCombinePostProcess.onApply = function (effect) {
  68777. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68778. };
  68779. };
  68780. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68781. var size = 512;
  68782. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68783. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68784. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68785. var context = this._randomTexture.getContext();
  68786. var rand = function (min, max) {
  68787. return Math.random() * (max - min) + min;
  68788. };
  68789. var randVector = BABYLON.Vector3.Zero();
  68790. for (var x = 0; x < size; x++) {
  68791. for (var y = 0; y < size; y++) {
  68792. randVector.x = rand(0.0, 1.0);
  68793. randVector.y = rand(0.0, 1.0);
  68794. randVector.z = 0.0;
  68795. randVector.normalize();
  68796. randVector.scaleInPlace(255);
  68797. randVector.x = Math.floor(randVector.x);
  68798. randVector.y = Math.floor(randVector.y);
  68799. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68800. context.fillRect(x, y, 1, 1);
  68801. }
  68802. }
  68803. this._randomTexture.update(false);
  68804. };
  68805. __decorate([
  68806. BABYLON.serialize()
  68807. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68808. __decorate([
  68809. BABYLON.serialize()
  68810. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68811. __decorate([
  68812. BABYLON.serialize()
  68813. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68814. __decorate([
  68815. BABYLON.serialize("samples")
  68816. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68817. __decorate([
  68818. BABYLON.serialize("expensiveBlur")
  68819. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68820. __decorate([
  68821. BABYLON.serialize()
  68822. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68823. __decorate([
  68824. BABYLON.serialize()
  68825. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68826. return SSAO2RenderingPipeline;
  68827. }(BABYLON.PostProcessRenderPipeline));
  68828. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68829. })(BABYLON || (BABYLON = {}));
  68830. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68831. "use strict";
  68832. // BABYLON.JS Chromatic Aberration GLSL Shader
  68833. // Author: Olivier Guyot
  68834. // Separates very slightly R, G and B colors on the edges of the screen
  68835. // Inspired by Francois Tarlier & Martins Upitis
  68836. var BABYLON;
  68837. (function (BABYLON) {
  68838. var LensRenderingPipeline = /** @class */ (function (_super) {
  68839. __extends(LensRenderingPipeline, _super);
  68840. /**
  68841. * @constructor
  68842. *
  68843. * Effect parameters are as follow:
  68844. * {
  68845. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68846. * edge_blur: number; // from 0 to x (1 for realism)
  68847. * distortion: number; // from 0 to x (1 for realism)
  68848. * grain_amount: number; // from 0 to 1
  68849. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68850. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68851. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68852. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68853. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68854. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68855. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68856. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68857. * }
  68858. * Note: if an effect parameter is unset, effect is disabled
  68859. *
  68860. * @param {string} name - The rendering pipeline name
  68861. * @param {object} parameters - An object containing all parameters (see above)
  68862. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68863. * @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)
  68864. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68865. */
  68866. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68867. if (ratio === void 0) { ratio = 1.0; }
  68868. var _this = _super.call(this, scene.getEngine(), name) || this;
  68869. // Lens effects can be of the following:
  68870. // - chromatic aberration (slight shift of RGB colors)
  68871. // - blur on the edge of the lens
  68872. // - lens distortion
  68873. // - depth-of-field blur & highlights enhancing
  68874. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68875. // - grain effect (noise or custom texture)
  68876. // Two additional texture samplers are needed:
  68877. // - depth map (for depth-of-field)
  68878. // - grain texture
  68879. /**
  68880. * The chromatic aberration PostProcess id in the pipeline
  68881. */
  68882. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68883. /**
  68884. * The highlights enhancing PostProcess id in the pipeline
  68885. */
  68886. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68887. /**
  68888. * The depth-of-field PostProcess id in the pipeline
  68889. */
  68890. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68891. _this._scene = scene;
  68892. // Fetch texture samplers
  68893. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68894. if (parameters.grain_texture) {
  68895. _this._grainTexture = parameters.grain_texture;
  68896. }
  68897. else {
  68898. _this._createGrainTexture();
  68899. }
  68900. // save parameters
  68901. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68902. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68903. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68904. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68905. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68906. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68907. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68908. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68909. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68910. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68911. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68912. // Create effects
  68913. _this._createChromaticAberrationPostProcess(ratio);
  68914. _this._createHighlightsPostProcess(ratio);
  68915. _this._createDepthOfFieldPostProcess(ratio / 4);
  68916. // Set up pipeline
  68917. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68918. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68919. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68920. if (_this._highlightsGain === -1) {
  68921. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68922. }
  68923. // Finish
  68924. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68925. if (cameras) {
  68926. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68927. }
  68928. return _this;
  68929. }
  68930. // public methods (self explanatory)
  68931. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68932. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68933. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68934. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68935. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68936. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68937. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68938. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68939. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68940. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68941. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68942. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68943. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68944. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68945. };
  68946. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68947. this._highlightsPostProcess.updateEffect();
  68948. };
  68949. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68950. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68951. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68952. this._highlightsGain = amount;
  68953. };
  68954. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68955. if (this._highlightsGain === -1) {
  68956. this._highlightsGain = 1.0;
  68957. }
  68958. this._highlightsThreshold = amount;
  68959. };
  68960. LensRenderingPipeline.prototype.disableHighlights = function () {
  68961. this._highlightsGain = -1;
  68962. };
  68963. /**
  68964. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68965. */
  68966. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68967. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68968. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68969. this._chromaticAberrationPostProcess = null;
  68970. this._highlightsPostProcess = null;
  68971. this._depthOfFieldPostProcess = null;
  68972. this._grainTexture.dispose();
  68973. if (disableDepthRender)
  68974. this._scene.disableDepthRenderer();
  68975. };
  68976. // colors shifting and distortion
  68977. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68978. var _this = this;
  68979. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68980. [], // samplers
  68981. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68982. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68983. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68984. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68985. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68986. effect.setFloat('radialIntensity', 1);
  68987. effect.setFloat2('direction', 17, 17);
  68988. effect.setFloat2('centerPosition', 0.5, 0.5);
  68989. };
  68990. };
  68991. // highlights enhancing
  68992. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68993. var _this = this;
  68994. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68995. [], // samplers
  68996. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68997. this._highlightsPostProcess.onApply = function (effect) {
  68998. effect.setFloat('gain', _this._highlightsGain);
  68999. effect.setFloat('threshold', _this._highlightsThreshold);
  69000. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  69001. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69002. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69003. };
  69004. };
  69005. // colors shifting and distortion
  69006. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  69007. var _this = this;
  69008. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  69009. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  69010. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  69011. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69012. this._depthOfFieldPostProcess.onApply = function (effect) {
  69013. effect.setTexture("depthSampler", _this._depthTexture);
  69014. effect.setTexture("grainSampler", _this._grainTexture);
  69015. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69016. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69017. effect.setFloat('grain_amount', _this._grainAmount);
  69018. effect.setBool('blur_noise', _this._blurNoise);
  69019. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69020. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69021. effect.setFloat('distortion', _this._distortion);
  69022. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69023. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69024. effect.setFloat('aperture', _this._dofAperture);
  69025. effect.setFloat('darken', _this._dofDarken);
  69026. effect.setFloat('edge_blur', _this._edgeBlur);
  69027. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69028. if (_this._scene.activeCamera) {
  69029. effect.setFloat('near', _this._scene.activeCamera.minZ);
  69030. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  69031. }
  69032. };
  69033. };
  69034. // creates a black and white random noise texture, 512x512
  69035. LensRenderingPipeline.prototype._createGrainTexture = function () {
  69036. var size = 512;
  69037. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69038. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69039. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69040. var context = this._grainTexture.getContext();
  69041. var rand = function (min, max) {
  69042. return Math.random() * (max - min) + min;
  69043. };
  69044. var value;
  69045. for (var x = 0; x < size; x++) {
  69046. for (var y = 0; y < size; y++) {
  69047. value = Math.floor(rand(0.42, 0.58) * 255);
  69048. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  69049. context.fillRect(x, y, 1, 1);
  69050. }
  69051. }
  69052. this._grainTexture.update(false);
  69053. };
  69054. return LensRenderingPipeline;
  69055. }(BABYLON.PostProcessRenderPipeline));
  69056. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  69057. })(BABYLON || (BABYLON = {}));
  69058. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  69059. "use strict";
  69060. var BABYLON;
  69061. (function (BABYLON) {
  69062. var StandardRenderingPipeline = /** @class */ (function (_super) {
  69063. __extends(StandardRenderingPipeline, _super);
  69064. /**
  69065. * @constructor
  69066. * @param {string} name - The rendering pipeline name
  69067. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69068. * @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)
  69069. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  69070. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69071. */
  69072. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  69073. if (originalPostProcess === void 0) { originalPostProcess = null; }
  69074. var _this = _super.call(this, scene.getEngine(), name) || this;
  69075. _this.downSampleX4PostProcess = null;
  69076. _this.brightPassPostProcess = null;
  69077. _this.blurHPostProcesses = [];
  69078. _this.blurVPostProcesses = [];
  69079. _this.textureAdderPostProcess = null;
  69080. _this.volumetricLightPostProcess = null;
  69081. _this.volumetricLightSmoothXPostProcess = null;
  69082. _this.volumetricLightSmoothYPostProcess = null;
  69083. _this.volumetricLightMergePostProces = null;
  69084. _this.volumetricLightFinalPostProcess = null;
  69085. _this.luminancePostProcess = null;
  69086. _this.luminanceDownSamplePostProcesses = [];
  69087. _this.hdrPostProcess = null;
  69088. _this.textureAdderFinalPostProcess = null;
  69089. _this.lensFlareFinalPostProcess = null;
  69090. _this.hdrFinalPostProcess = null;
  69091. _this.lensFlarePostProcess = null;
  69092. _this.lensFlareComposePostProcess = null;
  69093. _this.motionBlurPostProcess = null;
  69094. _this.depthOfFieldPostProcess = null;
  69095. // Values
  69096. _this.brightThreshold = 1.0;
  69097. _this.blurWidth = 512.0;
  69098. _this.horizontalBlur = false;
  69099. _this.exposure = 1.0;
  69100. _this.lensTexture = null;
  69101. _this.volumetricLightCoefficient = 0.2;
  69102. _this.volumetricLightPower = 4.0;
  69103. _this.volumetricLightBlurScale = 64.0;
  69104. _this.sourceLight = null;
  69105. _this.hdrMinimumLuminance = 1.0;
  69106. _this.hdrDecreaseRate = 0.5;
  69107. _this.hdrIncreaseRate = 0.5;
  69108. _this.lensColorTexture = null;
  69109. _this.lensFlareStrength = 20.0;
  69110. _this.lensFlareGhostDispersal = 1.4;
  69111. _this.lensFlareHaloWidth = 0.7;
  69112. _this.lensFlareDistortionStrength = 16.0;
  69113. _this.lensStarTexture = null;
  69114. _this.lensFlareDirtTexture = null;
  69115. _this.depthOfFieldDistance = 10.0;
  69116. _this.depthOfFieldBlurWidth = 64.0;
  69117. _this.motionStrength = 1.0;
  69118. // IAnimatable
  69119. _this.animations = [];
  69120. _this._currentDepthOfFieldSource = null;
  69121. _this._hdrCurrentLuminance = 1.0;
  69122. // Getters and setters
  69123. _this._bloomEnabled = true;
  69124. _this._depthOfFieldEnabled = false;
  69125. _this._vlsEnabled = false;
  69126. _this._lensFlareEnabled = false;
  69127. _this._hdrEnabled = false;
  69128. _this._motionBlurEnabled = false;
  69129. _this._motionBlurSamples = 64.0;
  69130. _this._volumetricLightStepsCount = 50.0;
  69131. _this._cameras = cameras || [];
  69132. // Initialize
  69133. _this._scene = scene;
  69134. _this._basePostProcess = originalPostProcess;
  69135. _this._ratio = ratio;
  69136. // Misc
  69137. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69138. // Finish
  69139. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69140. _this._buildPipeline();
  69141. return _this;
  69142. }
  69143. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69144. get: function () {
  69145. return this._bloomEnabled;
  69146. },
  69147. set: function (enabled) {
  69148. if (this._bloomEnabled === enabled) {
  69149. return;
  69150. }
  69151. this._bloomEnabled = enabled;
  69152. this._buildPipeline();
  69153. },
  69154. enumerable: true,
  69155. configurable: true
  69156. });
  69157. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69158. get: function () {
  69159. return this._depthOfFieldEnabled;
  69160. },
  69161. set: function (enabled) {
  69162. if (this._depthOfFieldEnabled === enabled) {
  69163. return;
  69164. }
  69165. this._depthOfFieldEnabled = enabled;
  69166. this._buildPipeline();
  69167. },
  69168. enumerable: true,
  69169. configurable: true
  69170. });
  69171. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69172. get: function () {
  69173. return this._lensFlareEnabled;
  69174. },
  69175. set: function (enabled) {
  69176. if (this._lensFlareEnabled === enabled) {
  69177. return;
  69178. }
  69179. this._lensFlareEnabled = enabled;
  69180. this._buildPipeline();
  69181. },
  69182. enumerable: true,
  69183. configurable: true
  69184. });
  69185. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69186. get: function () {
  69187. return this._hdrEnabled;
  69188. },
  69189. set: function (enabled) {
  69190. if (this._hdrEnabled === enabled) {
  69191. return;
  69192. }
  69193. this._hdrEnabled = enabled;
  69194. this._buildPipeline();
  69195. },
  69196. enumerable: true,
  69197. configurable: true
  69198. });
  69199. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69200. get: function () {
  69201. return this._vlsEnabled;
  69202. },
  69203. set: function (enabled) {
  69204. if (this._vlsEnabled === enabled) {
  69205. return;
  69206. }
  69207. if (enabled) {
  69208. var geometry = this._scene.enableGeometryBufferRenderer();
  69209. if (!geometry) {
  69210. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69211. return;
  69212. }
  69213. }
  69214. this._vlsEnabled = enabled;
  69215. this._buildPipeline();
  69216. },
  69217. enumerable: true,
  69218. configurable: true
  69219. });
  69220. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69221. get: function () {
  69222. return this._motionBlurEnabled;
  69223. },
  69224. set: function (enabled) {
  69225. if (this._motionBlurEnabled === enabled) {
  69226. return;
  69227. }
  69228. this._motionBlurEnabled = enabled;
  69229. this._buildPipeline();
  69230. },
  69231. enumerable: true,
  69232. configurable: true
  69233. });
  69234. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69235. get: function () {
  69236. return this._volumetricLightStepsCount;
  69237. },
  69238. set: function (count) {
  69239. if (this.volumetricLightPostProcess) {
  69240. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69241. }
  69242. this._volumetricLightStepsCount = count;
  69243. },
  69244. enumerable: true,
  69245. configurable: true
  69246. });
  69247. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69248. get: function () {
  69249. return this._motionBlurSamples;
  69250. },
  69251. set: function (samples) {
  69252. if (this.motionBlurPostProcess) {
  69253. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69254. }
  69255. this._motionBlurSamples = samples;
  69256. },
  69257. enumerable: true,
  69258. configurable: true
  69259. });
  69260. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69261. var _this = this;
  69262. var ratio = this._ratio;
  69263. var scene = this._scene;
  69264. this._disposePostProcesses();
  69265. this._reset();
  69266. // Create pass post-process
  69267. if (!this._basePostProcess) {
  69268. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69269. this.originalPostProcess.onApply = function (effect) {
  69270. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69271. };
  69272. }
  69273. else {
  69274. this.originalPostProcess = this._basePostProcess;
  69275. }
  69276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69277. this._currentDepthOfFieldSource = this.originalPostProcess;
  69278. if (this._vlsEnabled) {
  69279. // Create volumetric light
  69280. this._createVolumetricLightPostProcess(scene, ratio);
  69281. // Create volumetric light final post-process
  69282. 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);
  69283. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69284. }
  69285. if (this._bloomEnabled) {
  69286. // Create down sample X4 post-process
  69287. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69288. // Create bright pass post-process
  69289. this._createBrightPassPostProcess(scene, ratio / 2);
  69290. // Create gaussian blur post-processes (down sampling blurs)
  69291. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69292. // Create texture adder post-process
  69293. this._createTextureAdderPostProcess(scene, ratio);
  69294. // Create depth-of-field source post-process
  69295. 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);
  69296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69297. }
  69298. if (this._lensFlareEnabled) {
  69299. // Create lens flare post-process
  69300. this._createLensFlarePostProcess(scene, ratio);
  69301. // Create depth-of-field source post-process post lens-flare and disable it now
  69302. 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);
  69303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69304. }
  69305. if (this._hdrEnabled) {
  69306. // Create luminance
  69307. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69308. // Create HDR
  69309. this._createHdrPostProcess(scene, ratio);
  69310. // Create depth-of-field source post-process post hdr and disable it now
  69311. 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);
  69312. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69313. }
  69314. if (this._depthOfFieldEnabled) {
  69315. // Create gaussian blur used by depth-of-field
  69316. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69317. // Create depth-of-field post-process
  69318. this._createDepthOfFieldPostProcess(scene, ratio);
  69319. }
  69320. if (this._motionBlurEnabled) {
  69321. // Create motion blur post-process
  69322. this._createMotionBlurPostProcess(scene, ratio);
  69323. }
  69324. if (this._cameras !== null) {
  69325. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69326. }
  69327. };
  69328. // Down Sample X4 Post-Processs
  69329. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69330. var _this = this;
  69331. var downSampleX4Offsets = new Array(32);
  69332. 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);
  69333. this.downSampleX4PostProcess.onApply = function (effect) {
  69334. var id = 0;
  69335. var width = _this.downSampleX4PostProcess.width;
  69336. var height = _this.downSampleX4PostProcess.height;
  69337. for (var i = -2; i < 2; i++) {
  69338. for (var j = -2; j < 2; j++) {
  69339. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69340. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69341. id += 2;
  69342. }
  69343. }
  69344. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69345. };
  69346. // Add to pipeline
  69347. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69348. };
  69349. // Brightpass Post-Process
  69350. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69351. var _this = this;
  69352. var brightOffsets = new Array(8);
  69353. 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);
  69354. this.brightPassPostProcess.onApply = function (effect) {
  69355. var sU = (1.0 / _this.brightPassPostProcess.width);
  69356. var sV = (1.0 / _this.brightPassPostProcess.height);
  69357. brightOffsets[0] = -0.5 * sU;
  69358. brightOffsets[1] = 0.5 * sV;
  69359. brightOffsets[2] = 0.5 * sU;
  69360. brightOffsets[3] = 0.5 * sV;
  69361. brightOffsets[4] = -0.5 * sU;
  69362. brightOffsets[5] = -0.5 * sV;
  69363. brightOffsets[6] = 0.5 * sU;
  69364. brightOffsets[7] = -0.5 * sV;
  69365. effect.setArray2("dsOffsets", brightOffsets);
  69366. effect.setFloat("brightThreshold", _this.brightThreshold);
  69367. };
  69368. // Add to pipeline
  69369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69370. };
  69371. // Create blur H&V post-processes
  69372. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69373. var _this = this;
  69374. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69375. var engine = scene.getEngine();
  69376. 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);
  69377. 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);
  69378. blurX.onActivateObservable.add(function () {
  69379. var dw = blurX.width / engine.getRenderWidth();
  69380. blurX.kernel = _this[blurWidthKey] * dw;
  69381. });
  69382. blurY.onActivateObservable.add(function () {
  69383. var dw = blurY.height / engine.getRenderHeight();
  69384. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69385. });
  69386. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69387. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69388. this.blurHPostProcesses.push(blurX);
  69389. this.blurVPostProcesses.push(blurY);
  69390. };
  69391. // Create texture adder post-process
  69392. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69393. var _this = this;
  69394. 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);
  69395. this.textureAdderPostProcess.onApply = function (effect) {
  69396. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69397. effect.setTexture("lensSampler", _this.lensTexture);
  69398. effect.setFloat("exposure", _this.exposure);
  69399. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69400. };
  69401. // Add to pipeline
  69402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69403. };
  69404. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69405. var _this = this;
  69406. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69407. geometryRenderer.enablePosition = true;
  69408. var geometry = geometryRenderer.getGBuffer();
  69409. // Base post-process
  69410. 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));
  69411. var depthValues = BABYLON.Vector2.Zero();
  69412. this.volumetricLightPostProcess.onApply = function (effect) {
  69413. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69414. var generator = _this.sourceLight.getShadowGenerator();
  69415. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69416. effect.setTexture("positionSampler", geometry.textures[2]);
  69417. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69418. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69419. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69420. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69421. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69422. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69423. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69424. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69425. effect.setVector2("depthValues", depthValues);
  69426. }
  69427. };
  69428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69429. // Smooth
  69430. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69431. // Merge
  69432. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69433. this.volumetricLightMergePostProces.onApply = function (effect) {
  69434. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69435. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69436. };
  69437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69438. };
  69439. // Create luminance
  69440. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69441. var _this = this;
  69442. // Create luminance
  69443. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69444. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69445. var offsets = [];
  69446. this.luminancePostProcess.onApply = function (effect) {
  69447. var sU = (1.0 / _this.luminancePostProcess.width);
  69448. var sV = (1.0 / _this.luminancePostProcess.height);
  69449. offsets[0] = -0.5 * sU;
  69450. offsets[1] = 0.5 * sV;
  69451. offsets[2] = 0.5 * sU;
  69452. offsets[3] = 0.5 * sV;
  69453. offsets[4] = -0.5 * sU;
  69454. offsets[5] = -0.5 * sV;
  69455. offsets[6] = 0.5 * sU;
  69456. offsets[7] = -0.5 * sV;
  69457. effect.setArray2("lumOffsets", offsets);
  69458. };
  69459. // Add to pipeline
  69460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69461. // Create down sample luminance
  69462. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69463. var size = Math.pow(3, i);
  69464. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69465. if (i === 0) {
  69466. defines += "#define FINAL_DOWN_SAMPLER";
  69467. }
  69468. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69469. this.luminanceDownSamplePostProcesses.push(postProcess);
  69470. }
  69471. // Create callbacks and add effects
  69472. var lastLuminance = this.luminancePostProcess;
  69473. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69474. var downSampleOffsets = new Array(18);
  69475. pp.onApply = function (effect) {
  69476. if (!lastLuminance) {
  69477. return;
  69478. }
  69479. var id = 0;
  69480. for (var x = -1; x < 2; x++) {
  69481. for (var y = -1; y < 2; y++) {
  69482. downSampleOffsets[id] = x / lastLuminance.width;
  69483. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69484. id += 2;
  69485. }
  69486. }
  69487. effect.setArray2("dsOffsets", downSampleOffsets);
  69488. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69489. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69490. lastLuminance = _this.luminancePostProcess;
  69491. }
  69492. else {
  69493. lastLuminance = pp;
  69494. }
  69495. };
  69496. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69497. pp.onAfterRender = function (effect) {
  69498. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69499. 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);
  69500. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69501. };
  69502. }
  69503. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69504. });
  69505. };
  69506. // Create HDR post-process
  69507. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69508. var _this = this;
  69509. 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);
  69510. var outputLiminance = 1;
  69511. var time = 0;
  69512. var lastTime = 0;
  69513. this.hdrPostProcess.onApply = function (effect) {
  69514. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69515. time += scene.getEngine().getDeltaTime();
  69516. if (outputLiminance < 0) {
  69517. outputLiminance = _this._hdrCurrentLuminance;
  69518. }
  69519. else {
  69520. var dt = (lastTime - time) / 1000.0;
  69521. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69522. outputLiminance += _this.hdrDecreaseRate * dt;
  69523. }
  69524. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69525. outputLiminance -= _this.hdrIncreaseRate * dt;
  69526. }
  69527. else {
  69528. outputLiminance = _this._hdrCurrentLuminance;
  69529. }
  69530. }
  69531. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69532. effect.setFloat("averageLuminance", outputLiminance);
  69533. lastTime = time;
  69534. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69535. };
  69536. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69537. };
  69538. // Create lens flare post-process
  69539. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69540. var _this = this;
  69541. 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);
  69542. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69543. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69544. 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);
  69545. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69546. var resolution = new BABYLON.Vector2(0, 0);
  69547. // Lens flare
  69548. this.lensFlarePostProcess.onApply = function (effect) {
  69549. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69550. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69551. effect.setFloat("strength", _this.lensFlareStrength);
  69552. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69553. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69554. // Shift
  69555. resolution.x = _this.lensFlarePostProcess.width;
  69556. resolution.y = _this.lensFlarePostProcess.height;
  69557. effect.setVector2("resolution", resolution);
  69558. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69559. };
  69560. // Compose
  69561. 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);
  69562. 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);
  69563. this.lensFlareComposePostProcess.onApply = function (effect) {
  69564. if (!_this._scene.activeCamera) {
  69565. return;
  69566. }
  69567. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69568. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69569. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69570. // Lens start rotation matrix
  69571. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69572. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69573. 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));
  69574. camRot *= 4.0;
  69575. 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);
  69576. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69577. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69578. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69579. };
  69580. };
  69581. // Create depth-of-field post-process
  69582. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69583. var _this = this;
  69584. 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);
  69585. this.depthOfFieldPostProcess.onApply = function (effect) {
  69586. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69587. effect.setTexture("depthSampler", _this._getDepthTexture());
  69588. effect.setFloat("distance", _this.depthOfFieldDistance);
  69589. };
  69590. // Add to pipeline
  69591. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69592. };
  69593. // Create motion blur post-process
  69594. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69595. var _this = this;
  69596. 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);
  69597. var motionScale = 0;
  69598. var prevViewProjection = BABYLON.Matrix.Identity();
  69599. var invViewProjection = BABYLON.Matrix.Identity();
  69600. var viewProjection = BABYLON.Matrix.Identity();
  69601. var screenSize = BABYLON.Vector2.Zero();
  69602. this.motionBlurPostProcess.onApply = function (effect) {
  69603. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69604. viewProjection.invertToRef(invViewProjection);
  69605. effect.setMatrix("inverseViewProjection", invViewProjection);
  69606. effect.setMatrix("prevViewProjection", prevViewProjection);
  69607. prevViewProjection = viewProjection;
  69608. screenSize.x = _this.motionBlurPostProcess.width;
  69609. screenSize.y = _this.motionBlurPostProcess.height;
  69610. effect.setVector2("screenSize", screenSize);
  69611. motionScale = scene.getEngine().getFps() / 60.0;
  69612. effect.setFloat("motionScale", motionScale);
  69613. effect.setFloat("motionStrength", _this.motionStrength);
  69614. effect.setTexture("depthSampler", _this._getDepthTexture());
  69615. };
  69616. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69617. };
  69618. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69619. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69620. var renderer = this._scene.enableGeometryBufferRenderer();
  69621. return renderer.getGBuffer().textures[0];
  69622. }
  69623. return this._scene.enableDepthRenderer().getDepthMap();
  69624. };
  69625. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69626. for (var i = 0; i < this._cameras.length; i++) {
  69627. var camera = this._cameras[i];
  69628. if (this.originalPostProcess) {
  69629. this.originalPostProcess.dispose(camera);
  69630. }
  69631. if (this.downSampleX4PostProcess) {
  69632. this.downSampleX4PostProcess.dispose(camera);
  69633. }
  69634. if (this.brightPassPostProcess) {
  69635. this.brightPassPostProcess.dispose(camera);
  69636. }
  69637. if (this.textureAdderPostProcess) {
  69638. this.textureAdderPostProcess.dispose(camera);
  69639. }
  69640. if (this.textureAdderFinalPostProcess) {
  69641. this.textureAdderFinalPostProcess.dispose(camera);
  69642. }
  69643. if (this.volumetricLightPostProcess) {
  69644. this.volumetricLightPostProcess.dispose(camera);
  69645. }
  69646. if (this.volumetricLightSmoothXPostProcess) {
  69647. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69648. }
  69649. if (this.volumetricLightSmoothYPostProcess) {
  69650. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69651. }
  69652. if (this.volumetricLightMergePostProces) {
  69653. this.volumetricLightMergePostProces.dispose(camera);
  69654. }
  69655. if (this.volumetricLightFinalPostProcess) {
  69656. this.volumetricLightFinalPostProcess.dispose(camera);
  69657. }
  69658. if (this.lensFlarePostProcess) {
  69659. this.lensFlarePostProcess.dispose(camera);
  69660. }
  69661. if (this.lensFlareComposePostProcess) {
  69662. this.lensFlareComposePostProcess.dispose(camera);
  69663. }
  69664. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69665. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69666. }
  69667. if (this.luminancePostProcess) {
  69668. this.luminancePostProcess.dispose(camera);
  69669. }
  69670. if (this.hdrPostProcess) {
  69671. this.hdrPostProcess.dispose(camera);
  69672. }
  69673. if (this.hdrFinalPostProcess) {
  69674. this.hdrFinalPostProcess.dispose(camera);
  69675. }
  69676. if (this.depthOfFieldPostProcess) {
  69677. this.depthOfFieldPostProcess.dispose(camera);
  69678. }
  69679. if (this.motionBlurPostProcess) {
  69680. this.motionBlurPostProcess.dispose(camera);
  69681. }
  69682. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69683. this.blurHPostProcesses[j].dispose(camera);
  69684. }
  69685. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69686. this.blurVPostProcesses[j].dispose(camera);
  69687. }
  69688. }
  69689. this.originalPostProcess = null;
  69690. this.downSampleX4PostProcess = null;
  69691. this.brightPassPostProcess = null;
  69692. this.textureAdderPostProcess = null;
  69693. this.textureAdderFinalPostProcess = null;
  69694. this.volumetricLightPostProcess = null;
  69695. this.volumetricLightSmoothXPostProcess = null;
  69696. this.volumetricLightSmoothYPostProcess = null;
  69697. this.volumetricLightMergePostProces = null;
  69698. this.volumetricLightFinalPostProcess = null;
  69699. this.lensFlarePostProcess = null;
  69700. this.lensFlareComposePostProcess = null;
  69701. this.luminancePostProcess = null;
  69702. this.hdrPostProcess = null;
  69703. this.hdrFinalPostProcess = null;
  69704. this.depthOfFieldPostProcess = null;
  69705. this.motionBlurPostProcess = null;
  69706. this.luminanceDownSamplePostProcesses = [];
  69707. this.blurHPostProcesses = [];
  69708. this.blurVPostProcesses = [];
  69709. };
  69710. // Dispose
  69711. StandardRenderingPipeline.prototype.dispose = function () {
  69712. this._disposePostProcesses();
  69713. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69714. _super.prototype.dispose.call(this);
  69715. };
  69716. // Serialize rendering pipeline
  69717. StandardRenderingPipeline.prototype.serialize = function () {
  69718. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69719. serializationObject.customType = "StandardRenderingPipeline";
  69720. return serializationObject;
  69721. };
  69722. /**
  69723. * Static members
  69724. */
  69725. // Parse serialized pipeline
  69726. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69727. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69728. };
  69729. // Luminance steps
  69730. StandardRenderingPipeline.LuminanceSteps = 6;
  69731. __decorate([
  69732. BABYLON.serialize()
  69733. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69734. __decorate([
  69735. BABYLON.serialize()
  69736. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69737. __decorate([
  69738. BABYLON.serialize()
  69739. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69740. __decorate([
  69741. BABYLON.serialize()
  69742. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69743. __decorate([
  69744. BABYLON.serializeAsTexture("lensTexture")
  69745. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69746. __decorate([
  69747. BABYLON.serialize()
  69748. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69749. __decorate([
  69750. BABYLON.serialize()
  69751. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69752. __decorate([
  69753. BABYLON.serialize()
  69754. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69755. __decorate([
  69756. BABYLON.serialize()
  69757. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69758. __decorate([
  69759. BABYLON.serialize()
  69760. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69761. __decorate([
  69762. BABYLON.serialize()
  69763. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69764. __decorate([
  69765. BABYLON.serializeAsTexture("lensColorTexture")
  69766. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69767. __decorate([
  69768. BABYLON.serialize()
  69769. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69770. __decorate([
  69771. BABYLON.serialize()
  69772. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69773. __decorate([
  69774. BABYLON.serialize()
  69775. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69776. __decorate([
  69777. BABYLON.serialize()
  69778. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69779. __decorate([
  69780. BABYLON.serializeAsTexture("lensStarTexture")
  69781. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69782. __decorate([
  69783. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69784. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69785. __decorate([
  69786. BABYLON.serialize()
  69787. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69788. __decorate([
  69789. BABYLON.serialize()
  69790. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69791. __decorate([
  69792. BABYLON.serialize()
  69793. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69794. __decorate([
  69795. BABYLON.serialize()
  69796. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69797. __decorate([
  69798. BABYLON.serialize()
  69799. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69800. __decorate([
  69801. BABYLON.serialize()
  69802. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69803. __decorate([
  69804. BABYLON.serialize()
  69805. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69806. __decorate([
  69807. BABYLON.serialize()
  69808. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69809. __decorate([
  69810. BABYLON.serialize()
  69811. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69812. __decorate([
  69813. BABYLON.serialize()
  69814. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69815. __decorate([
  69816. BABYLON.serialize()
  69817. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69818. __decorate([
  69819. BABYLON.serialize()
  69820. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69821. return StandardRenderingPipeline;
  69822. }(BABYLON.PostProcessRenderPipeline));
  69823. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69824. })(BABYLON || (BABYLON = {}));
  69825. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69826. "use strict";
  69827. var BABYLON;
  69828. (function (BABYLON) {
  69829. var FxaaPostProcess = /** @class */ (function (_super) {
  69830. __extends(FxaaPostProcess, _super);
  69831. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69832. if (camera === void 0) { camera = null; }
  69833. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69834. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69835. _this.onApplyObservable.add(function (effect) {
  69836. var texelSize = _this.texelSize;
  69837. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69838. });
  69839. return _this;
  69840. }
  69841. return FxaaPostProcess;
  69842. }(BABYLON.PostProcess));
  69843. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69844. })(BABYLON || (BABYLON = {}));
  69845. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69846. "use strict";
  69847. var BABYLON;
  69848. (function (BABYLON) {
  69849. /**
  69850. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69851. */
  69852. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69853. __extends(ChromaticAberrationPostProcess, _super);
  69854. /**
  69855. * Creates a new instance ChromaticAberrationPostProcess
  69856. * @param name The name of the effect.
  69857. * @param screenWidth The width of the screen to apply the effect on.
  69858. * @param screenHeight The height of the screen to apply the effect on.
  69859. * @param options The required width/height ratio to downsize to before computing the render pass.
  69860. * @param camera The camera to apply the render pass to.
  69861. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69862. * @param engine The engine which the post process will be applied. (default: current engine)
  69863. * @param reusable If the post process can be reused on the same frame. (default: false)
  69864. * @param textureType Type of textures used when performing the post process. (default: 0)
  69865. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69866. */
  69867. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69868. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69869. if (blockCompilation === void 0) { blockCompilation = false; }
  69870. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69871. /**
  69872. * The amount of seperation of rgb channels (default: 30)
  69873. */
  69874. _this.aberrationAmount = 30;
  69875. /**
  69876. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69877. */
  69878. _this.radialIntensity = 0;
  69879. /**
  69880. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  69881. */
  69882. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69883. /**
  69884. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  69885. */
  69886. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69887. _this.onApplyObservable.add(function (effect) {
  69888. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69889. effect.setFloat('screen_width', screenWidth);
  69890. effect.setFloat('screen_height', screenHeight);
  69891. effect.setFloat('radialIntensity', _this.radialIntensity);
  69892. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69893. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69894. });
  69895. return _this;
  69896. }
  69897. return ChromaticAberrationPostProcess;
  69898. }(BABYLON.PostProcess));
  69899. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69900. })(BABYLON || (BABYLON = {}));
  69901. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69902. "use strict";
  69903. var BABYLON;
  69904. (function (BABYLON) {
  69905. /**
  69906. * The GrainPostProcess adds noise to the image at mid luminance levels
  69907. */
  69908. var GrainPostProcess = /** @class */ (function (_super) {
  69909. __extends(GrainPostProcess, _super);
  69910. /**
  69911. * Creates a new instance of @see GrainPostProcess
  69912. * @param name The name of the effect.
  69913. * @param options The required width/height ratio to downsize to before computing the render pass.
  69914. * @param camera The camera to apply the render pass to.
  69915. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69916. * @param engine The engine which the post process will be applied. (default: current engine)
  69917. * @param reusable If the post process can be reused on the same frame. (default: false)
  69918. * @param textureType Type of textures used when performing the post process. (default: 0)
  69919. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69920. */
  69921. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69922. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69923. if (blockCompilation === void 0) { blockCompilation = false; }
  69924. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69925. /**
  69926. * The intensity of the grain added (default: 30)
  69927. */
  69928. _this.intensity = 30;
  69929. /**
  69930. * If the grain should be randomized on every frame
  69931. */
  69932. _this.animated = false;
  69933. _this.onApplyObservable.add(function (effect) {
  69934. effect.setFloat('intensity', _this.intensity);
  69935. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  69936. });
  69937. return _this;
  69938. }
  69939. return GrainPostProcess;
  69940. }(BABYLON.PostProcess));
  69941. BABYLON.GrainPostProcess = GrainPostProcess;
  69942. })(BABYLON || (BABYLON = {}));
  69943. //# sourceMappingURL=babylon.grainPostProcess.js.map
  69944. "use strict";
  69945. var BABYLON;
  69946. (function (BABYLON) {
  69947. /**
  69948. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69949. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69950. */
  69951. var SharpenPostProcess = /** @class */ (function (_super) {
  69952. __extends(SharpenPostProcess, _super);
  69953. /**
  69954. * Creates a new instance ConvolutionPostProcess
  69955. * @param name The name of the effect.
  69956. * @param options The required width/height ratio to downsize to before computing the render pass.
  69957. * @param camera The camera to apply the render pass to.
  69958. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69959. * @param engine The engine which the post process will be applied. (default: current engine)
  69960. * @param reusable If the post process can be reused on the same frame. (default: false)
  69961. * @param textureType Type of textures used when performing the post process. (default: 0)
  69962. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69963. */
  69964. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69965. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69966. if (blockCompilation === void 0) { blockCompilation = false; }
  69967. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69968. /**
  69969. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69970. */
  69971. _this.colorAmount = 1.0;
  69972. /**
  69973. * How much sharpness should be applied (default: 0.3)
  69974. */
  69975. _this.edgeAmount = 0.3;
  69976. _this.onApply = function (effect) {
  69977. effect.setFloat2("screenSize", _this.width, _this.height);
  69978. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69979. };
  69980. return _this;
  69981. }
  69982. return SharpenPostProcess;
  69983. }(BABYLON.PostProcess));
  69984. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69985. })(BABYLON || (BABYLON = {}));
  69986. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69987. "use strict";
  69988. var BABYLON;
  69989. (function (BABYLON) {
  69990. /**
  69991. * The Blur Post Process which blurs an image based on a kernel and direction.
  69992. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69993. */
  69994. var BlurPostProcess = /** @class */ (function (_super) {
  69995. __extends(BlurPostProcess, _super);
  69996. /**
  69997. * Creates a new instance BlurPostProcess
  69998. * @param name The name of the effect.
  69999. * @param direction The direction in which to blur the image.
  70000. * @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.
  70001. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70002. * @param camera The camera to apply the render pass to.
  70003. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70004. * @param engine The engine which the post process will be applied. (default: current engine)
  70005. * @param reusable If the post process can be reused on the same frame. (default: false)
  70006. * @param textureType Type of textures used when performing the post process. (default: 0)
  70007. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70008. */
  70009. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  70010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70011. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70012. if (defines === void 0) { defines = ""; }
  70013. if (blockCompilation === void 0) { blockCompilation = false; }
  70014. 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;
  70015. _this.direction = direction;
  70016. _this.blockCompilation = blockCompilation;
  70017. _this._packedFloat = false;
  70018. _this._staticDefines = "";
  70019. _this._staticDefines = defines;
  70020. _this.onApplyObservable.add(function (effect) {
  70021. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70022. });
  70023. _this.kernel = kernel;
  70024. return _this;
  70025. }
  70026. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70027. /**
  70028. * Gets the length in pixels of the blur sample region
  70029. */
  70030. get: function () {
  70031. return this._idealKernel;
  70032. },
  70033. /**
  70034. * Sets the length in pixels of the blur sample region
  70035. */
  70036. set: function (v) {
  70037. if (this._idealKernel === v) {
  70038. return;
  70039. }
  70040. v = Math.max(v, 1);
  70041. this._idealKernel = v;
  70042. this._kernel = this._nearestBestKernel(v);
  70043. if (!this.blockCompilation) {
  70044. this._updateParameters();
  70045. }
  70046. },
  70047. enumerable: true,
  70048. configurable: true
  70049. });
  70050. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70051. /**
  70052. * Gets wether or not the blur is unpacking/repacking floats
  70053. */
  70054. get: function () {
  70055. return this._packedFloat;
  70056. },
  70057. /**
  70058. * Sets wether or not the blur needs to unpack/repack floats
  70059. */
  70060. set: function (v) {
  70061. if (this._packedFloat === v) {
  70062. return;
  70063. }
  70064. this._packedFloat = v;
  70065. if (!this.blockCompilation) {
  70066. this._updateParameters();
  70067. }
  70068. },
  70069. enumerable: true,
  70070. configurable: true
  70071. });
  70072. /**
  70073. * Updates the effect with the current post process compile time values and recompiles the shader.
  70074. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70075. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70076. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70077. * @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
  70078. * @param onCompiled Called when the shader has been compiled.
  70079. * @param onError Called if there is an error when compiling a shader.
  70080. */
  70081. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70082. if (defines === void 0) { defines = null; }
  70083. if (uniforms === void 0) { uniforms = null; }
  70084. if (samplers === void 0) { samplers = null; }
  70085. this._updateParameters(onCompiled, onError);
  70086. };
  70087. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  70088. // Generate sampling offsets and weights
  70089. var N = this._kernel;
  70090. var centerIndex = (N - 1) / 2;
  70091. // Generate Gaussian sampling weights over kernel
  70092. var offsets = [];
  70093. var weights = [];
  70094. var totalWeight = 0;
  70095. for (var i = 0; i < N; i++) {
  70096. var u = i / (N - 1);
  70097. var w = this._gaussianWeight(u * 2.0 - 1);
  70098. offsets[i] = (i - centerIndex);
  70099. weights[i] = w;
  70100. totalWeight += w;
  70101. }
  70102. // Normalize weights
  70103. for (var i = 0; i < weights.length; i++) {
  70104. weights[i] /= totalWeight;
  70105. }
  70106. // Optimize: combine samples to take advantage of hardware linear sampling
  70107. // Walk from left to center, combining pairs (symmetrically)
  70108. var linearSamplingWeights = [];
  70109. var linearSamplingOffsets = [];
  70110. var linearSamplingMap = [];
  70111. for (var i = 0; i <= centerIndex; i += 2) {
  70112. var j = Math.min(i + 1, Math.floor(centerIndex));
  70113. var singleCenterSample = i === j;
  70114. if (singleCenterSample) {
  70115. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70116. }
  70117. else {
  70118. var sharedCell = j === centerIndex;
  70119. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70120. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70121. if (offsetLinear === 0) {
  70122. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70123. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70124. }
  70125. else {
  70126. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70127. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70128. }
  70129. }
  70130. }
  70131. for (var i = 0; i < linearSamplingMap.length; i++) {
  70132. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70133. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70134. }
  70135. // Replace with optimized
  70136. offsets = linearSamplingOffsets;
  70137. weights = linearSamplingWeights;
  70138. // Generate shaders
  70139. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70140. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70141. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70142. var defines = "";
  70143. defines += this._staticDefines;
  70144. for (var i = 0; i < varyingCount; i++) {
  70145. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70146. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70147. }
  70148. var depCount = 0;
  70149. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70150. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70151. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70152. depCount++;
  70153. }
  70154. if (this.packedFloat) {
  70155. defines += "#define PACKEDFLOAT 1";
  70156. }
  70157. this.blockCompilation = false;
  70158. _super.prototype.updateEffect.call(this, defines, null, null, {
  70159. varyingCount: varyingCount,
  70160. depCount: depCount
  70161. }, onCompiled, onError);
  70162. };
  70163. /**
  70164. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70165. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70166. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70167. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70168. * The gaps between physical kernels are compensated for in the weighting of the samples
  70169. * @param idealKernel Ideal blur kernel.
  70170. * @return Nearest best kernel.
  70171. */
  70172. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70173. var v = Math.round(idealKernel);
  70174. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70175. var k = _a[_i];
  70176. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70177. return Math.max(k, 3);
  70178. }
  70179. }
  70180. return Math.max(v, 3);
  70181. };
  70182. /**
  70183. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70184. * @param x The point on the Gaussian distribution to sample.
  70185. * @return the value of the Gaussian function at x.
  70186. */
  70187. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70188. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70189. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70190. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70191. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70192. // truncated at around 1.3% of peak strength.
  70193. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70194. var sigma = (1 / 3);
  70195. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70196. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70197. var weight = (1.0 / denominator) * Math.exp(exponent);
  70198. return weight;
  70199. };
  70200. /**
  70201. * Generates a string that can be used as a floating point number in GLSL.
  70202. * @param x Value to print.
  70203. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70204. * @return GLSL float string.
  70205. */
  70206. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70207. if (decimalFigures === void 0) { decimalFigures = 8; }
  70208. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70209. };
  70210. return BlurPostProcess;
  70211. }(BABYLON.PostProcess));
  70212. BABYLON.BlurPostProcess = BlurPostProcess;
  70213. })(BABYLON || (BABYLON = {}));
  70214. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70215. "use strict";
  70216. var BABYLON;
  70217. (function (BABYLON) {
  70218. /**
  70219. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70220. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70221. * based on samples that have a large difference in distance than the center pixel.
  70222. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70223. */
  70224. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70225. __extends(DepthOfFieldBlurPostProcess, _super);
  70226. /**
  70227. * Creates a new instance CircleOfConfusionPostProcess
  70228. * @param name The name of the effect.
  70229. * @param scene The scene the effect belongs to.
  70230. * @param direction The direction the blur should be applied.
  70231. * @param kernel The size of the kernel used to blur.
  70232. * @param options The required width/height ratio to downsize to before computing the render pass.
  70233. * @param camera The camera to apply the render pass to.
  70234. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70235. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70236. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70237. * @param engine The engine which the post process will be applied. (default: current engine)
  70238. * @param reusable If the post process can be reused on the same frame. (default: false)
  70239. * @param textureType Type of textures used when performing the post process. (default: 0)
  70240. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70241. */
  70242. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70243. if (imageToBlur === void 0) { imageToBlur = null; }
  70244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70245. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70246. if (blockCompilation === void 0) { blockCompilation = false; }
  70247. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  70248. _this.direction = direction;
  70249. _this.onApplyObservable.add(function (effect) {
  70250. if (imageToBlur != null) {
  70251. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70252. }
  70253. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70254. if (scene.activeCamera) {
  70255. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70256. }
  70257. });
  70258. return _this;
  70259. }
  70260. return DepthOfFieldBlurPostProcess;
  70261. }(BABYLON.BlurPostProcess));
  70262. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70263. })(BABYLON || (BABYLON = {}));
  70264. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70265. "use strict";
  70266. var BABYLON;
  70267. (function (BABYLON) {
  70268. /**
  70269. * Options to be set when merging outputs from the default pipeline.
  70270. */
  70271. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  70272. function DepthOfFieldMergePostProcessOptions() {
  70273. }
  70274. return DepthOfFieldMergePostProcessOptions;
  70275. }());
  70276. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  70277. /**
  70278. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70279. */
  70280. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70281. __extends(DepthOfFieldMergePostProcess, _super);
  70282. /**
  70283. * Creates a new instance of DepthOfFieldMergePostProcess
  70284. * @param name The name of the effect.
  70285. * @param originalFromInput Post process which's input will be used for the merge.
  70286. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  70287. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  70288. * @param options The required width/height ratio to downsize to before computing the render pass.
  70289. * @param camera The camera to apply the render pass to.
  70290. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70291. * @param engine The engine which the post process will be applied. (default: current engine)
  70292. * @param reusable If the post process can be reused on the same frame. (default: false)
  70293. * @param textureType Type of textures used when performing the post process. (default: 0)
  70294. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70295. */
  70296. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70297. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70298. if (blockCompilation === void 0) { blockCompilation = false; }
  70299. var _this = _super.call(this, name, "depthOfFieldMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70300. _this.blurSteps = blurSteps;
  70301. _this.onApplyObservable.add(function (effect) {
  70302. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70303. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70304. blurSteps.forEach(function (step, index) {
  70305. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70306. });
  70307. });
  70308. if (!blockCompilation) {
  70309. _this.updateEffect();
  70310. }
  70311. return _this;
  70312. }
  70313. /**
  70314. * Updates the effect with the current post process compile time values and recompiles the shader.
  70315. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70316. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70317. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70318. * @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
  70319. * @param onCompiled Called when the shader has been compiled.
  70320. * @param onError Called if there is an error when compiling a shader.
  70321. */
  70322. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70323. if (defines === void 0) { defines = null; }
  70324. if (uniforms === void 0) { uniforms = null; }
  70325. if (samplers === void 0) { samplers = null; }
  70326. if (!defines) {
  70327. defines = "";
  70328. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  70329. }
  70330. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  70331. };
  70332. return DepthOfFieldMergePostProcess;
  70333. }(BABYLON.PostProcess));
  70334. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70335. })(BABYLON || (BABYLON = {}));
  70336. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70337. "use strict";
  70338. var BABYLON;
  70339. (function (BABYLON) {
  70340. /**
  70341. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70342. */
  70343. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70344. __extends(CircleOfConfusionPostProcess, _super);
  70345. /**
  70346. * Creates a new instance CircleOfConfusionPostProcess
  70347. * @param name The name of the effect.
  70348. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  70349. * @param options The required width/height ratio to downsize to before computing the render pass.
  70350. * @param camera The camera to apply the render pass to.
  70351. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70352. * @param engine The engine which the post process will be applied. (default: current engine)
  70353. * @param reusable If the post process can be reused on the same frame. (default: false)
  70354. * @param textureType Type of textures used when performing the post process. (default: 0)
  70355. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70356. */
  70357. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70358. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70359. if (blockCompilation === void 0) { blockCompilation = false; }
  70360. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70361. /**
  70362. * 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.
  70363. */
  70364. _this.lensSize = 50;
  70365. /**
  70366. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70367. */
  70368. _this.fStop = 1.4;
  70369. /**
  70370. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70371. */
  70372. _this.focusDistance = 2000;
  70373. /**
  70374. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70375. */
  70376. _this.focalLength = 50;
  70377. _this._depthTexture = null;
  70378. _this._depthTexture = depthTexture;
  70379. _this.onApplyObservable.add(function (effect) {
  70380. if (!_this._depthTexture) {
  70381. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70382. return;
  70383. }
  70384. effect.setTexture("depthSampler", _this._depthTexture);
  70385. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70386. var aperture = _this.lensSize / _this.fStop;
  70387. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70388. effect.setFloat('focusDistance', _this.focusDistance);
  70389. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70390. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70391. });
  70392. return _this;
  70393. }
  70394. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70395. /**
  70396. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  70397. */
  70398. set: function (value) {
  70399. this._depthTexture = value;
  70400. },
  70401. enumerable: true,
  70402. configurable: true
  70403. });
  70404. return CircleOfConfusionPostProcess;
  70405. }(BABYLON.PostProcess));
  70406. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70407. })(BABYLON || (BABYLON = {}));
  70408. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70409. "use strict";
  70410. var BABYLON;
  70411. (function (BABYLON) {
  70412. /**
  70413. * Specifies the level of max blur that should be applied when using the depth of field effect
  70414. */
  70415. var DepthOfFieldEffectBlurLevel;
  70416. (function (DepthOfFieldEffectBlurLevel) {
  70417. /**
  70418. * Subtle blur
  70419. */
  70420. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70421. /**
  70422. * Medium blur
  70423. */
  70424. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70425. /**
  70426. * Large blur
  70427. */
  70428. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70429. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70430. ;
  70431. /**
  70432. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70433. */
  70434. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70435. __extends(DepthOfFieldEffect, _super);
  70436. /**
  70437. * Creates a new instance DepthOfFieldEffect
  70438. * @param scene The scene the effect belongs to.
  70439. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  70440. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70441. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70442. */
  70443. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70444. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70445. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70446. if (blockCompilation === void 0) { blockCompilation = false; }
  70447. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70448. return _this._effects;
  70449. }, true) || this;
  70450. /**
  70451. * Internal post processes in depth of field effect
  70452. */
  70453. _this._effects = [];
  70454. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70455. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70456. // 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)
  70457. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70458. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70459. _this._depthOfFieldBlurY = [];
  70460. _this._depthOfFieldBlurX = [];
  70461. var blurCount = 1;
  70462. var kernelSize = 15;
  70463. switch (blurLevel) {
  70464. case DepthOfFieldEffectBlurLevel.High: {
  70465. blurCount = 3;
  70466. kernelSize = 51;
  70467. break;
  70468. }
  70469. case DepthOfFieldEffectBlurLevel.Medium: {
  70470. blurCount = 2;
  70471. kernelSize = 31;
  70472. break;
  70473. }
  70474. default: {
  70475. kernelSize = 15;
  70476. blurCount = 1;
  70477. break;
  70478. }
  70479. }
  70480. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70481. for (var i = 0; i < blurCount; i++) {
  70482. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70483. blurY.autoClear = false;
  70484. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70485. blurX.autoClear = false;
  70486. _this._depthOfFieldBlurY.push(blurY);
  70487. _this._depthOfFieldBlurX.push(blurX);
  70488. }
  70489. // Set all post processes on the effect.
  70490. _this._effects = [_this._circleOfConfusion];
  70491. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70492. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70493. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70494. }
  70495. // Merge blurred images with original image based on circleOfConfusion
  70496. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70497. _this._dofMerge.autoClear = false;
  70498. _this._effects.push(_this._dofMerge);
  70499. return _this;
  70500. }
  70501. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70502. get: function () {
  70503. return this._circleOfConfusion.focalLength;
  70504. },
  70505. /**
  70506. * The focal the length of the camera used in the effect
  70507. */
  70508. set: function (value) {
  70509. this._circleOfConfusion.focalLength = value;
  70510. },
  70511. enumerable: true,
  70512. configurable: true
  70513. });
  70514. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70515. get: function () {
  70516. return this._circleOfConfusion.fStop;
  70517. },
  70518. /**
  70519. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70520. */
  70521. set: function (value) {
  70522. this._circleOfConfusion.fStop = value;
  70523. },
  70524. enumerable: true,
  70525. configurable: true
  70526. });
  70527. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70528. get: function () {
  70529. return this._circleOfConfusion.focusDistance;
  70530. },
  70531. /**
  70532. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70533. */
  70534. set: function (value) {
  70535. this._circleOfConfusion.focusDistance = value;
  70536. },
  70537. enumerable: true,
  70538. configurable: true
  70539. });
  70540. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70541. get: function () {
  70542. return this._circleOfConfusion.lensSize;
  70543. },
  70544. /**
  70545. * 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.
  70546. */
  70547. set: function (value) {
  70548. this._circleOfConfusion.lensSize = value;
  70549. },
  70550. enumerable: true,
  70551. configurable: true
  70552. });
  70553. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70554. /**
  70555. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  70556. */
  70557. set: function (value) {
  70558. this._circleOfConfusion.depthTexture = value;
  70559. },
  70560. enumerable: true,
  70561. configurable: true
  70562. });
  70563. /**
  70564. * Disposes each of the internal effects for a given camera.
  70565. * @param camera The camera to dispose the effect on.
  70566. */
  70567. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70568. for (var effect in this._effects) {
  70569. this._effects[effect].dispose(camera);
  70570. }
  70571. };
  70572. /**
  70573. * Internal
  70574. */
  70575. DepthOfFieldEffect.prototype._updateEffects = function () {
  70576. for (var effect in this._effects) {
  70577. this._effects[effect].updateEffect();
  70578. }
  70579. };
  70580. /**
  70581. * Internal
  70582. * @returns if all the contained post processes are ready.
  70583. */
  70584. DepthOfFieldEffect.prototype._isReady = function () {
  70585. for (var effect in this._effects) {
  70586. if (!this._effects[effect].isReady()) {
  70587. return false;
  70588. }
  70589. }
  70590. return true;
  70591. };
  70592. return DepthOfFieldEffect;
  70593. }(BABYLON.PostProcessRenderEffect));
  70594. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70595. })(BABYLON || (BABYLON = {}));
  70596. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70597. "use strict";
  70598. var BABYLON;
  70599. (function (BABYLON) {
  70600. /**
  70601. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70602. */
  70603. var BloomMergePostProcess = /** @class */ (function (_super) {
  70604. __extends(BloomMergePostProcess, _super);
  70605. /**
  70606. * Creates a new instance of @see BloomMergePostProcess
  70607. * @param name The name of the effect.
  70608. * @param originalFromInput Post process which's input will be used for the merge.
  70609. * @param blurred Blurred highlights post process which's output will be used.
  70610. * @param weight Weight of the bloom to be added to the original input.
  70611. * @param options The required width/height ratio to downsize to before computing the render pass.
  70612. * @param camera The camera to apply the render pass to.
  70613. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70614. * @param engine The engine which the post process will be applied. (default: current engine)
  70615. * @param reusable If the post process can be reused on the same frame. (default: false)
  70616. * @param textureType Type of textures used when performing the post process. (default: 0)
  70617. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70618. */
  70619. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70620. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70621. if (blockCompilation === void 0) { blockCompilation = false; }
  70622. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70623. _this.weight = weight;
  70624. _this.onApplyObservable.add(function (effect) {
  70625. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70626. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  70627. effect.setFloat("bloomWeight", _this.weight);
  70628. });
  70629. if (!blockCompilation) {
  70630. _this.updateEffect();
  70631. }
  70632. return _this;
  70633. }
  70634. return BloomMergePostProcess;
  70635. }(BABYLON.PostProcess));
  70636. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  70637. })(BABYLON || (BABYLON = {}));
  70638. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  70639. "use strict";
  70640. var BABYLON;
  70641. (function (BABYLON) {
  70642. /**
  70643. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  70644. */
  70645. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  70646. __extends(ExtractHighlightsPostProcess, _super);
  70647. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70648. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70649. if (blockCompilation === void 0) { blockCompilation = false; }
  70650. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70651. /**
  70652. * The luminance threshold, pixels below this value will be set to black.
  70653. */
  70654. _this.threshold = 0.9;
  70655. /**
  70656. * Internal
  70657. */
  70658. _this._exposure = 1;
  70659. /**
  70660. * Post process which has the input texture to be used when performing highlight extraction
  70661. */
  70662. _this._inputPostProcess = null;
  70663. _this.onApplyObservable.add(function (effect) {
  70664. if (_this._inputPostProcess) {
  70665. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  70666. }
  70667. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  70668. effect.setFloat('exposure', _this._exposure);
  70669. });
  70670. return _this;
  70671. }
  70672. return ExtractHighlightsPostProcess;
  70673. }(BABYLON.PostProcess));
  70674. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  70675. })(BABYLON || (BABYLON = {}));
  70676. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  70677. "use strict";
  70678. var BABYLON;
  70679. (function (BABYLON) {
  70680. /**
  70681. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  70682. */
  70683. var BloomEffect = /** @class */ (function (_super) {
  70684. __extends(BloomEffect, _super);
  70685. /**
  70686. * Creates a new instance of @see BloomEffect
  70687. * @param scene The scene the effect belongs to.
  70688. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  70689. * @param bloomKernel The size of the kernel to be used when applying the blur.
  70690. * @param bloomWeight The the strength of bloom.
  70691. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70692. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70693. */
  70694. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  70695. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70696. if (blockCompilation === void 0) { blockCompilation = false; }
  70697. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  70698. return _this._effects;
  70699. }, true) || this;
  70700. _this.bloomScale = bloomScale;
  70701. /**
  70702. * Internal
  70703. */
  70704. _this._effects = [];
  70705. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70706. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  70707. _this._blurX.alwaysForcePOT = true;
  70708. _this._blurX.autoClear = false;
  70709. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  70710. _this._blurY.alwaysForcePOT = true;
  70711. _this._blurY.autoClear = false;
  70712. _this.kernel = bloomKernel;
  70713. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  70714. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70715. _this._merge.autoClear = false;
  70716. _this._effects.push(_this._merge);
  70717. return _this;
  70718. }
  70719. Object.defineProperty(BloomEffect.prototype, "threshold", {
  70720. /**
  70721. * The luminance threshold to find bright areas of the image to bloom.
  70722. */
  70723. get: function () {
  70724. return this._downscale.threshold;
  70725. },
  70726. set: function (value) {
  70727. this._downscale.threshold = value;
  70728. },
  70729. enumerable: true,
  70730. configurable: true
  70731. });
  70732. Object.defineProperty(BloomEffect.prototype, "weight", {
  70733. /**
  70734. * The strength of the bloom.
  70735. */
  70736. get: function () {
  70737. return this._merge.weight;
  70738. },
  70739. set: function (value) {
  70740. this._merge.weight = value;
  70741. },
  70742. enumerable: true,
  70743. configurable: true
  70744. });
  70745. Object.defineProperty(BloomEffect.prototype, "kernel", {
  70746. /**
  70747. * Specifies the size of the bloom blur kernel, relative to the final output size
  70748. */
  70749. get: function () {
  70750. return this._blurX.kernel / this.bloomScale;
  70751. },
  70752. set: function (value) {
  70753. this._blurX.kernel = value * this.bloomScale;
  70754. this._blurY.kernel = value * this.bloomScale;
  70755. },
  70756. enumerable: true,
  70757. configurable: true
  70758. });
  70759. /**
  70760. * Disposes each of the internal effects for a given camera.
  70761. * @param camera The camera to dispose the effect on.
  70762. */
  70763. BloomEffect.prototype.disposeEffects = function (camera) {
  70764. for (var effect in this._effects) {
  70765. this._effects[effect].dispose(camera);
  70766. }
  70767. };
  70768. /**
  70769. * Internal
  70770. */
  70771. BloomEffect.prototype._updateEffects = function () {
  70772. for (var effect in this._effects) {
  70773. this._effects[effect].updateEffect();
  70774. }
  70775. };
  70776. /**
  70777. * Internal
  70778. * @returns if all the contained post processes are ready.
  70779. */
  70780. BloomEffect.prototype._isReady = function () {
  70781. for (var effect in this._effects) {
  70782. if (!this._effects[effect].isReady()) {
  70783. return false;
  70784. }
  70785. }
  70786. return true;
  70787. };
  70788. return BloomEffect;
  70789. }(BABYLON.PostProcessRenderEffect));
  70790. BABYLON.BloomEffect = BloomEffect;
  70791. })(BABYLON || (BABYLON = {}));
  70792. //# sourceMappingURL=babylon.bloomEffect.js.map
  70793. "use strict";
  70794. var BABYLON;
  70795. (function (BABYLON) {
  70796. /**
  70797. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70798. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70799. */
  70800. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70801. __extends(DefaultRenderingPipeline, _super);
  70802. /**
  70803. * @constructor
  70804. * @param {string} name - The rendering pipeline name
  70805. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70806. * @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)
  70807. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70808. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70809. */
  70810. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70811. if (automaticBuild === void 0) { automaticBuild = true; }
  70812. var _this = _super.call(this, scene.getEngine(), name) || this;
  70813. _this._originalCameras = [];
  70814. /**
  70815. * ID of the sharpen post process,
  70816. */
  70817. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70818. /**
  70819. * ID of the image processing post process;
  70820. */
  70821. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70822. /**
  70823. * ID of the Fast Approximate Anti-Aliasing post process;
  70824. */
  70825. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70826. /**
  70827. * ID of the chromatic aberration post process,
  70828. */
  70829. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70830. /**
  70831. * ID of the grain post process
  70832. */
  70833. _this.GrainPostProcessId = "GrainPostProcessEffect";
  70834. /**
  70835. * Animations which can be used to tweak settings over a period of time
  70836. */
  70837. _this.animations = [];
  70838. _this._imageProcessingConfigurationObserver = null;
  70839. // Values
  70840. _this._sharpenEnabled = false;
  70841. _this._bloomEnabled = false;
  70842. _this._depthOfFieldEnabled = false;
  70843. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70844. _this._fxaaEnabled = false;
  70845. _this._imageProcessingEnabled = true;
  70846. _this._bloomScale = 0.5;
  70847. _this._chromaticAberrationEnabled = false;
  70848. _this._grainEnabled = false;
  70849. _this._buildAllowed = true;
  70850. _this._resizeObserver = null;
  70851. _this._hardwareScaleLevel = 1.0;
  70852. _this._bloomKernel = 64;
  70853. /**
  70854. * Specifies the weight of the bloom in the final rendering
  70855. */
  70856. _this._bloomWeight = 0.15;
  70857. /**
  70858. * Specifies the luma threshold for the area that will be blurred by the bloom
  70859. */
  70860. _this._bloomThreshold = 0.9;
  70861. _this._samples = 1;
  70862. _this._hasCleared = false;
  70863. _this._prevPostProcess = null;
  70864. _this._prevPrevPostProcess = null;
  70865. _this._cameras = cameras || [];
  70866. _this._originalCameras = _this._cameras.slice();
  70867. _this._buildAllowed = automaticBuild;
  70868. // Initialize
  70869. _this._scene = scene;
  70870. var caps = _this._scene.getEngine().getCaps();
  70871. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70872. // Misc
  70873. if (_this._hdr) {
  70874. if (caps.textureHalfFloatRender) {
  70875. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70876. }
  70877. else if (caps.textureFloatRender) {
  70878. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70879. }
  70880. }
  70881. else {
  70882. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70883. }
  70884. // Attach
  70885. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70886. var engine = _this._scene.getEngine();
  70887. // Create post processes before hand so they can be modified before enabled.
  70888. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70889. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70890. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70891. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70892. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  70893. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70894. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70895. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70896. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  70897. _this._resizeObserver = engine.onResizeObservable.add(function () {
  70898. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  70899. _this.bloomKernel = _this.bloomKernel;
  70900. });
  70901. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70902. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  70903. });
  70904. _this._buildPipeline();
  70905. return _this;
  70906. }
  70907. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70908. get: function () {
  70909. return this._sharpenEnabled;
  70910. },
  70911. /**
  70912. * Enable or disable the sharpen process from the pipeline
  70913. */
  70914. set: function (enabled) {
  70915. if (this._sharpenEnabled === enabled) {
  70916. return;
  70917. }
  70918. this._sharpenEnabled = enabled;
  70919. this._buildPipeline();
  70920. },
  70921. enumerable: true,
  70922. configurable: true
  70923. });
  70924. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  70925. /**
  70926. * Specifies the size of the bloom blur kernel, relative to the final output size
  70927. */
  70928. get: function () {
  70929. return this._bloomKernel;
  70930. },
  70931. set: function (value) {
  70932. this._bloomKernel = value;
  70933. this.bloom.kernel = value / this._hardwareScaleLevel;
  70934. },
  70935. enumerable: true,
  70936. configurable: true
  70937. });
  70938. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70939. get: function () {
  70940. return this._bloomWeight;
  70941. },
  70942. /**
  70943. * The strength of the bloom.
  70944. */
  70945. set: function (value) {
  70946. if (this._bloomWeight === value) {
  70947. return;
  70948. }
  70949. this.bloom.weight = value;
  70950. this._bloomWeight = value;
  70951. },
  70952. enumerable: true,
  70953. configurable: true
  70954. });
  70955. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  70956. get: function () {
  70957. return this._bloomThreshold;
  70958. },
  70959. /**
  70960. * The strength of the bloom.
  70961. */
  70962. set: function (value) {
  70963. if (this._bloomThreshold === value) {
  70964. return;
  70965. }
  70966. this.bloom.threshold = value;
  70967. this._bloomThreshold = value;
  70968. },
  70969. enumerable: true,
  70970. configurable: true
  70971. });
  70972. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70973. get: function () {
  70974. return this._bloomScale;
  70975. },
  70976. /**
  70977. * The scale of the bloom, lower value will provide better performance.
  70978. */
  70979. set: function (value) {
  70980. if (this._bloomScale === value) {
  70981. return;
  70982. }
  70983. this._bloomScale = value;
  70984. // recreate bloom and dispose old as this setting is not dynamic
  70985. this._rebuildBloom();
  70986. this._buildPipeline();
  70987. },
  70988. enumerable: true,
  70989. configurable: true
  70990. });
  70991. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70992. get: function () {
  70993. return this._bloomEnabled;
  70994. },
  70995. /**
  70996. * Enable or disable the bloom from the pipeline
  70997. */
  70998. set: function (enabled) {
  70999. if (this._bloomEnabled === enabled) {
  71000. return;
  71001. }
  71002. this._bloomEnabled = enabled;
  71003. this._buildPipeline();
  71004. },
  71005. enumerable: true,
  71006. configurable: true
  71007. });
  71008. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  71009. // recreate bloom and dispose old as this setting is not dynamic
  71010. var oldBloom = this.bloom;
  71011. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  71012. this.bloom.threshold = oldBloom.threshold;
  71013. for (var i = 0; i < this._cameras.length; i++) {
  71014. oldBloom.disposeEffects(this._cameras[i]);
  71015. }
  71016. };
  71017. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  71018. /**
  71019. * If the depth of field is enabled.
  71020. */
  71021. get: function () {
  71022. return this._depthOfFieldEnabled;
  71023. },
  71024. set: function (enabled) {
  71025. if (this._depthOfFieldEnabled === enabled) {
  71026. return;
  71027. }
  71028. this._depthOfFieldEnabled = enabled;
  71029. this._buildPipeline();
  71030. },
  71031. enumerable: true,
  71032. configurable: true
  71033. });
  71034. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  71035. /**
  71036. * Blur level of the depth of field effect. (Higher blur will effect performance)
  71037. */
  71038. get: function () {
  71039. return this._depthOfFieldBlurLevel;
  71040. },
  71041. set: function (value) {
  71042. if (this._depthOfFieldBlurLevel === value) {
  71043. return;
  71044. }
  71045. this._depthOfFieldBlurLevel = value;
  71046. // recreate dof and dispose old as this setting is not dynamic
  71047. var oldDof = this.depthOfField;
  71048. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  71049. this.depthOfField.focalLength = oldDof.focalLength;
  71050. this.depthOfField.focusDistance = oldDof.focusDistance;
  71051. this.depthOfField.fStop = oldDof.fStop;
  71052. this.depthOfField.lensSize = oldDof.lensSize;
  71053. for (var i = 0; i < this._cameras.length; i++) {
  71054. oldDof.disposeEffects(this._cameras[i]);
  71055. }
  71056. this._buildPipeline();
  71057. },
  71058. enumerable: true,
  71059. configurable: true
  71060. });
  71061. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  71062. get: function () {
  71063. return this._fxaaEnabled;
  71064. },
  71065. /**
  71066. * If the anti aliasing is enabled.
  71067. */
  71068. set: function (enabled) {
  71069. if (this._fxaaEnabled === enabled) {
  71070. return;
  71071. }
  71072. this._fxaaEnabled = enabled;
  71073. this._buildPipeline();
  71074. },
  71075. enumerable: true,
  71076. configurable: true
  71077. });
  71078. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  71079. get: function () {
  71080. return this._samples;
  71081. },
  71082. /**
  71083. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  71084. */
  71085. set: function (sampleCount) {
  71086. if (this._samples === sampleCount) {
  71087. return;
  71088. }
  71089. this._samples = sampleCount;
  71090. this._buildPipeline();
  71091. },
  71092. enumerable: true,
  71093. configurable: true
  71094. });
  71095. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  71096. get: function () {
  71097. return this._imageProcessingEnabled;
  71098. },
  71099. /**
  71100. * If image processing is enabled.
  71101. */
  71102. set: function (enabled) {
  71103. if (this._imageProcessingEnabled === enabled) {
  71104. return;
  71105. }
  71106. this._imageProcessingEnabled = enabled;
  71107. this._buildPipeline();
  71108. },
  71109. enumerable: true,
  71110. configurable: true
  71111. });
  71112. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  71113. get: function () {
  71114. return this._chromaticAberrationEnabled;
  71115. },
  71116. /**
  71117. * Enable or disable the chromaticAberration process from the pipeline
  71118. */
  71119. set: function (enabled) {
  71120. if (this._chromaticAberrationEnabled === enabled) {
  71121. return;
  71122. }
  71123. this._chromaticAberrationEnabled = enabled;
  71124. this._buildPipeline();
  71125. },
  71126. enumerable: true,
  71127. configurable: true
  71128. });
  71129. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  71130. get: function () {
  71131. return this._grainEnabled;
  71132. },
  71133. /**
  71134. * Enable or disable the grain process from the pipeline
  71135. */
  71136. set: function (enabled) {
  71137. if (this._grainEnabled === enabled) {
  71138. return;
  71139. }
  71140. this._grainEnabled = enabled;
  71141. this._buildPipeline();
  71142. },
  71143. enumerable: true,
  71144. configurable: true
  71145. });
  71146. /**
  71147. * Force the compilation of the entire pipeline.
  71148. */
  71149. DefaultRenderingPipeline.prototype.prepare = function () {
  71150. var previousState = this._buildAllowed;
  71151. this._buildAllowed = true;
  71152. this._buildPipeline();
  71153. this._buildAllowed = previousState;
  71154. };
  71155. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  71156. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  71157. if (this._hasCleared) {
  71158. postProcess.autoClear = false;
  71159. }
  71160. else {
  71161. postProcess.autoClear = true;
  71162. this._scene.autoClear = false;
  71163. this._hasCleared = true;
  71164. }
  71165. if (!skipTextureSharing) {
  71166. if (this._prevPrevPostProcess) {
  71167. postProcess.shareOutputWith(this._prevPrevPostProcess);
  71168. }
  71169. else {
  71170. postProcess.useOwnOutput();
  71171. }
  71172. if (this._prevPostProcess) {
  71173. this._prevPrevPostProcess = this._prevPostProcess;
  71174. }
  71175. this._prevPostProcess = postProcess;
  71176. }
  71177. };
  71178. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  71179. var _this = this;
  71180. if (!this._buildAllowed) {
  71181. return;
  71182. }
  71183. this._scene.autoClear = true;
  71184. var engine = this._scene.getEngine();
  71185. this._disposePostProcesses();
  71186. if (this._cameras !== null) {
  71187. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71188. // get back cameras to be used to reattach pipeline
  71189. this._cameras = this._originalCameras.slice();
  71190. }
  71191. this._reset();
  71192. this._prevPostProcess = null;
  71193. this._prevPrevPostProcess = null;
  71194. this._hasCleared = false;
  71195. if (this.depthOfFieldEnabled) {
  71196. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  71197. this.depthOfField.depthTexture = depthTexture;
  71198. if (!this.depthOfField._isReady()) {
  71199. this.depthOfField._updateEffects();
  71200. }
  71201. this.addEffect(this.depthOfField);
  71202. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  71203. }
  71204. if (this.bloomEnabled) {
  71205. if (!this.bloom._isReady()) {
  71206. this.bloom._updateEffects();
  71207. }
  71208. this.addEffect(this.bloom);
  71209. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  71210. }
  71211. if (this._imageProcessingEnabled) {
  71212. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71213. if (this._hdr) {
  71214. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  71215. this._setAutoClearAndTextureSharing(this.imageProcessing);
  71216. }
  71217. else {
  71218. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  71219. }
  71220. }
  71221. if (this.sharpenEnabled) {
  71222. if (!this.sharpen.isReady()) {
  71223. this.sharpen.updateEffect();
  71224. }
  71225. this.addEffect(this._sharpenEffect);
  71226. this._setAutoClearAndTextureSharing(this.sharpen);
  71227. }
  71228. if (this.grainEnabled) {
  71229. if (!this.grain.isReady()) {
  71230. this.grain.updateEffect();
  71231. }
  71232. this.addEffect(this._grainEffect);
  71233. this._setAutoClearAndTextureSharing(this.grain);
  71234. }
  71235. if (this.chromaticAberrationEnabled) {
  71236. if (!this.chromaticAberration.isReady()) {
  71237. this.chromaticAberration.updateEffect();
  71238. }
  71239. this.addEffect(this._chromaticAberrationEffect);
  71240. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71241. }
  71242. if (this.fxaaEnabled) {
  71243. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71244. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71245. this._setAutoClearAndTextureSharing(this.fxaa, true);
  71246. }
  71247. if (this._cameras !== null) {
  71248. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71249. }
  71250. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  71251. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71252. }
  71253. };
  71254. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71255. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71256. for (var i = 0; i < this._cameras.length; i++) {
  71257. var camera = this._cameras[i];
  71258. if (this.imageProcessing) {
  71259. this.imageProcessing.dispose(camera);
  71260. }
  71261. if (this.fxaa) {
  71262. this.fxaa.dispose(camera);
  71263. }
  71264. // These are created in the constructor and should not be disposed on every pipeline change
  71265. if (disposeNonRecreated) {
  71266. if (this.sharpen) {
  71267. this.sharpen.dispose(camera);
  71268. }
  71269. if (this.depthOfField) {
  71270. this.depthOfField.disposeEffects(camera);
  71271. }
  71272. if (this.bloom) {
  71273. this.bloom.disposeEffects(camera);
  71274. }
  71275. if (this.chromaticAberration) {
  71276. this.chromaticAberration.dispose(camera);
  71277. }
  71278. if (this.grain) {
  71279. this.grain.dispose(camera);
  71280. }
  71281. }
  71282. }
  71283. this.imageProcessing = null;
  71284. this.fxaa = null;
  71285. if (disposeNonRecreated) {
  71286. this.sharpen = null;
  71287. this._sharpenEffect = null;
  71288. this.depthOfField = null;
  71289. this.bloom = null;
  71290. this.chromaticAberration = null;
  71291. this._chromaticAberrationEffect = null;
  71292. this.grain = null;
  71293. this._grainEffect = null;
  71294. }
  71295. };
  71296. /**
  71297. * Dispose of the pipeline and stop all post processes
  71298. */
  71299. DefaultRenderingPipeline.prototype.dispose = function () {
  71300. this._disposePostProcesses(true);
  71301. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71302. this._scene.autoClear = true;
  71303. if (this._resizeObserver) {
  71304. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  71305. this._resizeObserver = null;
  71306. }
  71307. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  71308. _super.prototype.dispose.call(this);
  71309. };
  71310. /**
  71311. * Serialize the rendering pipeline (Used when exporting)
  71312. * @returns the serialized object
  71313. */
  71314. DefaultRenderingPipeline.prototype.serialize = function () {
  71315. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71316. serializationObject.customType = "DefaultRenderingPipeline";
  71317. return serializationObject;
  71318. };
  71319. /**
  71320. * Parse the serialized pipeline
  71321. * @param source Source pipeline.
  71322. * @param scene The scene to load the pipeline to.
  71323. * @param rootUrl The URL of the serialized pipeline.
  71324. * @returns An instantiated pipeline from the serialized object.
  71325. */
  71326. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  71327. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  71328. };
  71329. __decorate([
  71330. BABYLON.serialize()
  71331. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  71332. __decorate([
  71333. BABYLON.serialize()
  71334. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  71335. __decorate([
  71336. BABYLON.serialize()
  71337. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  71338. __decorate([
  71339. BABYLON.serialize()
  71340. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  71341. __decorate([
  71342. BABYLON.serialize()
  71343. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  71344. __decorate([
  71345. BABYLON.serialize()
  71346. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  71347. __decorate([
  71348. BABYLON.serialize()
  71349. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  71350. __decorate([
  71351. BABYLON.serialize()
  71352. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  71353. __decorate([
  71354. BABYLON.serialize()
  71355. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  71356. __decorate([
  71357. BABYLON.serialize()
  71358. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  71359. __decorate([
  71360. BABYLON.serialize()
  71361. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  71362. __decorate([
  71363. BABYLON.serialize()
  71364. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  71365. __decorate([
  71366. BABYLON.serialize()
  71367. ], DefaultRenderingPipeline.prototype, "samples", null);
  71368. __decorate([
  71369. BABYLON.serialize()
  71370. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71371. __decorate([
  71372. BABYLON.serialize()
  71373. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71374. __decorate([
  71375. BABYLON.serialize()
  71376. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  71377. return DefaultRenderingPipeline;
  71378. }(BABYLON.PostProcessRenderPipeline));
  71379. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71380. })(BABYLON || (BABYLON = {}));
  71381. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71382. "use strict";
  71383. var BABYLON;
  71384. (function (BABYLON) {
  71385. /**
  71386. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71387. */
  71388. var GeometryBufferRenderer = /** @class */ (function () {
  71389. /**
  71390. * Creates a new G Buffer for the scene
  71391. * @param scene The scene the buffer belongs to
  71392. * @param ratio How big is the buffer related to the main canvas.
  71393. */
  71394. function GeometryBufferRenderer(scene, ratio) {
  71395. if (ratio === void 0) { ratio = 1; }
  71396. this._enablePosition = false;
  71397. this._scene = scene;
  71398. this._ratio = ratio;
  71399. // Render target
  71400. this._createRenderTargets();
  71401. }
  71402. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71403. /**
  71404. * Set the render list (meshes to be rendered) used in the G buffer.
  71405. */
  71406. set: function (meshes) {
  71407. this._multiRenderTarget.renderList = meshes;
  71408. },
  71409. enumerable: true,
  71410. configurable: true
  71411. });
  71412. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71413. /**
  71414. * Gets wether or not G buffer are supported by the running hardware.
  71415. * This requires draw buffer supports
  71416. */
  71417. get: function () {
  71418. return this._multiRenderTarget.isSupported;
  71419. },
  71420. enumerable: true,
  71421. configurable: true
  71422. });
  71423. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71424. /**
  71425. * Gets wether or not position are enabled for the G buffer.
  71426. */
  71427. get: function () {
  71428. return this._enablePosition;
  71429. },
  71430. /**
  71431. * Sets wether or not position are enabled for the G buffer.
  71432. */
  71433. set: function (enable) {
  71434. this._enablePosition = enable;
  71435. this.dispose();
  71436. this._createRenderTargets();
  71437. },
  71438. enumerable: true,
  71439. configurable: true
  71440. });
  71441. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71442. /**
  71443. * Gets the scene associated with the buffer.
  71444. */
  71445. get: function () {
  71446. return this._scene;
  71447. },
  71448. enumerable: true,
  71449. configurable: true
  71450. });
  71451. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71452. /**
  71453. * Gets the ratio used by the buffer during its creation.
  71454. * How big is the buffer related to the main canvas.
  71455. */
  71456. get: function () {
  71457. return this._ratio;
  71458. },
  71459. enumerable: true,
  71460. configurable: true
  71461. });
  71462. /**
  71463. * Checks wether everything is ready to render a submesh to the G buffer.
  71464. * @param subMesh the submesh to check readiness for
  71465. * @param useInstances is the mesh drawn using instance or not
  71466. * @returns true if ready otherwise false
  71467. */
  71468. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71469. var material = subMesh.getMaterial();
  71470. if (material && material.disableDepthWrite) {
  71471. return false;
  71472. }
  71473. var defines = [];
  71474. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71475. var mesh = subMesh.getMesh();
  71476. // Alpha test
  71477. if (material && material.needAlphaTesting()) {
  71478. defines.push("#define ALPHATEST");
  71479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71480. attribs.push(BABYLON.VertexBuffer.UVKind);
  71481. defines.push("#define UV1");
  71482. }
  71483. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71484. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71485. defines.push("#define UV2");
  71486. }
  71487. }
  71488. // Buffers
  71489. if (this._enablePosition) {
  71490. defines.push("#define POSITION");
  71491. }
  71492. // Bones
  71493. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71494. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71495. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71496. if (mesh.numBoneInfluencers > 4) {
  71497. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71498. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71499. }
  71500. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71501. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71502. }
  71503. else {
  71504. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71505. }
  71506. // Instances
  71507. if (useInstances) {
  71508. defines.push("#define INSTANCES");
  71509. attribs.push("world0");
  71510. attribs.push("world1");
  71511. attribs.push("world2");
  71512. attribs.push("world3");
  71513. }
  71514. // Get correct effect
  71515. var join = defines.join("\n");
  71516. if (this._cachedDefines !== join) {
  71517. this._cachedDefines = join;
  71518. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71519. }
  71520. return this._effect.isReady();
  71521. };
  71522. /**
  71523. * Gets the current underlying G Buffer.
  71524. * @returns the buffer
  71525. */
  71526. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71527. return this._multiRenderTarget;
  71528. };
  71529. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71530. /**
  71531. * Gets the number of samples used to render the buffer (anti aliasing).
  71532. */
  71533. get: function () {
  71534. return this._multiRenderTarget.samples;
  71535. },
  71536. /**
  71537. * Sets the number of samples used to render the buffer (anti aliasing).
  71538. */
  71539. set: function (value) {
  71540. this._multiRenderTarget.samples = value;
  71541. },
  71542. enumerable: true,
  71543. configurable: true
  71544. });
  71545. /**
  71546. * Disposes the renderer and frees up associated resources.
  71547. */
  71548. GeometryBufferRenderer.prototype.dispose = function () {
  71549. this.getGBuffer().dispose();
  71550. };
  71551. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71552. var _this = this;
  71553. var engine = this._scene.getEngine();
  71554. var count = this._enablePosition ? 3 : 2;
  71555. 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 });
  71556. if (!this.isSupported) {
  71557. return;
  71558. }
  71559. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71560. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71561. this._multiRenderTarget.refreshRate = 1;
  71562. this._multiRenderTarget.renderParticles = false;
  71563. this._multiRenderTarget.renderList = null;
  71564. // set default depth value to 1.0 (far away)
  71565. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71566. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71567. });
  71568. // Custom render function
  71569. var renderSubMesh = function (subMesh) {
  71570. var mesh = subMesh.getRenderingMesh();
  71571. var scene = _this._scene;
  71572. var engine = scene.getEngine();
  71573. var material = subMesh.getMaterial();
  71574. if (!material) {
  71575. return;
  71576. }
  71577. // Culling
  71578. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71579. // Managing instances
  71580. var batch = mesh._getInstancesRenderList(subMesh._id);
  71581. if (batch.mustReturn) {
  71582. return;
  71583. }
  71584. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71585. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71586. engine.enableEffect(_this._effect);
  71587. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71588. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71589. _this._effect.setMatrix("view", scene.getViewMatrix());
  71590. // Alpha test
  71591. if (material && material.needAlphaTesting()) {
  71592. var alphaTexture = material.getAlphaTestTexture();
  71593. if (alphaTexture) {
  71594. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71595. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71596. }
  71597. }
  71598. // Bones
  71599. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71600. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71601. }
  71602. // Draw
  71603. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71604. }
  71605. };
  71606. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71607. var index;
  71608. if (depthOnlySubMeshes.length) {
  71609. engine.setColorWrite(false);
  71610. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71611. renderSubMesh(depthOnlySubMeshes.data[index]);
  71612. }
  71613. engine.setColorWrite(true);
  71614. }
  71615. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71616. renderSubMesh(opaqueSubMeshes.data[index]);
  71617. }
  71618. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71619. renderSubMesh(alphaTestSubMeshes.data[index]);
  71620. }
  71621. };
  71622. };
  71623. return GeometryBufferRenderer;
  71624. }());
  71625. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71626. })(BABYLON || (BABYLON = {}));
  71627. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71628. "use strict";
  71629. var BABYLON;
  71630. (function (BABYLON) {
  71631. var RefractionPostProcess = /** @class */ (function (_super) {
  71632. __extends(RefractionPostProcess, _super);
  71633. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71634. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71635. _this.color = color;
  71636. _this.depth = depth;
  71637. _this.colorLevel = colorLevel;
  71638. _this._ownRefractionTexture = true;
  71639. _this.onActivateObservable.add(function (cam) {
  71640. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71641. });
  71642. _this.onApplyObservable.add(function (effect) {
  71643. effect.setColor3("baseColor", _this.color);
  71644. effect.setFloat("depth", _this.depth);
  71645. effect.setFloat("colorLevel", _this.colorLevel);
  71646. effect.setTexture("refractionSampler", _this._refTexture);
  71647. });
  71648. return _this;
  71649. }
  71650. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71651. /**
  71652. * Gets or sets the refraction texture
  71653. * Please note that you are responsible for disposing the texture if you set it manually
  71654. */
  71655. get: function () {
  71656. return this._refTexture;
  71657. },
  71658. set: function (value) {
  71659. if (this._refTexture && this._ownRefractionTexture) {
  71660. this._refTexture.dispose();
  71661. }
  71662. this._refTexture = value;
  71663. this._ownRefractionTexture = false;
  71664. },
  71665. enumerable: true,
  71666. configurable: true
  71667. });
  71668. // Methods
  71669. RefractionPostProcess.prototype.dispose = function (camera) {
  71670. if (this._refTexture && this._ownRefractionTexture) {
  71671. this._refTexture.dispose();
  71672. this._refTexture = null;
  71673. }
  71674. _super.prototype.dispose.call(this, camera);
  71675. };
  71676. return RefractionPostProcess;
  71677. }(BABYLON.PostProcess));
  71678. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71679. })(BABYLON || (BABYLON = {}));
  71680. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71681. "use strict";
  71682. var BABYLON;
  71683. (function (BABYLON) {
  71684. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71685. __extends(BlackAndWhitePostProcess, _super);
  71686. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71687. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71688. _this.degree = 1;
  71689. _this.onApplyObservable.add(function (effect) {
  71690. effect.setFloat("degree", _this.degree);
  71691. });
  71692. return _this;
  71693. }
  71694. return BlackAndWhitePostProcess;
  71695. }(BABYLON.PostProcess));
  71696. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71697. })(BABYLON || (BABYLON = {}));
  71698. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71699. "use strict";
  71700. var BABYLON;
  71701. (function (BABYLON) {
  71702. /**
  71703. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71704. * input texture to perform effects such as edge detection or sharpening
  71705. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71706. */
  71707. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71708. __extends(ConvolutionPostProcess, _super);
  71709. /**
  71710. * Creates a new instance ConvolutionPostProcess
  71711. * @param name The name of the effect.
  71712. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71713. * @param options The required width/height ratio to downsize to before computing the render pass.
  71714. * @param camera The camera to apply the render pass to.
  71715. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71716. * @param engine The engine which the post process will be applied. (default: current engine)
  71717. * @param reusable If the post process can be reused on the same frame. (default: false)
  71718. * @param textureType Type of textures used when performing the post process. (default: 0)
  71719. */
  71720. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71721. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71722. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71723. _this.kernel = kernel;
  71724. _this.onApply = function (effect) {
  71725. effect.setFloat2("screenSize", _this.width, _this.height);
  71726. effect.setArray("kernel", _this.kernel);
  71727. };
  71728. return _this;
  71729. }
  71730. // Statics
  71731. /**
  71732. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71733. */
  71734. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71735. /**
  71736. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71737. */
  71738. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71739. /**
  71740. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71741. */
  71742. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71743. /**
  71744. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71745. */
  71746. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71747. /**
  71748. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71749. */
  71750. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71751. /**
  71752. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71753. */
  71754. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71755. return ConvolutionPostProcess;
  71756. }(BABYLON.PostProcess));
  71757. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71758. })(BABYLON || (BABYLON = {}));
  71759. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71760. "use strict";
  71761. var BABYLON;
  71762. (function (BABYLON) {
  71763. var FilterPostProcess = /** @class */ (function (_super) {
  71764. __extends(FilterPostProcess, _super);
  71765. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71766. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71767. _this.kernelMatrix = kernelMatrix;
  71768. _this.onApply = function (effect) {
  71769. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71770. };
  71771. return _this;
  71772. }
  71773. return FilterPostProcess;
  71774. }(BABYLON.PostProcess));
  71775. BABYLON.FilterPostProcess = FilterPostProcess;
  71776. })(BABYLON || (BABYLON = {}));
  71777. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71778. "use strict";
  71779. var BABYLON;
  71780. (function (BABYLON) {
  71781. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71782. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71783. __extends(VolumetricLightScatteringPostProcess, _super);
  71784. /**
  71785. * @constructor
  71786. * @param {string} name - The post-process name
  71787. * @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)
  71788. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71789. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71790. * @param {number} samples - The post-process quality, default 100
  71791. * @param {number} samplingMode - The post-process filtering mode
  71792. * @param {BABYLON.Engine} engine - The babylon engine
  71793. * @param {boolean} reusable - If the post-process is reusable
  71794. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71795. */
  71796. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71797. if (samples === void 0) { samples = 100; }
  71798. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71799. 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;
  71800. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71801. /**
  71802. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71803. */
  71804. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71805. /**
  71806. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71807. */
  71808. _this.useCustomMeshPosition = false;
  71809. /**
  71810. * If the post-process should inverse the light scattering direction
  71811. */
  71812. _this.invert = true;
  71813. /**
  71814. * Array containing the excluded meshes not rendered in the internal pass
  71815. */
  71816. _this.excludedMeshes = new Array();
  71817. /**
  71818. * Controls the overall intensity of the post-process
  71819. */
  71820. _this.exposure = 0.3;
  71821. /**
  71822. * Dissipates each sample's contribution in range [0, 1]
  71823. */
  71824. _this.decay = 0.96815;
  71825. /**
  71826. * Controls the overall intensity of each sample
  71827. */
  71828. _this.weight = 0.58767;
  71829. /**
  71830. * Controls the density of each sample
  71831. */
  71832. _this.density = 0.926;
  71833. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71834. engine = scene.getEngine();
  71835. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71836. // Configure mesh
  71837. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71838. // Configure
  71839. _this._createPass(scene, ratio.passRatio || ratio);
  71840. _this.onActivate = function (camera) {
  71841. if (!_this.isSupported) {
  71842. _this.dispose(camera);
  71843. }
  71844. _this.onActivate = null;
  71845. };
  71846. _this.onApplyObservable.add(function (effect) {
  71847. _this._updateMeshScreenCoordinates(scene);
  71848. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71849. effect.setFloat("exposure", _this.exposure);
  71850. effect.setFloat("decay", _this.decay);
  71851. effect.setFloat("weight", _this.weight);
  71852. effect.setFloat("density", _this.density);
  71853. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71854. });
  71855. return _this;
  71856. }
  71857. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71858. get: function () {
  71859. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71860. return false;
  71861. },
  71862. set: function (useDiffuseColor) {
  71863. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71864. },
  71865. enumerable: true,
  71866. configurable: true
  71867. });
  71868. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71869. return "VolumetricLightScatteringPostProcess";
  71870. };
  71871. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71872. var mesh = subMesh.getMesh();
  71873. // Render this.mesh as default
  71874. if (mesh === this.mesh && mesh.material) {
  71875. return mesh.material.isReady(mesh);
  71876. }
  71877. var defines = [];
  71878. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71879. var material = subMesh.getMaterial();
  71880. // Alpha test
  71881. if (material) {
  71882. if (material.needAlphaTesting()) {
  71883. defines.push("#define ALPHATEST");
  71884. }
  71885. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71886. attribs.push(BABYLON.VertexBuffer.UVKind);
  71887. defines.push("#define UV1");
  71888. }
  71889. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71890. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71891. defines.push("#define UV2");
  71892. }
  71893. }
  71894. // Bones
  71895. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71896. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71897. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71898. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71899. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71900. }
  71901. else {
  71902. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71903. }
  71904. // Instances
  71905. if (useInstances) {
  71906. defines.push("#define INSTANCES");
  71907. attribs.push("world0");
  71908. attribs.push("world1");
  71909. attribs.push("world2");
  71910. attribs.push("world3");
  71911. }
  71912. // Get correct effect
  71913. var join = defines.join("\n");
  71914. if (this._cachedDefines !== join) {
  71915. this._cachedDefines = join;
  71916. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71917. }
  71918. return this._volumetricLightScatteringPass.isReady();
  71919. };
  71920. /**
  71921. * Sets the new light position for light scattering effect
  71922. * @param {BABYLON.Vector3} The new custom light position
  71923. */
  71924. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71925. this.customMeshPosition = position;
  71926. };
  71927. /**
  71928. * Returns the light position for light scattering effect
  71929. * @return {BABYLON.Vector3} The custom light position
  71930. */
  71931. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71932. return this.customMeshPosition;
  71933. };
  71934. /**
  71935. * Disposes the internal assets and detaches the post-process from the camera
  71936. */
  71937. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71938. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71939. if (rttIndex !== -1) {
  71940. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71941. }
  71942. this._volumetricLightScatteringRTT.dispose();
  71943. _super.prototype.dispose.call(this, camera);
  71944. };
  71945. /**
  71946. * Returns the render target texture used by the post-process
  71947. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71948. */
  71949. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71950. return this._volumetricLightScatteringRTT;
  71951. };
  71952. // Private methods
  71953. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71954. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71955. return true;
  71956. }
  71957. return false;
  71958. };
  71959. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71960. var _this = this;
  71961. var engine = scene.getEngine();
  71962. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71963. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71964. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71965. this._volumetricLightScatteringRTT.renderList = null;
  71966. this._volumetricLightScatteringRTT.renderParticles = false;
  71967. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71968. var camera = this.getCamera();
  71969. if (camera) {
  71970. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71971. }
  71972. else {
  71973. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71974. }
  71975. // Custom render function for submeshes
  71976. var renderSubMesh = function (subMesh) {
  71977. var mesh = subMesh.getRenderingMesh();
  71978. if (_this._meshExcluded(mesh)) {
  71979. return;
  71980. }
  71981. var material = subMesh.getMaterial();
  71982. if (!material) {
  71983. return;
  71984. }
  71985. var scene = mesh.getScene();
  71986. var engine = scene.getEngine();
  71987. // Culling
  71988. engine.setState(material.backFaceCulling);
  71989. // Managing instances
  71990. var batch = mesh._getInstancesRenderList(subMesh._id);
  71991. if (batch.mustReturn) {
  71992. return;
  71993. }
  71994. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71995. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71996. var effect = _this._volumetricLightScatteringPass;
  71997. if (mesh === _this.mesh) {
  71998. if (subMesh.effect) {
  71999. effect = subMesh.effect;
  72000. }
  72001. else {
  72002. effect = material.getEffect();
  72003. }
  72004. }
  72005. engine.enableEffect(effect);
  72006. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  72007. if (mesh === _this.mesh) {
  72008. material.bind(mesh.getWorldMatrix(), mesh);
  72009. }
  72010. else {
  72011. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  72012. // Alpha test
  72013. if (material && material.needAlphaTesting()) {
  72014. var alphaTexture = material.getAlphaTestTexture();
  72015. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  72016. if (alphaTexture) {
  72017. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72018. }
  72019. }
  72020. // Bones
  72021. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72022. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72023. }
  72024. }
  72025. // Draw
  72026. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  72027. }
  72028. };
  72029. // Render target texture callbacks
  72030. var savedSceneClearColor;
  72031. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  72032. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  72033. savedSceneClearColor = scene.clearColor;
  72034. scene.clearColor = sceneClearColor;
  72035. });
  72036. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  72037. scene.clearColor = savedSceneClearColor;
  72038. });
  72039. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72040. var engine = scene.getEngine();
  72041. var index;
  72042. if (depthOnlySubMeshes.length) {
  72043. engine.setColorWrite(false);
  72044. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72045. renderSubMesh(depthOnlySubMeshes.data[index]);
  72046. }
  72047. engine.setColorWrite(true);
  72048. }
  72049. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72050. renderSubMesh(opaqueSubMeshes.data[index]);
  72051. }
  72052. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72053. renderSubMesh(alphaTestSubMeshes.data[index]);
  72054. }
  72055. if (transparentSubMeshes.length) {
  72056. // Sort sub meshes
  72057. for (index = 0; index < transparentSubMeshes.length; index++) {
  72058. var submesh = transparentSubMeshes.data[index];
  72059. var boundingInfo = submesh.getBoundingInfo();
  72060. if (boundingInfo && scene.activeCamera) {
  72061. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  72062. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  72063. }
  72064. }
  72065. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  72066. sortedArray.sort(function (a, b) {
  72067. // Alpha index first
  72068. if (a._alphaIndex > b._alphaIndex) {
  72069. return 1;
  72070. }
  72071. if (a._alphaIndex < b._alphaIndex) {
  72072. return -1;
  72073. }
  72074. // Then distance to camera
  72075. if (a._distanceToCamera < b._distanceToCamera) {
  72076. return 1;
  72077. }
  72078. if (a._distanceToCamera > b._distanceToCamera) {
  72079. return -1;
  72080. }
  72081. return 0;
  72082. });
  72083. // Render sub meshes
  72084. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  72085. for (index = 0; index < sortedArray.length; index++) {
  72086. renderSubMesh(sortedArray[index]);
  72087. }
  72088. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72089. }
  72090. };
  72091. };
  72092. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  72093. var transform = scene.getTransformMatrix();
  72094. var meshPosition;
  72095. if (this.useCustomMeshPosition) {
  72096. meshPosition = this.customMeshPosition;
  72097. }
  72098. else if (this.attachedNode) {
  72099. meshPosition = this.attachedNode.position;
  72100. }
  72101. else {
  72102. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  72103. }
  72104. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  72105. this._screenCoordinates.x = pos.x / this._viewPort.width;
  72106. this._screenCoordinates.y = pos.y / this._viewPort.height;
  72107. if (this.invert)
  72108. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  72109. };
  72110. // Static methods
  72111. /**
  72112. * Creates a default mesh for the Volumeric Light Scattering post-process
  72113. * @param {string} The mesh name
  72114. * @param {BABYLON.Scene} The scene where to create the mesh
  72115. * @return {BABYLON.Mesh} the default mesh
  72116. */
  72117. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  72118. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  72119. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  72120. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  72121. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  72122. mesh.material = material;
  72123. return mesh;
  72124. };
  72125. __decorate([
  72126. BABYLON.serializeAsVector3()
  72127. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  72128. __decorate([
  72129. BABYLON.serialize()
  72130. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  72131. __decorate([
  72132. BABYLON.serialize()
  72133. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  72134. __decorate([
  72135. BABYLON.serializeAsMeshReference()
  72136. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  72137. __decorate([
  72138. BABYLON.serialize()
  72139. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  72140. __decorate([
  72141. BABYLON.serialize()
  72142. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  72143. __decorate([
  72144. BABYLON.serialize()
  72145. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  72146. __decorate([
  72147. BABYLON.serialize()
  72148. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  72149. __decorate([
  72150. BABYLON.serialize()
  72151. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  72152. return VolumetricLightScatteringPostProcess;
  72153. }(BABYLON.PostProcess));
  72154. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  72155. })(BABYLON || (BABYLON = {}));
  72156. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  72157. "use strict";
  72158. //
  72159. // This post-process allows the modification of rendered colors by using
  72160. // a 'look-up table' (LUT). This effect is also called Color Grading.
  72161. //
  72162. // The object needs to be provided an url to a texture containing the color
  72163. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  72164. // Use an image editing software to tweak the LUT to match your needs.
  72165. //
  72166. // For an example of a color LUT, see here:
  72167. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  72168. // For explanations on color grading, see here:
  72169. // http://udn.epicgames.com/Three/ColorGrading.html
  72170. //
  72171. var BABYLON;
  72172. (function (BABYLON) {
  72173. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  72174. __extends(ColorCorrectionPostProcess, _super);
  72175. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  72176. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  72177. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72178. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  72179. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72180. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72181. _this.onApply = function (effect) {
  72182. effect.setTexture("colorTable", _this._colorTableTexture);
  72183. };
  72184. return _this;
  72185. }
  72186. return ColorCorrectionPostProcess;
  72187. }(BABYLON.PostProcess));
  72188. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  72189. })(BABYLON || (BABYLON = {}));
  72190. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  72191. "use strict";
  72192. var BABYLON;
  72193. (function (BABYLON) {
  72194. var TonemappingOperator;
  72195. (function (TonemappingOperator) {
  72196. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  72197. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  72198. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  72199. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  72200. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  72201. ;
  72202. var TonemapPostProcess = /** @class */ (function (_super) {
  72203. __extends(TonemapPostProcess, _super);
  72204. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  72205. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72206. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72207. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  72208. _this._operator = _operator;
  72209. _this.exposureAdjustment = exposureAdjustment;
  72210. var defines = "#define ";
  72211. if (_this._operator === TonemappingOperator.Hable)
  72212. defines += "HABLE_TONEMAPPING";
  72213. else if (_this._operator === TonemappingOperator.Reinhard)
  72214. defines += "REINHARD_TONEMAPPING";
  72215. else if (_this._operator === TonemappingOperator.HejiDawson)
  72216. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72217. else if (_this._operator === TonemappingOperator.Photographic)
  72218. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72219. //sadly a second call to create the effect.
  72220. _this.updateEffect(defines);
  72221. _this.onApply = function (effect) {
  72222. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72223. };
  72224. return _this;
  72225. }
  72226. return TonemapPostProcess;
  72227. }(BABYLON.PostProcess));
  72228. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72229. })(BABYLON || (BABYLON = {}));
  72230. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72231. "use strict";
  72232. var BABYLON;
  72233. (function (BABYLON) {
  72234. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72235. __extends(DisplayPassPostProcess, _super);
  72236. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72237. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72238. }
  72239. return DisplayPassPostProcess;
  72240. }(BABYLON.PostProcess));
  72241. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72242. })(BABYLON || (BABYLON = {}));
  72243. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72244. "use strict";
  72245. var BABYLON;
  72246. (function (BABYLON) {
  72247. var HighlightsPostProcess = /** @class */ (function (_super) {
  72248. __extends(HighlightsPostProcess, _super);
  72249. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72250. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72251. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72252. }
  72253. return HighlightsPostProcess;
  72254. }(BABYLON.PostProcess));
  72255. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72256. })(BABYLON || (BABYLON = {}));
  72257. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72258. "use strict";
  72259. var BABYLON;
  72260. (function (BABYLON) {
  72261. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72262. __extends(ImageProcessingPostProcess, _super);
  72263. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  72264. if (camera === void 0) { camera = null; }
  72265. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72266. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  72267. _this._fromLinearSpace = true;
  72268. /**
  72269. * Defines cache preventing GC.
  72270. */
  72271. _this._defines = {
  72272. IMAGEPROCESSING: false,
  72273. VIGNETTE: false,
  72274. VIGNETTEBLENDMODEMULTIPLY: false,
  72275. VIGNETTEBLENDMODEOPAQUE: false,
  72276. TONEMAPPING: false,
  72277. CONTRAST: false,
  72278. COLORCURVES: false,
  72279. COLORGRADING: false,
  72280. COLORGRADING3D: false,
  72281. FROMLINEARSPACE: false,
  72282. SAMPLER3DGREENDEPTH: false,
  72283. SAMPLER3DBGRMAP: false,
  72284. IMAGEPROCESSINGPOSTPROCESS: false,
  72285. EXPOSURE: false,
  72286. };
  72287. // Setup the configuration as forced by the constructor. This would then not force the
  72288. // scene materials output in linear space and let untouched the default forward pass.
  72289. if (imageProcessingConfiguration) {
  72290. imageProcessingConfiguration.applyByPostProcess = true;
  72291. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  72292. // This will cause the shader to be compiled
  72293. _this.fromLinearSpace = false;
  72294. }
  72295. else {
  72296. _this._attachImageProcessingConfiguration(null, true);
  72297. _this.imageProcessingConfiguration.applyByPostProcess = true;
  72298. }
  72299. _this.onApply = function (effect) {
  72300. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  72301. };
  72302. return _this;
  72303. }
  72304. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  72305. /**
  72306. * Gets the image processing configuration used either in this material.
  72307. */
  72308. get: function () {
  72309. return this._imageProcessingConfiguration;
  72310. },
  72311. /**
  72312. * Sets the Default image processing configuration used either in the this material.
  72313. *
  72314. * If sets to null, the scene one is in use.
  72315. */
  72316. set: function (value) {
  72317. this._attachImageProcessingConfiguration(value);
  72318. },
  72319. enumerable: true,
  72320. configurable: true
  72321. });
  72322. /**
  72323. * Attaches a new image processing configuration to the PBR Material.
  72324. * @param configuration
  72325. */
  72326. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  72327. var _this = this;
  72328. if (doNotBuild === void 0) { doNotBuild = false; }
  72329. if (configuration === this._imageProcessingConfiguration) {
  72330. return;
  72331. }
  72332. // Detaches observer.
  72333. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72334. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72335. }
  72336. // Pick the scene configuration if needed.
  72337. if (!configuration) {
  72338. var scene = null;
  72339. var engine = this.getEngine();
  72340. var camera = this.getCamera();
  72341. if (camera) {
  72342. scene = camera.getScene();
  72343. }
  72344. else if (engine && engine.scenes) {
  72345. var scenes = engine.scenes;
  72346. scene = scenes[scenes.length - 1];
  72347. }
  72348. else {
  72349. scene = BABYLON.Engine.LastCreatedScene;
  72350. }
  72351. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  72352. }
  72353. else {
  72354. this._imageProcessingConfiguration = configuration;
  72355. }
  72356. // Attaches observer.
  72357. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  72358. _this._updateParameters();
  72359. });
  72360. // Ensure the effect will be rebuilt.
  72361. if (!doNotBuild) {
  72362. this._updateParameters();
  72363. }
  72364. };
  72365. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72366. /**
  72367. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72368. */
  72369. get: function () {
  72370. return this.imageProcessingConfiguration.colorCurves;
  72371. },
  72372. /**
  72373. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72374. */
  72375. set: function (value) {
  72376. this.imageProcessingConfiguration.colorCurves = value;
  72377. },
  72378. enumerable: true,
  72379. configurable: true
  72380. });
  72381. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72382. /**
  72383. * Gets wether the color curves effect is enabled.
  72384. */
  72385. get: function () {
  72386. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72387. },
  72388. /**
  72389. * Sets wether the color curves effect is enabled.
  72390. */
  72391. set: function (value) {
  72392. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72393. },
  72394. enumerable: true,
  72395. configurable: true
  72396. });
  72397. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72398. /**
  72399. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72400. */
  72401. get: function () {
  72402. return this.imageProcessingConfiguration.colorGradingTexture;
  72403. },
  72404. /**
  72405. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72406. */
  72407. set: function (value) {
  72408. this.imageProcessingConfiguration.colorGradingTexture = value;
  72409. },
  72410. enumerable: true,
  72411. configurable: true
  72412. });
  72413. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72414. /**
  72415. * Gets wether the color grading effect is enabled.
  72416. */
  72417. get: function () {
  72418. return this.imageProcessingConfiguration.colorGradingEnabled;
  72419. },
  72420. /**
  72421. * Gets wether the color grading effect is enabled.
  72422. */
  72423. set: function (value) {
  72424. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72425. },
  72426. enumerable: true,
  72427. configurable: true
  72428. });
  72429. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72430. /**
  72431. * Gets exposure used in the effect.
  72432. */
  72433. get: function () {
  72434. return this.imageProcessingConfiguration.exposure;
  72435. },
  72436. /**
  72437. * Sets exposure used in the effect.
  72438. */
  72439. set: function (value) {
  72440. this.imageProcessingConfiguration.exposure = value;
  72441. },
  72442. enumerable: true,
  72443. configurable: true
  72444. });
  72445. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72446. /**
  72447. * Gets wether tonemapping is enabled or not.
  72448. */
  72449. get: function () {
  72450. return this._imageProcessingConfiguration.toneMappingEnabled;
  72451. },
  72452. /**
  72453. * Sets wether tonemapping is enabled or not
  72454. */
  72455. set: function (value) {
  72456. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72457. },
  72458. enumerable: true,
  72459. configurable: true
  72460. });
  72461. ;
  72462. ;
  72463. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72464. /**
  72465. * Gets contrast used in the effect.
  72466. */
  72467. get: function () {
  72468. return this.imageProcessingConfiguration.contrast;
  72469. },
  72470. /**
  72471. * Sets contrast used in the effect.
  72472. */
  72473. set: function (value) {
  72474. this.imageProcessingConfiguration.contrast = value;
  72475. },
  72476. enumerable: true,
  72477. configurable: true
  72478. });
  72479. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72480. /**
  72481. * Gets Vignette stretch size.
  72482. */
  72483. get: function () {
  72484. return this.imageProcessingConfiguration.vignetteStretch;
  72485. },
  72486. /**
  72487. * Sets Vignette stretch size.
  72488. */
  72489. set: function (value) {
  72490. this.imageProcessingConfiguration.vignetteStretch = value;
  72491. },
  72492. enumerable: true,
  72493. configurable: true
  72494. });
  72495. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72496. /**
  72497. * Gets Vignette centre X Offset.
  72498. */
  72499. get: function () {
  72500. return this.imageProcessingConfiguration.vignetteCentreX;
  72501. },
  72502. /**
  72503. * Sets Vignette centre X Offset.
  72504. */
  72505. set: function (value) {
  72506. this.imageProcessingConfiguration.vignetteCentreX = value;
  72507. },
  72508. enumerable: true,
  72509. configurable: true
  72510. });
  72511. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72512. /**
  72513. * Gets Vignette centre Y Offset.
  72514. */
  72515. get: function () {
  72516. return this.imageProcessingConfiguration.vignetteCentreY;
  72517. },
  72518. /**
  72519. * Sets Vignette centre Y Offset.
  72520. */
  72521. set: function (value) {
  72522. this.imageProcessingConfiguration.vignetteCentreY = value;
  72523. },
  72524. enumerable: true,
  72525. configurable: true
  72526. });
  72527. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72528. /**
  72529. * Gets Vignette weight or intensity of the vignette effect.
  72530. */
  72531. get: function () {
  72532. return this.imageProcessingConfiguration.vignetteWeight;
  72533. },
  72534. /**
  72535. * Sets Vignette weight or intensity of the vignette effect.
  72536. */
  72537. set: function (value) {
  72538. this.imageProcessingConfiguration.vignetteWeight = value;
  72539. },
  72540. enumerable: true,
  72541. configurable: true
  72542. });
  72543. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72544. /**
  72545. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72546. * if vignetteEnabled is set to true.
  72547. */
  72548. get: function () {
  72549. return this.imageProcessingConfiguration.vignetteColor;
  72550. },
  72551. /**
  72552. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72553. * if vignetteEnabled is set to true.
  72554. */
  72555. set: function (value) {
  72556. this.imageProcessingConfiguration.vignetteColor = value;
  72557. },
  72558. enumerable: true,
  72559. configurable: true
  72560. });
  72561. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72562. /**
  72563. * Gets Camera field of view used by the Vignette effect.
  72564. */
  72565. get: function () {
  72566. return this.imageProcessingConfiguration.vignetteCameraFov;
  72567. },
  72568. /**
  72569. * Sets Camera field of view used by the Vignette effect.
  72570. */
  72571. set: function (value) {
  72572. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72573. },
  72574. enumerable: true,
  72575. configurable: true
  72576. });
  72577. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72578. /**
  72579. * Gets the vignette blend mode allowing different kind of effect.
  72580. */
  72581. get: function () {
  72582. return this.imageProcessingConfiguration.vignetteBlendMode;
  72583. },
  72584. /**
  72585. * Sets the vignette blend mode allowing different kind of effect.
  72586. */
  72587. set: function (value) {
  72588. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72589. },
  72590. enumerable: true,
  72591. configurable: true
  72592. });
  72593. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72594. /**
  72595. * Gets wether the vignette effect is enabled.
  72596. */
  72597. get: function () {
  72598. return this.imageProcessingConfiguration.vignetteEnabled;
  72599. },
  72600. /**
  72601. * Sets wether the vignette effect is enabled.
  72602. */
  72603. set: function (value) {
  72604. this.imageProcessingConfiguration.vignetteEnabled = value;
  72605. },
  72606. enumerable: true,
  72607. configurable: true
  72608. });
  72609. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72610. /**
  72611. * Gets wether the input of the processing is in Gamma or Linear Space.
  72612. */
  72613. get: function () {
  72614. return this._fromLinearSpace;
  72615. },
  72616. /**
  72617. * Sets wether the input of the processing is in Gamma or Linear Space.
  72618. */
  72619. set: function (value) {
  72620. if (this._fromLinearSpace === value) {
  72621. return;
  72622. }
  72623. this._fromLinearSpace = value;
  72624. this._updateParameters();
  72625. },
  72626. enumerable: true,
  72627. configurable: true
  72628. });
  72629. ImageProcessingPostProcess.prototype.getClassName = function () {
  72630. return "ImageProcessingPostProcess";
  72631. };
  72632. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72633. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72634. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72635. var defines = "";
  72636. for (var define in this._defines) {
  72637. if (this._defines[define]) {
  72638. defines += "#define " + define + ";\r\n";
  72639. }
  72640. }
  72641. var samplers = ["textureSampler"];
  72642. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72643. var uniforms = ["scale"];
  72644. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72645. this.updateEffect(defines, uniforms, samplers);
  72646. };
  72647. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72648. _super.prototype.dispose.call(this, camera);
  72649. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72650. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72651. }
  72652. this.imageProcessingConfiguration.applyByPostProcess = false;
  72653. };
  72654. __decorate([
  72655. BABYLON.serialize()
  72656. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72657. return ImageProcessingPostProcess;
  72658. }(BABYLON.PostProcess));
  72659. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72660. })(BABYLON || (BABYLON = {}));
  72661. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72662. "use strict";
  72663. var BABYLON;
  72664. (function (BABYLON) {
  72665. var Bone = /** @class */ (function (_super) {
  72666. __extends(Bone, _super);
  72667. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72668. if (parentBone === void 0) { parentBone = null; }
  72669. if (localMatrix === void 0) { localMatrix = null; }
  72670. if (restPose === void 0) { restPose = null; }
  72671. if (baseMatrix === void 0) { baseMatrix = null; }
  72672. if (index === void 0) { index = null; }
  72673. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72674. _this.name = name;
  72675. _this.children = new Array();
  72676. _this.animations = new Array();
  72677. // Set this value to map this bone to a different index in the transform matrices.
  72678. // Set this value to -1 to exclude the bone from the transform matrices.
  72679. _this._index = null;
  72680. _this._worldTransform = new BABYLON.Matrix();
  72681. _this._absoluteTransform = new BABYLON.Matrix();
  72682. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72683. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72684. _this._scaleVector = BABYLON.Vector3.One();
  72685. _this._negateScaleChildren = BABYLON.Vector3.One();
  72686. _this._scalingDeterminant = 1;
  72687. _this._skeleton = skeleton;
  72688. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72689. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72690. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72691. _this._index = index;
  72692. skeleton.bones.push(_this);
  72693. _this.setParent(parentBone, false);
  72694. _this._updateDifferenceMatrix();
  72695. return _this;
  72696. }
  72697. Object.defineProperty(Bone.prototype, "_matrix", {
  72698. get: function () {
  72699. return this._localMatrix;
  72700. },
  72701. set: function (val) {
  72702. if (this._localMatrix) {
  72703. this._localMatrix.copyFrom(val);
  72704. }
  72705. else {
  72706. this._localMatrix = val;
  72707. }
  72708. },
  72709. enumerable: true,
  72710. configurable: true
  72711. });
  72712. // Members
  72713. Bone.prototype.getSkeleton = function () {
  72714. return this._skeleton;
  72715. };
  72716. Bone.prototype.getParent = function () {
  72717. return this._parent;
  72718. };
  72719. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72720. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72721. if (this._parent === parent) {
  72722. return;
  72723. }
  72724. if (this._parent) {
  72725. var index = this._parent.children.indexOf(this);
  72726. if (index !== -1) {
  72727. this._parent.children.splice(index, 1);
  72728. }
  72729. }
  72730. this._parent = parent;
  72731. if (this._parent) {
  72732. this._parent.children.push(this);
  72733. }
  72734. if (updateDifferenceMatrix) {
  72735. this._updateDifferenceMatrix();
  72736. }
  72737. };
  72738. Bone.prototype.getLocalMatrix = function () {
  72739. return this._localMatrix;
  72740. };
  72741. Bone.prototype.getBaseMatrix = function () {
  72742. return this._baseMatrix;
  72743. };
  72744. Bone.prototype.getRestPose = function () {
  72745. return this._restPose;
  72746. };
  72747. Bone.prototype.returnToRest = function () {
  72748. this.updateMatrix(this._restPose.clone());
  72749. };
  72750. Bone.prototype.getWorldMatrix = function () {
  72751. return this._worldTransform;
  72752. };
  72753. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72754. return this._invertedAbsoluteTransform;
  72755. };
  72756. Bone.prototype.getAbsoluteTransform = function () {
  72757. return this._absoluteTransform;
  72758. };
  72759. Object.defineProperty(Bone.prototype, "position", {
  72760. // Properties (matches AbstractMesh properties)
  72761. get: function () {
  72762. return this.getPosition();
  72763. },
  72764. set: function (newPosition) {
  72765. this.setPosition(newPosition);
  72766. },
  72767. enumerable: true,
  72768. configurable: true
  72769. });
  72770. Object.defineProperty(Bone.prototype, "rotation", {
  72771. get: function () {
  72772. return this.getRotation();
  72773. },
  72774. set: function (newRotation) {
  72775. this.setRotation(newRotation);
  72776. },
  72777. enumerable: true,
  72778. configurable: true
  72779. });
  72780. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72781. get: function () {
  72782. return this.getRotationQuaternion();
  72783. },
  72784. set: function (newRotation) {
  72785. this.setRotationQuaternion(newRotation);
  72786. },
  72787. enumerable: true,
  72788. configurable: true
  72789. });
  72790. Object.defineProperty(Bone.prototype, "scaling", {
  72791. get: function () {
  72792. return this.getScale();
  72793. },
  72794. set: function (newScaling) {
  72795. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72796. },
  72797. enumerable: true,
  72798. configurable: true
  72799. });
  72800. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72801. /**
  72802. * Gets the animation properties override
  72803. */
  72804. get: function () {
  72805. return this._skeleton.animationPropertiesOverride;
  72806. },
  72807. enumerable: true,
  72808. configurable: true
  72809. });
  72810. // Methods
  72811. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72812. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72813. this._baseMatrix = matrix.clone();
  72814. this._localMatrix = matrix.clone();
  72815. this._skeleton._markAsDirty();
  72816. if (updateDifferenceMatrix) {
  72817. this._updateDifferenceMatrix();
  72818. }
  72819. };
  72820. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72821. if (!rootMatrix) {
  72822. rootMatrix = this._baseMatrix;
  72823. }
  72824. if (this._parent) {
  72825. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72826. }
  72827. else {
  72828. this._absoluteTransform.copyFrom(rootMatrix);
  72829. }
  72830. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72831. for (var index = 0; index < this.children.length; index++) {
  72832. this.children[index]._updateDifferenceMatrix();
  72833. }
  72834. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72835. };
  72836. Bone.prototype.markAsDirty = function () {
  72837. this._currentRenderId++;
  72838. this._childRenderId++;
  72839. this._skeleton._markAsDirty();
  72840. };
  72841. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72842. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72843. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72844. // all animation may be coming from a library skeleton, so may need to create animation
  72845. if (this.animations.length === 0) {
  72846. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72847. this.animations[0].setKeys([]);
  72848. }
  72849. // get animation info / verify there is such a range from the source bone
  72850. var sourceRange = source.animations[0].getRange(rangeName);
  72851. if (!sourceRange) {
  72852. return false;
  72853. }
  72854. var from = sourceRange.from;
  72855. var to = sourceRange.to;
  72856. var sourceKeys = source.animations[0].getKeys();
  72857. // rescaling prep
  72858. var sourceBoneLength = source.length;
  72859. var sourceParent = source.getParent();
  72860. var parent = this.getParent();
  72861. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72862. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72863. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72864. var destKeys = this.animations[0].getKeys();
  72865. // loop vars declaration
  72866. var orig;
  72867. var origTranslation;
  72868. var mat;
  72869. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72870. orig = sourceKeys[key];
  72871. if (orig.frame >= from && orig.frame <= to) {
  72872. if (rescaleAsRequired) {
  72873. mat = orig.value.clone();
  72874. // scale based on parent ratio, when bone has parent
  72875. if (parentScalingReqd) {
  72876. origTranslation = mat.getTranslation();
  72877. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72878. // scale based on skeleton dimension ratio when root bone, and value is passed
  72879. }
  72880. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72881. origTranslation = mat.getTranslation();
  72882. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72883. // use original when root bone, and no data for skelDimensionsRatio
  72884. }
  72885. else {
  72886. mat = orig.value;
  72887. }
  72888. }
  72889. else {
  72890. mat = orig.value;
  72891. }
  72892. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72893. }
  72894. }
  72895. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72896. return true;
  72897. };
  72898. /**
  72899. * Translate the bone in local or world space.
  72900. * @param vec The amount to translate the bone.
  72901. * @param space The space that the translation is in.
  72902. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72903. */
  72904. Bone.prototype.translate = function (vec, space, mesh) {
  72905. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72906. var lm = this.getLocalMatrix();
  72907. if (space == BABYLON.Space.LOCAL) {
  72908. lm.m[12] += vec.x;
  72909. lm.m[13] += vec.y;
  72910. lm.m[14] += vec.z;
  72911. }
  72912. else {
  72913. var wm = null;
  72914. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72915. if (mesh) {
  72916. wm = mesh.getWorldMatrix();
  72917. }
  72918. this._skeleton.computeAbsoluteTransforms();
  72919. var tmat = Bone._tmpMats[0];
  72920. var tvec = Bone._tmpVecs[0];
  72921. if (this._parent) {
  72922. if (mesh && wm) {
  72923. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72924. tmat.multiplyToRef(wm, tmat);
  72925. }
  72926. else {
  72927. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72928. }
  72929. }
  72930. tmat.m[12] = 0;
  72931. tmat.m[13] = 0;
  72932. tmat.m[14] = 0;
  72933. tmat.invert();
  72934. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72935. lm.m[12] += tvec.x;
  72936. lm.m[13] += tvec.y;
  72937. lm.m[14] += tvec.z;
  72938. }
  72939. this.markAsDirty();
  72940. };
  72941. /**
  72942. * Set the postion of the bone in local or world space.
  72943. * @param position The position to set the bone.
  72944. * @param space The space that the position is in.
  72945. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72946. */
  72947. Bone.prototype.setPosition = function (position, space, mesh) {
  72948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72949. var lm = this.getLocalMatrix();
  72950. if (space == BABYLON.Space.LOCAL) {
  72951. lm.m[12] = position.x;
  72952. lm.m[13] = position.y;
  72953. lm.m[14] = position.z;
  72954. }
  72955. else {
  72956. var wm = null;
  72957. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72958. if (mesh) {
  72959. wm = mesh.getWorldMatrix();
  72960. }
  72961. this._skeleton.computeAbsoluteTransforms();
  72962. var tmat = Bone._tmpMats[0];
  72963. var vec = Bone._tmpVecs[0];
  72964. if (this._parent) {
  72965. if (mesh && wm) {
  72966. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72967. tmat.multiplyToRef(wm, tmat);
  72968. }
  72969. else {
  72970. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72971. }
  72972. }
  72973. tmat.invert();
  72974. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72975. lm.m[12] = vec.x;
  72976. lm.m[13] = vec.y;
  72977. lm.m[14] = vec.z;
  72978. }
  72979. this.markAsDirty();
  72980. };
  72981. /**
  72982. * Set the absolute postion of the bone (world space).
  72983. * @param position The position to set the bone.
  72984. * @param mesh The mesh that this bone is attached to.
  72985. */
  72986. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72987. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72988. };
  72989. /**
  72990. * Set the scale of the bone on the x, y and z axes.
  72991. * @param x The scale of the bone on the x axis.
  72992. * @param x The scale of the bone on the y axis.
  72993. * @param z The scale of the bone on the z axis.
  72994. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72995. */
  72996. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72997. if (scaleChildren === void 0) { scaleChildren = false; }
  72998. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72999. if (!scaleChildren) {
  73000. this._negateScaleChildren.x = 1 / x;
  73001. this._negateScaleChildren.y = 1 / y;
  73002. this._negateScaleChildren.z = 1 / z;
  73003. }
  73004. this._syncScaleVector();
  73005. }
  73006. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  73007. };
  73008. /**
  73009. * Scale the bone on the x, y and z axes.
  73010. * @param x The amount to scale the bone on the x axis.
  73011. * @param x The amount to scale the bone on the y axis.
  73012. * @param z The amount to scale the bone on the z axis.
  73013. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73014. */
  73015. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  73016. if (scaleChildren === void 0) { scaleChildren = false; }
  73017. var locMat = this.getLocalMatrix();
  73018. var origLocMat = Bone._tmpMats[0];
  73019. origLocMat.copyFrom(locMat);
  73020. var origLocMatInv = Bone._tmpMats[1];
  73021. origLocMatInv.copyFrom(origLocMat);
  73022. origLocMatInv.invert();
  73023. var scaleMat = Bone._tmpMats[2];
  73024. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  73025. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  73026. this._scaleVector.x *= x;
  73027. this._scaleVector.y *= y;
  73028. this._scaleVector.z *= z;
  73029. locMat.multiplyToRef(origLocMatInv, locMat);
  73030. locMat.multiplyToRef(scaleMat, locMat);
  73031. locMat.multiplyToRef(origLocMat, locMat);
  73032. var parent = this.getParent();
  73033. if (parent) {
  73034. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  73035. }
  73036. else {
  73037. this.getAbsoluteTransform().copyFrom(locMat);
  73038. }
  73039. var len = this.children.length;
  73040. scaleMat.invert();
  73041. for (var i = 0; i < len; i++) {
  73042. var child = this.children[i];
  73043. var cm = child.getLocalMatrix();
  73044. cm.multiplyToRef(scaleMat, cm);
  73045. var lm = child.getLocalMatrix();
  73046. lm.m[12] *= x;
  73047. lm.m[13] *= y;
  73048. lm.m[14] *= z;
  73049. }
  73050. this.computeAbsoluteTransforms();
  73051. if (scaleChildren) {
  73052. for (var i = 0; i < len; i++) {
  73053. this.children[i].scale(x, y, z, scaleChildren);
  73054. }
  73055. }
  73056. this.markAsDirty();
  73057. };
  73058. /**
  73059. * Set the yaw, pitch, and roll of the bone in local or world space.
  73060. * @param yaw The rotation of the bone on the y axis.
  73061. * @param pitch The rotation of the bone on the x axis.
  73062. * @param roll The rotation of the bone on the z axis.
  73063. * @param space The space that the axes of rotation are in.
  73064. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73065. */
  73066. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  73067. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73068. var rotMat = Bone._tmpMats[0];
  73069. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  73070. var rotMatInv = Bone._tmpMats[1];
  73071. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73072. rotMatInv.multiplyToRef(rotMat, rotMat);
  73073. this._rotateWithMatrix(rotMat, space, mesh);
  73074. };
  73075. /**
  73076. * Rotate the bone on an axis in local or world space.
  73077. * @param axis The axis to rotate the bone on.
  73078. * @param amount The amount to rotate the bone.
  73079. * @param space The space that the axis is in.
  73080. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73081. */
  73082. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  73083. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73084. var rmat = Bone._tmpMats[0];
  73085. rmat.m[12] = 0;
  73086. rmat.m[13] = 0;
  73087. rmat.m[14] = 0;
  73088. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  73089. this._rotateWithMatrix(rmat, space, mesh);
  73090. };
  73091. /**
  73092. * Set the rotation of the bone to a particular axis angle in local or world space.
  73093. * @param axis The axis to rotate the bone on.
  73094. * @param angle The angle that the bone should be rotated to.
  73095. * @param space The space that the axis is in.
  73096. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73097. */
  73098. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  73099. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73100. var rotMat = Bone._tmpMats[0];
  73101. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  73102. var rotMatInv = Bone._tmpMats[1];
  73103. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73104. rotMatInv.multiplyToRef(rotMat, rotMat);
  73105. this._rotateWithMatrix(rotMat, space, mesh);
  73106. };
  73107. /**
  73108. * Set the euler rotation of the bone in local of world space.
  73109. * @param rotation The euler rotation that the bone should be set to.
  73110. * @param space The space that the rotation is in.
  73111. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73112. */
  73113. Bone.prototype.setRotation = function (rotation, space, mesh) {
  73114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73115. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  73116. };
  73117. /**
  73118. * Set the quaternion rotation of the bone in local of world space.
  73119. * @param quat The quaternion rotation that the bone should be set to.
  73120. * @param space The space that the rotation is in.
  73121. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73122. */
  73123. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  73124. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73125. var rotMatInv = Bone._tmpMats[0];
  73126. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73127. var rotMat = Bone._tmpMats[1];
  73128. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  73129. rotMatInv.multiplyToRef(rotMat, rotMat);
  73130. this._rotateWithMatrix(rotMat, space, mesh);
  73131. };
  73132. /**
  73133. * Set the rotation matrix of the bone in local of world space.
  73134. * @param rotMat The rotation matrix that the bone should be set to.
  73135. * @param space The space that the rotation is in.
  73136. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73137. */
  73138. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  73139. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73140. var rotMatInv = Bone._tmpMats[0];
  73141. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73142. var rotMat2 = Bone._tmpMats[1];
  73143. rotMat2.copyFrom(rotMat);
  73144. rotMatInv.multiplyToRef(rotMat, rotMat2);
  73145. this._rotateWithMatrix(rotMat2, space, mesh);
  73146. };
  73147. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  73148. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73149. var lmat = this.getLocalMatrix();
  73150. var lx = lmat.m[12];
  73151. var ly = lmat.m[13];
  73152. var lz = lmat.m[14];
  73153. var parent = this.getParent();
  73154. var parentScale = Bone._tmpMats[3];
  73155. var parentScaleInv = Bone._tmpMats[4];
  73156. if (parent) {
  73157. if (space == BABYLON.Space.WORLD) {
  73158. if (mesh) {
  73159. parentScale.copyFrom(mesh.getWorldMatrix());
  73160. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  73161. }
  73162. else {
  73163. parentScale.copyFrom(parent.getAbsoluteTransform());
  73164. }
  73165. }
  73166. else {
  73167. parentScale = parent._scaleMatrix;
  73168. }
  73169. parentScaleInv.copyFrom(parentScale);
  73170. parentScaleInv.invert();
  73171. lmat.multiplyToRef(parentScale, lmat);
  73172. lmat.multiplyToRef(rmat, lmat);
  73173. lmat.multiplyToRef(parentScaleInv, lmat);
  73174. }
  73175. else {
  73176. if (space == BABYLON.Space.WORLD && mesh) {
  73177. parentScale.copyFrom(mesh.getWorldMatrix());
  73178. parentScaleInv.copyFrom(parentScale);
  73179. parentScaleInv.invert();
  73180. lmat.multiplyToRef(parentScale, lmat);
  73181. lmat.multiplyToRef(rmat, lmat);
  73182. lmat.multiplyToRef(parentScaleInv, lmat);
  73183. }
  73184. else {
  73185. lmat.multiplyToRef(rmat, lmat);
  73186. }
  73187. }
  73188. lmat.m[12] = lx;
  73189. lmat.m[13] = ly;
  73190. lmat.m[14] = lz;
  73191. this.computeAbsoluteTransforms();
  73192. this.markAsDirty();
  73193. };
  73194. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73196. if (space == BABYLON.Space.WORLD) {
  73197. var scaleMatrix = Bone._tmpMats[2];
  73198. scaleMatrix.copyFrom(this._scaleMatrix);
  73199. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73200. if (mesh) {
  73201. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73202. var meshScale = Bone._tmpMats[3];
  73203. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73204. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73205. }
  73206. rotMatInv.invert();
  73207. scaleMatrix.m[0] *= this._scalingDeterminant;
  73208. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73209. }
  73210. else {
  73211. rotMatInv.copyFrom(this.getLocalMatrix());
  73212. rotMatInv.invert();
  73213. var scaleMatrix = Bone._tmpMats[2];
  73214. scaleMatrix.copyFrom(this._scaleMatrix);
  73215. if (this._parent) {
  73216. var pscaleMatrix = Bone._tmpMats[3];
  73217. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73218. pscaleMatrix.invert();
  73219. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73220. }
  73221. else {
  73222. scaleMatrix.m[0] *= this._scalingDeterminant;
  73223. }
  73224. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73225. }
  73226. };
  73227. /**
  73228. * Get the scale of the bone
  73229. * @returns the scale of the bone
  73230. */
  73231. Bone.prototype.getScale = function () {
  73232. return this._scaleVector.clone();
  73233. };
  73234. /**
  73235. * Copy the scale of the bone to a vector3.
  73236. * @param result The vector3 to copy the scale to
  73237. */
  73238. Bone.prototype.getScaleToRef = function (result) {
  73239. result.copyFrom(this._scaleVector);
  73240. };
  73241. /**
  73242. * Get the position of the bone in local or world space.
  73243. * @param space The space that the returned position is in.
  73244. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73245. * @returns The position of the bone
  73246. */
  73247. Bone.prototype.getPosition = function (space, mesh) {
  73248. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73249. if (mesh === void 0) { mesh = null; }
  73250. var pos = BABYLON.Vector3.Zero();
  73251. this.getPositionToRef(space, mesh, pos);
  73252. return pos;
  73253. };
  73254. /**
  73255. * Copy the position of the bone to a vector3 in local or world space.
  73256. * @param space The space that the returned position is in.
  73257. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73258. * @param result The vector3 to copy the position to.
  73259. */
  73260. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73261. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73262. if (space == BABYLON.Space.LOCAL) {
  73263. var lm = this.getLocalMatrix();
  73264. result.x = lm.m[12];
  73265. result.y = lm.m[13];
  73266. result.z = lm.m[14];
  73267. }
  73268. else {
  73269. var wm = null;
  73270. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73271. if (mesh) {
  73272. wm = mesh.getWorldMatrix();
  73273. }
  73274. this._skeleton.computeAbsoluteTransforms();
  73275. var tmat = Bone._tmpMats[0];
  73276. if (mesh && wm) {
  73277. tmat.copyFrom(this.getAbsoluteTransform());
  73278. tmat.multiplyToRef(wm, tmat);
  73279. }
  73280. else {
  73281. tmat = this.getAbsoluteTransform();
  73282. }
  73283. result.x = tmat.m[12];
  73284. result.y = tmat.m[13];
  73285. result.z = tmat.m[14];
  73286. }
  73287. };
  73288. /**
  73289. * Get the absolute position of the bone (world space).
  73290. * @param mesh The mesh that this bone is attached to.
  73291. * @returns The absolute position of the bone
  73292. */
  73293. Bone.prototype.getAbsolutePosition = function (mesh) {
  73294. if (mesh === void 0) { mesh = null; }
  73295. var pos = BABYLON.Vector3.Zero();
  73296. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  73297. return pos;
  73298. };
  73299. /**
  73300. * Copy the absolute position of the bone (world space) to the result param.
  73301. * @param mesh The mesh that this bone is attached to.
  73302. * @param result The vector3 to copy the absolute position to.
  73303. */
  73304. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  73305. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  73306. };
  73307. /**
  73308. * Compute the absolute transforms of this bone and its children.
  73309. */
  73310. Bone.prototype.computeAbsoluteTransforms = function () {
  73311. if (this._parent) {
  73312. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73313. }
  73314. else {
  73315. this._absoluteTransform.copyFrom(this._localMatrix);
  73316. var poseMatrix = this._skeleton.getPoseMatrix();
  73317. if (poseMatrix) {
  73318. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73319. }
  73320. }
  73321. var children = this.children;
  73322. var len = children.length;
  73323. for (var i = 0; i < len; i++) {
  73324. children[i].computeAbsoluteTransforms();
  73325. }
  73326. };
  73327. Bone.prototype._syncScaleVector = function () {
  73328. var lm = this.getLocalMatrix();
  73329. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73330. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73331. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73332. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73333. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73334. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73335. this._scaleVector.x = xs * Math.sqrt(xsq);
  73336. this._scaleVector.y = ys * Math.sqrt(ysq);
  73337. this._scaleVector.z = zs * Math.sqrt(zsq);
  73338. if (this._parent) {
  73339. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73340. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73341. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73342. }
  73343. 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);
  73344. };
  73345. /**
  73346. * Get the world direction from an axis that is in the local space of the bone.
  73347. * @param localAxis The local direction that is used to compute the world direction.
  73348. * @param mesh The mesh that this bone is attached to.
  73349. * @returns The world direction
  73350. */
  73351. Bone.prototype.getDirection = function (localAxis, mesh) {
  73352. if (mesh === void 0) { mesh = null; }
  73353. var result = BABYLON.Vector3.Zero();
  73354. this.getDirectionToRef(localAxis, mesh, result);
  73355. return result;
  73356. };
  73357. /**
  73358. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73359. * @param localAxis The local direction that is used to compute the world direction.
  73360. * @param mesh The mesh that this bone is attached to.
  73361. * @param result The vector3 that the world direction will be copied to.
  73362. */
  73363. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73364. if (mesh === void 0) { mesh = null; }
  73365. var wm = null;
  73366. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73367. if (mesh) {
  73368. wm = mesh.getWorldMatrix();
  73369. }
  73370. this._skeleton.computeAbsoluteTransforms();
  73371. var mat = Bone._tmpMats[0];
  73372. mat.copyFrom(this.getAbsoluteTransform());
  73373. if (mesh && wm) {
  73374. mat.multiplyToRef(wm, mat);
  73375. }
  73376. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73377. result.normalize();
  73378. };
  73379. /**
  73380. * Get the euler rotation of the bone in local or world space.
  73381. * @param space The space that the rotation should be in.
  73382. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73383. * @returns The euler rotation
  73384. */
  73385. Bone.prototype.getRotation = function (space, mesh) {
  73386. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73387. if (mesh === void 0) { mesh = null; }
  73388. var result = BABYLON.Vector3.Zero();
  73389. this.getRotationToRef(space, mesh, result);
  73390. return result;
  73391. };
  73392. /**
  73393. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73394. * @param space The space that the rotation should be in.
  73395. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73396. * @param result The vector3 that the rotation should be copied to.
  73397. */
  73398. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73399. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73400. if (mesh === void 0) { mesh = null; }
  73401. var quat = Bone._tmpQuat;
  73402. this.getRotationQuaternionToRef(space, mesh, quat);
  73403. quat.toEulerAnglesToRef(result);
  73404. };
  73405. /**
  73406. * Get the quaternion rotation of the bone in either local or world space.
  73407. * @param space The space that the rotation should be in.
  73408. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73409. * @returns The quaternion rotation
  73410. */
  73411. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73412. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73413. if (mesh === void 0) { mesh = null; }
  73414. var result = BABYLON.Quaternion.Identity();
  73415. this.getRotationQuaternionToRef(space, mesh, result);
  73416. return result;
  73417. };
  73418. /**
  73419. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73420. * @param space The space that the rotation should be in.
  73421. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73422. * @param result The quaternion that the rotation should be copied to.
  73423. */
  73424. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73425. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73426. if (mesh === void 0) { mesh = null; }
  73427. if (space == BABYLON.Space.LOCAL) {
  73428. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73429. }
  73430. else {
  73431. var mat = Bone._tmpMats[0];
  73432. var amat = this.getAbsoluteTransform();
  73433. if (mesh) {
  73434. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73435. }
  73436. else {
  73437. mat.copyFrom(amat);
  73438. }
  73439. mat.m[0] *= this._scalingDeterminant;
  73440. mat.m[1] *= this._scalingDeterminant;
  73441. mat.m[2] *= this._scalingDeterminant;
  73442. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73443. }
  73444. };
  73445. /**
  73446. * Get the rotation matrix of the bone in local or world space.
  73447. * @param space The space that the rotation should be in.
  73448. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73449. * @returns The rotation matrix
  73450. */
  73451. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73452. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73453. var result = BABYLON.Matrix.Identity();
  73454. this.getRotationMatrixToRef(space, mesh, result);
  73455. return result;
  73456. };
  73457. /**
  73458. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73459. * @param space The space that the rotation should be in.
  73460. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73461. * @param result The quaternion that the rotation should be copied to.
  73462. */
  73463. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73464. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73465. if (space == BABYLON.Space.LOCAL) {
  73466. this.getLocalMatrix().getRotationMatrixToRef(result);
  73467. }
  73468. else {
  73469. var mat = Bone._tmpMats[0];
  73470. var amat = this.getAbsoluteTransform();
  73471. if (mesh) {
  73472. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73473. }
  73474. else {
  73475. mat.copyFrom(amat);
  73476. }
  73477. mat.m[0] *= this._scalingDeterminant;
  73478. mat.m[1] *= this._scalingDeterminant;
  73479. mat.m[2] *= this._scalingDeterminant;
  73480. mat.getRotationMatrixToRef(result);
  73481. }
  73482. };
  73483. /**
  73484. * Get the world position of a point that is in the local space of the bone.
  73485. * @param position The local position
  73486. * @param mesh The mesh that this bone is attached to.
  73487. * @returns The world position
  73488. */
  73489. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73490. if (mesh === void 0) { mesh = null; }
  73491. var result = BABYLON.Vector3.Zero();
  73492. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73493. return result;
  73494. };
  73495. /**
  73496. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73497. * @param position The local position
  73498. * @param mesh The mesh that this bone is attached to.
  73499. * @param result The vector3 that the world position should be copied to.
  73500. */
  73501. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73502. if (mesh === void 0) { mesh = null; }
  73503. var wm = null;
  73504. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73505. if (mesh) {
  73506. wm = mesh.getWorldMatrix();
  73507. }
  73508. this._skeleton.computeAbsoluteTransforms();
  73509. var tmat = Bone._tmpMats[0];
  73510. if (mesh && wm) {
  73511. tmat.copyFrom(this.getAbsoluteTransform());
  73512. tmat.multiplyToRef(wm, tmat);
  73513. }
  73514. else {
  73515. tmat = this.getAbsoluteTransform();
  73516. }
  73517. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73518. };
  73519. /**
  73520. * Get the local position of a point that is in world space.
  73521. * @param position The world position
  73522. * @param mesh The mesh that this bone is attached to.
  73523. * @returns The local position
  73524. */
  73525. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73526. if (mesh === void 0) { mesh = null; }
  73527. var result = BABYLON.Vector3.Zero();
  73528. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73529. return result;
  73530. };
  73531. /**
  73532. * Get the local position of a point that is in world space and copy it to the result param.
  73533. * @param position The world position
  73534. * @param mesh The mesh that this bone is attached to.
  73535. * @param result The vector3 that the local position should be copied to.
  73536. */
  73537. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73538. if (mesh === void 0) { mesh = null; }
  73539. var wm = null;
  73540. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73541. if (mesh) {
  73542. wm = mesh.getWorldMatrix();
  73543. }
  73544. this._skeleton.computeAbsoluteTransforms();
  73545. var tmat = Bone._tmpMats[0];
  73546. tmat.copyFrom(this.getAbsoluteTransform());
  73547. if (mesh && wm) {
  73548. tmat.multiplyToRef(wm, tmat);
  73549. }
  73550. tmat.invert();
  73551. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73552. };
  73553. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73554. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73555. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73556. return Bone;
  73557. }(BABYLON.Node));
  73558. BABYLON.Bone = Bone;
  73559. })(BABYLON || (BABYLON = {}));
  73560. //# sourceMappingURL=babylon.bone.js.map
  73561. "use strict";
  73562. var BABYLON;
  73563. (function (BABYLON) {
  73564. var BoneIKController = /** @class */ (function () {
  73565. function BoneIKController(mesh, bone, options) {
  73566. this.targetPosition = BABYLON.Vector3.Zero();
  73567. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73568. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73569. this.poleAngle = 0;
  73570. this.slerpAmount = 1;
  73571. this._bone1Quat = BABYLON.Quaternion.Identity();
  73572. this._bone1Mat = BABYLON.Matrix.Identity();
  73573. this._bone2Ang = Math.PI;
  73574. this._maxAngle = Math.PI;
  73575. this._rightHandedSystem = false;
  73576. this._bendAxis = BABYLON.Vector3.Right();
  73577. this._slerping = false;
  73578. this._adjustRoll = 0;
  73579. this._bone2 = bone;
  73580. this._bone1 = bone.getParent();
  73581. if (!this._bone1) {
  73582. return;
  73583. }
  73584. this.mesh = mesh;
  73585. var bonePos = bone.getPosition();
  73586. if (bone.getAbsoluteTransform().determinant() > 0) {
  73587. this._rightHandedSystem = true;
  73588. this._bendAxis.x = 0;
  73589. this._bendAxis.y = 0;
  73590. this._bendAxis.z = -1;
  73591. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73592. this._adjustRoll = Math.PI * .5;
  73593. this._bendAxis.z = 1;
  73594. }
  73595. }
  73596. if (this._bone1.length) {
  73597. var boneScale1 = this._bone1.getScale();
  73598. var boneScale2 = this._bone2.getScale();
  73599. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73600. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73601. }
  73602. else if (this._bone1.children[0]) {
  73603. mesh.computeWorldMatrix(true);
  73604. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73605. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73606. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73607. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73608. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73609. }
  73610. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73611. this.maxAngle = Math.PI;
  73612. if (options) {
  73613. if (options.targetMesh) {
  73614. this.targetMesh = options.targetMesh;
  73615. this.targetMesh.computeWorldMatrix(true);
  73616. }
  73617. if (options.poleTargetMesh) {
  73618. this.poleTargetMesh = options.poleTargetMesh;
  73619. this.poleTargetMesh.computeWorldMatrix(true);
  73620. }
  73621. else if (options.poleTargetBone) {
  73622. this.poleTargetBone = options.poleTargetBone;
  73623. }
  73624. else if (this._bone1.getParent()) {
  73625. this.poleTargetBone = this._bone1.getParent();
  73626. }
  73627. if (options.poleTargetLocalOffset) {
  73628. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73629. }
  73630. if (options.poleAngle) {
  73631. this.poleAngle = options.poleAngle;
  73632. }
  73633. if (options.bendAxis) {
  73634. this._bendAxis.copyFrom(options.bendAxis);
  73635. }
  73636. if (options.maxAngle) {
  73637. this.maxAngle = options.maxAngle;
  73638. }
  73639. if (options.slerpAmount) {
  73640. this.slerpAmount = options.slerpAmount;
  73641. }
  73642. }
  73643. }
  73644. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73645. get: function () {
  73646. return this._maxAngle;
  73647. },
  73648. set: function (value) {
  73649. this._setMaxAngle(value);
  73650. },
  73651. enumerable: true,
  73652. configurable: true
  73653. });
  73654. BoneIKController.prototype._setMaxAngle = function (ang) {
  73655. if (ang < 0) {
  73656. ang = 0;
  73657. }
  73658. if (ang > Math.PI || ang == undefined) {
  73659. ang = Math.PI;
  73660. }
  73661. this._maxAngle = ang;
  73662. var a = this._bone1Length;
  73663. var b = this._bone2Length;
  73664. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73665. };
  73666. BoneIKController.prototype.update = function () {
  73667. var bone1 = this._bone1;
  73668. if (!bone1) {
  73669. return;
  73670. }
  73671. var target = this.targetPosition;
  73672. var poleTarget = this.poleTargetPosition;
  73673. var mat1 = BoneIKController._tmpMats[0];
  73674. var mat2 = BoneIKController._tmpMats[1];
  73675. if (this.targetMesh) {
  73676. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73677. }
  73678. if (this.poleTargetBone) {
  73679. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73680. }
  73681. else if (this.poleTargetMesh) {
  73682. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73683. }
  73684. var bonePos = BoneIKController._tmpVecs[0];
  73685. var zaxis = BoneIKController._tmpVecs[1];
  73686. var xaxis = BoneIKController._tmpVecs[2];
  73687. var yaxis = BoneIKController._tmpVecs[3];
  73688. var upAxis = BoneIKController._tmpVecs[4];
  73689. var _tmpQuat = BoneIKController._tmpQuat;
  73690. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73691. poleTarget.subtractToRef(bonePos, upAxis);
  73692. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73693. upAxis.y = 1;
  73694. }
  73695. else {
  73696. upAxis.normalize();
  73697. }
  73698. target.subtractToRef(bonePos, yaxis);
  73699. yaxis.normalize();
  73700. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73701. zaxis.normalize();
  73702. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73703. xaxis.normalize();
  73704. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73705. var a = this._bone1Length;
  73706. var b = this._bone2Length;
  73707. var c = BABYLON.Vector3.Distance(bonePos, target);
  73708. if (this._maxReach > 0) {
  73709. c = Math.min(this._maxReach, c);
  73710. }
  73711. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73712. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73713. if (acosa > 1) {
  73714. acosa = 1;
  73715. }
  73716. if (acosb > 1) {
  73717. acosb = 1;
  73718. }
  73719. if (acosa < -1) {
  73720. acosa = -1;
  73721. }
  73722. if (acosb < -1) {
  73723. acosb = -1;
  73724. }
  73725. var angA = Math.acos(acosa);
  73726. var angB = Math.acos(acosb);
  73727. var angC = -angA - angB;
  73728. if (this._rightHandedSystem) {
  73729. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73730. mat2.multiplyToRef(mat1, mat1);
  73731. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73732. mat2.multiplyToRef(mat1, mat1);
  73733. }
  73734. else {
  73735. var _tmpVec = BoneIKController._tmpVecs[5];
  73736. _tmpVec.copyFrom(this._bendAxis);
  73737. _tmpVec.x *= -1;
  73738. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73739. mat2.multiplyToRef(mat1, mat1);
  73740. }
  73741. if (this.poleAngle) {
  73742. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73743. mat1.multiplyToRef(mat2, mat1);
  73744. }
  73745. if (this._bone1) {
  73746. if (this.slerpAmount < 1) {
  73747. if (!this._slerping) {
  73748. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73749. }
  73750. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73751. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73752. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73753. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73754. this._slerping = true;
  73755. }
  73756. else {
  73757. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73758. this._bone1Mat.copyFrom(mat1);
  73759. this._slerping = false;
  73760. }
  73761. }
  73762. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73763. this._bone2Ang = angC;
  73764. };
  73765. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73766. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73767. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73768. return BoneIKController;
  73769. }());
  73770. BABYLON.BoneIKController = BoneIKController;
  73771. })(BABYLON || (BABYLON = {}));
  73772. //# sourceMappingURL=babylon.boneIKController.js.map
  73773. "use strict";
  73774. var BABYLON;
  73775. (function (BABYLON) {
  73776. var BoneLookController = /** @class */ (function () {
  73777. /**
  73778. * Create a BoneLookController
  73779. * @param mesh the mesh that the bone belongs to
  73780. * @param bone the bone that will be looking to the target
  73781. * @param target the target Vector3 to look at
  73782. * @param settings optional settings:
  73783. * - maxYaw: the maximum angle the bone will yaw to
  73784. * - minYaw: the minimum angle the bone will yaw to
  73785. * - maxPitch: the maximum angle the bone will pitch to
  73786. * - minPitch: the minimum angle the bone will yaw to
  73787. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73788. * - upAxis: the up axis of the coordinate system
  73789. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73790. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73791. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73792. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73793. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73794. * - adjustRoll: used to make an adjustment to the roll of the bone
  73795. **/
  73796. function BoneLookController(mesh, bone, target, options) {
  73797. /**
  73798. * The up axis of the coordinate system that is used when the bone is rotated.
  73799. */
  73800. this.upAxis = BABYLON.Vector3.Up();
  73801. /**
  73802. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73803. */
  73804. this.upAxisSpace = BABYLON.Space.LOCAL;
  73805. /**
  73806. * Used to make an adjustment to the yaw of the bone.
  73807. */
  73808. this.adjustYaw = 0;
  73809. /**
  73810. * Used to make an adjustment to the pitch of the bone.
  73811. */
  73812. this.adjustPitch = 0;
  73813. /**
  73814. * Used to make an adjustment to the roll of the bone.
  73815. */
  73816. this.adjustRoll = 0;
  73817. /**
  73818. * 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).
  73819. */
  73820. this.slerpAmount = 1;
  73821. this._boneQuat = BABYLON.Quaternion.Identity();
  73822. this._slerping = false;
  73823. this._firstFrameSkipped = false;
  73824. this._fowardAxis = BABYLON.Vector3.Forward();
  73825. this.mesh = mesh;
  73826. this.bone = bone;
  73827. this.target = target;
  73828. if (options) {
  73829. if (options.adjustYaw) {
  73830. this.adjustYaw = options.adjustYaw;
  73831. }
  73832. if (options.adjustPitch) {
  73833. this.adjustPitch = options.adjustPitch;
  73834. }
  73835. if (options.adjustRoll) {
  73836. this.adjustRoll = options.adjustRoll;
  73837. }
  73838. if (options.maxYaw != null) {
  73839. this.maxYaw = options.maxYaw;
  73840. }
  73841. else {
  73842. this.maxYaw = Math.PI;
  73843. }
  73844. if (options.minYaw != null) {
  73845. this.minYaw = options.minYaw;
  73846. }
  73847. else {
  73848. this.minYaw = -Math.PI;
  73849. }
  73850. if (options.maxPitch != null) {
  73851. this.maxPitch = options.maxPitch;
  73852. }
  73853. else {
  73854. this.maxPitch = Math.PI;
  73855. }
  73856. if (options.minPitch != null) {
  73857. this.minPitch = options.minPitch;
  73858. }
  73859. else {
  73860. this.minPitch = -Math.PI;
  73861. }
  73862. if (options.slerpAmount != null) {
  73863. this.slerpAmount = options.slerpAmount;
  73864. }
  73865. if (options.upAxis != null) {
  73866. this.upAxis = options.upAxis;
  73867. }
  73868. if (options.upAxisSpace != null) {
  73869. this.upAxisSpace = options.upAxisSpace;
  73870. }
  73871. if (options.yawAxis != null || options.pitchAxis != null) {
  73872. var newYawAxis = BABYLON.Axis.Y;
  73873. var newPitchAxis = BABYLON.Axis.X;
  73874. if (options.yawAxis != null) {
  73875. newYawAxis = options.yawAxis.clone();
  73876. newYawAxis.normalize();
  73877. }
  73878. if (options.pitchAxis != null) {
  73879. newPitchAxis = options.pitchAxis.clone();
  73880. newPitchAxis.normalize();
  73881. }
  73882. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73883. this._transformYawPitch = BABYLON.Matrix.Identity();
  73884. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73885. this._transformYawPitchInv = this._transformYawPitch.clone();
  73886. this._transformYawPitch.invert();
  73887. }
  73888. }
  73889. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73890. this.upAxisSpace = BABYLON.Space.LOCAL;
  73891. }
  73892. }
  73893. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73894. /**
  73895. * Get/set the minimum yaw angle that the bone can look to.
  73896. */
  73897. get: function () {
  73898. return this._minYaw;
  73899. },
  73900. set: function (value) {
  73901. this._minYaw = value;
  73902. this._minYawSin = Math.sin(value);
  73903. this._minYawCos = Math.cos(value);
  73904. if (this._maxYaw != null) {
  73905. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73906. this._yawRange = this._maxYaw - this._minYaw;
  73907. }
  73908. },
  73909. enumerable: true,
  73910. configurable: true
  73911. });
  73912. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73913. /**
  73914. * Get/set the maximum yaw angle that the bone can look to.
  73915. */
  73916. get: function () {
  73917. return this._maxYaw;
  73918. },
  73919. set: function (value) {
  73920. this._maxYaw = value;
  73921. this._maxYawSin = Math.sin(value);
  73922. this._maxYawCos = Math.cos(value);
  73923. if (this._minYaw != null) {
  73924. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73925. this._yawRange = this._maxYaw - this._minYaw;
  73926. }
  73927. },
  73928. enumerable: true,
  73929. configurable: true
  73930. });
  73931. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73932. /**
  73933. * Get/set the minimum pitch angle that the bone can look to.
  73934. */
  73935. get: function () {
  73936. return this._minPitch;
  73937. },
  73938. set: function (value) {
  73939. this._minPitch = value;
  73940. this._minPitchTan = Math.tan(value);
  73941. },
  73942. enumerable: true,
  73943. configurable: true
  73944. });
  73945. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73946. /**
  73947. * Get/set the maximum pitch angle that the bone can look to.
  73948. */
  73949. get: function () {
  73950. return this._maxPitch;
  73951. },
  73952. set: function (value) {
  73953. this._maxPitch = value;
  73954. this._maxPitchTan = Math.tan(value);
  73955. },
  73956. enumerable: true,
  73957. configurable: true
  73958. });
  73959. /**
  73960. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73961. */
  73962. BoneLookController.prototype.update = function () {
  73963. //skip the first frame when slerping so that the mesh rotation is correct
  73964. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73965. this._firstFrameSkipped = true;
  73966. return;
  73967. }
  73968. var bone = this.bone;
  73969. var bonePos = BoneLookController._tmpVecs[0];
  73970. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73971. var target = this.target;
  73972. var _tmpMat1 = BoneLookController._tmpMats[0];
  73973. var _tmpMat2 = BoneLookController._tmpMats[1];
  73974. var mesh = this.mesh;
  73975. var parentBone = bone.getParent();
  73976. var upAxis = BoneLookController._tmpVecs[1];
  73977. upAxis.copyFrom(this.upAxis);
  73978. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73979. if (this._transformYawPitch) {
  73980. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73981. }
  73982. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73983. }
  73984. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73985. mesh.getDirectionToRef(upAxis, upAxis);
  73986. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73987. upAxis.normalize();
  73988. }
  73989. }
  73990. var checkYaw = false;
  73991. var checkPitch = false;
  73992. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73993. checkYaw = true;
  73994. }
  73995. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73996. checkPitch = true;
  73997. }
  73998. if (checkYaw || checkPitch) {
  73999. var spaceMat = BoneLookController._tmpMats[2];
  74000. var spaceMatInv = BoneLookController._tmpMats[3];
  74001. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  74002. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  74003. }
  74004. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  74005. spaceMat.copyFrom(mesh.getWorldMatrix());
  74006. }
  74007. else {
  74008. var forwardAxis = BoneLookController._tmpVecs[2];
  74009. forwardAxis.copyFrom(this._fowardAxis);
  74010. if (this._transformYawPitch) {
  74011. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  74012. }
  74013. if (parentBone) {
  74014. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  74015. }
  74016. else {
  74017. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  74018. }
  74019. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  74020. rightAxis.normalize();
  74021. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  74022. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  74023. }
  74024. spaceMat.invertToRef(spaceMatInv);
  74025. var xzlen = null;
  74026. if (checkPitch) {
  74027. var localTarget = BoneLookController._tmpVecs[3];
  74028. target.subtractToRef(bonePos, localTarget);
  74029. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74030. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74031. var pitch = Math.atan2(localTarget.y, xzlen);
  74032. var newPitch = pitch;
  74033. if (pitch > this._maxPitch) {
  74034. localTarget.y = this._maxPitchTan * xzlen;
  74035. newPitch = this._maxPitch;
  74036. }
  74037. else if (pitch < this._minPitch) {
  74038. localTarget.y = this._minPitchTan * xzlen;
  74039. newPitch = this._minPitch;
  74040. }
  74041. if (pitch != newPitch) {
  74042. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74043. localTarget.addInPlace(bonePos);
  74044. target = localTarget;
  74045. }
  74046. }
  74047. if (checkYaw) {
  74048. var localTarget = BoneLookController._tmpVecs[4];
  74049. target.subtractToRef(bonePos, localTarget);
  74050. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74051. var yaw = Math.atan2(localTarget.x, localTarget.z);
  74052. var newYaw = yaw;
  74053. if (yaw > this._maxYaw || yaw < this._minYaw) {
  74054. if (xzlen == null) {
  74055. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74056. }
  74057. if (this._yawRange > Math.PI) {
  74058. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  74059. localTarget.z = this._maxYawCos * xzlen;
  74060. localTarget.x = this._maxYawSin * xzlen;
  74061. newYaw = this._maxYaw;
  74062. }
  74063. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  74064. localTarget.z = this._minYawCos * xzlen;
  74065. localTarget.x = this._minYawSin * xzlen;
  74066. newYaw = this._minYaw;
  74067. }
  74068. }
  74069. else {
  74070. if (yaw > this._maxYaw) {
  74071. localTarget.z = this._maxYawCos * xzlen;
  74072. localTarget.x = this._maxYawSin * xzlen;
  74073. newYaw = this._maxYaw;
  74074. }
  74075. else if (yaw < this._minYaw) {
  74076. localTarget.z = this._minYawCos * xzlen;
  74077. localTarget.x = this._minYawSin * xzlen;
  74078. newYaw = this._minYaw;
  74079. }
  74080. }
  74081. }
  74082. if (this._slerping && this._yawRange > Math.PI) {
  74083. //are we going to be crossing into the min/max region?
  74084. var boneFwd = BoneLookController._tmpVecs[8];
  74085. boneFwd.copyFrom(BABYLON.Axis.Z);
  74086. if (this._transformYawPitch) {
  74087. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  74088. }
  74089. var boneRotMat = BoneLookController._tmpMats[4];
  74090. this._boneQuat.toRotationMatrix(boneRotMat);
  74091. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  74092. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  74093. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  74094. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  74095. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  74096. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  74097. if (angBtwTar > angBtwMidYaw) {
  74098. if (xzlen == null) {
  74099. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74100. }
  74101. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  74102. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  74103. if (angBtwMin < angBtwMax) {
  74104. newYaw = boneYaw + Math.PI * .75;
  74105. localTarget.z = Math.cos(newYaw) * xzlen;
  74106. localTarget.x = Math.sin(newYaw) * xzlen;
  74107. }
  74108. else {
  74109. newYaw = boneYaw - Math.PI * .75;
  74110. localTarget.z = Math.cos(newYaw) * xzlen;
  74111. localTarget.x = Math.sin(newYaw) * xzlen;
  74112. }
  74113. }
  74114. }
  74115. if (yaw != newYaw) {
  74116. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74117. localTarget.addInPlace(bonePos);
  74118. target = localTarget;
  74119. }
  74120. }
  74121. }
  74122. var zaxis = BoneLookController._tmpVecs[5];
  74123. var xaxis = BoneLookController._tmpVecs[6];
  74124. var yaxis = BoneLookController._tmpVecs[7];
  74125. var _tmpQuat = BoneLookController._tmpQuat;
  74126. target.subtractToRef(bonePos, zaxis);
  74127. zaxis.normalize();
  74128. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  74129. xaxis.normalize();
  74130. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  74131. yaxis.normalize();
  74132. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  74133. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  74134. return;
  74135. }
  74136. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  74137. return;
  74138. }
  74139. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  74140. return;
  74141. }
  74142. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  74143. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  74144. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  74145. }
  74146. if (this.slerpAmount < 1) {
  74147. if (!this._slerping) {
  74148. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  74149. }
  74150. if (this._transformYawPitch) {
  74151. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74152. }
  74153. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  74154. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  74155. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  74156. this._slerping = true;
  74157. }
  74158. else {
  74159. if (this._transformYawPitch) {
  74160. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74161. }
  74162. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  74163. this._slerping = false;
  74164. }
  74165. };
  74166. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74167. var angDiff = ang2 - ang1;
  74168. angDiff %= Math.PI * 2;
  74169. if (angDiff > Math.PI) {
  74170. angDiff -= Math.PI * 2;
  74171. }
  74172. else if (angDiff < -Math.PI) {
  74173. angDiff += Math.PI * 2;
  74174. }
  74175. return angDiff;
  74176. };
  74177. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74178. ang1 %= (2 * Math.PI);
  74179. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74180. ang2 %= (2 * Math.PI);
  74181. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74182. var ab = 0;
  74183. if (ang1 < ang2) {
  74184. ab = ang2 - ang1;
  74185. }
  74186. else {
  74187. ab = ang1 - ang2;
  74188. }
  74189. if (ab > Math.PI) {
  74190. ab = Math.PI * 2 - ab;
  74191. }
  74192. return ab;
  74193. };
  74194. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74195. ang %= (2 * Math.PI);
  74196. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74197. ang1 %= (2 * Math.PI);
  74198. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74199. ang2 %= (2 * Math.PI);
  74200. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74201. if (ang1 < ang2) {
  74202. if (ang > ang1 && ang < ang2) {
  74203. return true;
  74204. }
  74205. }
  74206. else {
  74207. if (ang > ang2 && ang < ang1) {
  74208. return true;
  74209. }
  74210. }
  74211. return false;
  74212. };
  74213. 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()];
  74214. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74215. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74216. return BoneLookController;
  74217. }());
  74218. BABYLON.BoneLookController = BoneLookController;
  74219. })(BABYLON || (BABYLON = {}));
  74220. //# sourceMappingURL=babylon.boneLookController.js.map
  74221. "use strict";
  74222. var BABYLON;
  74223. (function (BABYLON) {
  74224. var Skeleton = /** @class */ (function () {
  74225. function Skeleton(name, id, scene) {
  74226. this.name = name;
  74227. this.id = id;
  74228. this.bones = new Array();
  74229. this.needInitialSkinMatrix = false;
  74230. this._isDirty = true;
  74231. this._meshesWithPoseMatrix = new Array();
  74232. this._identity = BABYLON.Matrix.Identity();
  74233. this._ranges = {};
  74234. this._lastAbsoluteTransformsUpdateId = -1;
  74235. /**
  74236. * Specifies if the skeleton should be serialized.
  74237. */
  74238. this.doNotSerialize = false;
  74239. // Events
  74240. /**
  74241. * An event triggered before computing the skeleton's matrices
  74242. */
  74243. this.onBeforeComputeObservable = new BABYLON.Observable();
  74244. this.bones = [];
  74245. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74246. scene.skeletons.push(this);
  74247. //make sure it will recalculate the matrix next time prepare is called.
  74248. this._isDirty = true;
  74249. }
  74250. // Members
  74251. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74252. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74253. return mesh._bonesTransformMatrices;
  74254. }
  74255. if (!this._transformMatrices) {
  74256. this.prepare();
  74257. }
  74258. return this._transformMatrices;
  74259. };
  74260. Skeleton.prototype.getScene = function () {
  74261. return this._scene;
  74262. };
  74263. // Methods
  74264. /**
  74265. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  74266. */
  74267. Skeleton.prototype.toString = function (fullDetails) {
  74268. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  74269. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  74270. if (fullDetails) {
  74271. ret += ", Ranges: {";
  74272. var first = true;
  74273. for (var name_1 in this._ranges) {
  74274. if (first) {
  74275. ret += ", ";
  74276. first = false;
  74277. }
  74278. ret += name_1;
  74279. }
  74280. ret += "}";
  74281. }
  74282. return ret;
  74283. };
  74284. /**
  74285. * Get bone's index searching by name
  74286. * @param {string} name is bone's name to search for
  74287. * @return {number} Indice of the bone. Returns -1 if not found
  74288. */
  74289. Skeleton.prototype.getBoneIndexByName = function (name) {
  74290. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  74291. if (this.bones[boneIndex].name === name) {
  74292. return boneIndex;
  74293. }
  74294. }
  74295. return -1;
  74296. };
  74297. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  74298. // check name not already in use
  74299. if (!this._ranges[name]) {
  74300. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  74301. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74302. if (this.bones[i].animations[0]) {
  74303. this.bones[i].animations[0].createRange(name, from, to);
  74304. }
  74305. }
  74306. }
  74307. };
  74308. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  74309. if (deleteFrames === void 0) { deleteFrames = true; }
  74310. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74311. if (this.bones[i].animations[0]) {
  74312. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  74313. }
  74314. }
  74315. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  74316. };
  74317. Skeleton.prototype.getAnimationRange = function (name) {
  74318. return this._ranges[name];
  74319. };
  74320. /**
  74321. * Returns as an Array, all AnimationRanges defined on this skeleton
  74322. */
  74323. Skeleton.prototype.getAnimationRanges = function () {
  74324. var animationRanges = [];
  74325. var name;
  74326. var i = 0;
  74327. for (name in this._ranges) {
  74328. animationRanges[i] = this._ranges[name];
  74329. i++;
  74330. }
  74331. return animationRanges;
  74332. };
  74333. /**
  74334. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74335. */
  74336. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74337. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74338. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74339. return false;
  74340. }
  74341. var ret = true;
  74342. var frameOffset = this._getHighestAnimationFrame() + 1;
  74343. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74344. var boneDict = {};
  74345. var sourceBones = source.bones;
  74346. var nBones;
  74347. var i;
  74348. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74349. boneDict[sourceBones[i].name] = sourceBones[i];
  74350. }
  74351. if (this.bones.length !== sourceBones.length) {
  74352. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74353. ret = false;
  74354. }
  74355. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74356. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74357. var boneName = this.bones[i].name;
  74358. var sourceBone = boneDict[boneName];
  74359. if (sourceBone) {
  74360. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74361. }
  74362. else {
  74363. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74364. ret = false;
  74365. }
  74366. }
  74367. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74368. var range = source.getAnimationRange(name);
  74369. if (range) {
  74370. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74371. }
  74372. return ret;
  74373. };
  74374. Skeleton.prototype.returnToRest = function () {
  74375. for (var index = 0; index < this.bones.length; index++) {
  74376. this.bones[index].returnToRest();
  74377. }
  74378. };
  74379. Skeleton.prototype._getHighestAnimationFrame = function () {
  74380. var ret = 0;
  74381. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74382. if (this.bones[i].animations[0]) {
  74383. var highest = this.bones[i].animations[0].getHighestFrame();
  74384. if (ret < highest) {
  74385. ret = highest;
  74386. }
  74387. }
  74388. }
  74389. return ret;
  74390. };
  74391. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74392. var range = this.getAnimationRange(name);
  74393. if (!range) {
  74394. return null;
  74395. }
  74396. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74397. };
  74398. Skeleton.prototype._markAsDirty = function () {
  74399. this._isDirty = true;
  74400. };
  74401. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74402. this._meshesWithPoseMatrix.push(mesh);
  74403. };
  74404. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74405. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74406. if (index > -1) {
  74407. this._meshesWithPoseMatrix.splice(index, 1);
  74408. }
  74409. };
  74410. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74411. this.onBeforeComputeObservable.notifyObservers(this);
  74412. for (var index = 0; index < this.bones.length; index++) {
  74413. var bone = this.bones[index];
  74414. var parentBone = bone.getParent();
  74415. if (parentBone) {
  74416. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74417. }
  74418. else {
  74419. if (initialSkinMatrix) {
  74420. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74421. }
  74422. else {
  74423. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74424. }
  74425. }
  74426. if (bone._index !== -1) {
  74427. var mappedIndex = bone._index === null ? index : bone._index;
  74428. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74429. }
  74430. }
  74431. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74432. };
  74433. Skeleton.prototype.prepare = function () {
  74434. if (!this._isDirty) {
  74435. return;
  74436. }
  74437. if (this.needInitialSkinMatrix) {
  74438. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74439. var mesh = this._meshesWithPoseMatrix[index];
  74440. var poseMatrix = mesh.getPoseMatrix();
  74441. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74442. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74443. }
  74444. if (this._synchronizedWithMesh !== mesh) {
  74445. this._synchronizedWithMesh = mesh;
  74446. // Prepare bones
  74447. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74448. var bone = this.bones[boneIndex];
  74449. if (!bone.getParent()) {
  74450. var matrix = bone.getBaseMatrix();
  74451. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74452. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74453. }
  74454. }
  74455. }
  74456. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74457. }
  74458. }
  74459. else {
  74460. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74461. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74462. }
  74463. this._computeTransformMatrices(this._transformMatrices, null);
  74464. }
  74465. this._isDirty = false;
  74466. this._scene._activeBones.addCount(this.bones.length, false);
  74467. };
  74468. Skeleton.prototype.getAnimatables = function () {
  74469. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74470. this._animatables = [];
  74471. for (var index = 0; index < this.bones.length; index++) {
  74472. this._animatables.push(this.bones[index]);
  74473. }
  74474. }
  74475. return this._animatables;
  74476. };
  74477. Skeleton.prototype.clone = function (name, id) {
  74478. var result = new Skeleton(name, id || name, this._scene);
  74479. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74480. for (var index = 0; index < this.bones.length; index++) {
  74481. var source = this.bones[index];
  74482. var parentBone = null;
  74483. var parent_1 = source.getParent();
  74484. if (parent_1) {
  74485. var parentIndex = this.bones.indexOf(parent_1);
  74486. parentBone = result.bones[parentIndex];
  74487. }
  74488. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74489. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74490. }
  74491. if (this._ranges) {
  74492. result._ranges = {};
  74493. for (var rangeName in this._ranges) {
  74494. var range = this._ranges[rangeName];
  74495. if (range) {
  74496. result._ranges[rangeName] = range.clone();
  74497. }
  74498. }
  74499. }
  74500. this._isDirty = true;
  74501. return result;
  74502. };
  74503. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74504. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74505. this.bones.forEach(function (bone) {
  74506. bone.animations.forEach(function (animation) {
  74507. animation.enableBlending = true;
  74508. animation.blendingSpeed = blendingSpeed;
  74509. });
  74510. });
  74511. };
  74512. Skeleton.prototype.dispose = function () {
  74513. this._meshesWithPoseMatrix = [];
  74514. // Animations
  74515. this.getScene().stopAnimation(this);
  74516. // Remove from scene
  74517. this.getScene().removeSkeleton(this);
  74518. };
  74519. Skeleton.prototype.serialize = function () {
  74520. var serializationObject = {};
  74521. serializationObject.name = this.name;
  74522. serializationObject.id = this.id;
  74523. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  74524. serializationObject.bones = [];
  74525. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74526. for (var index = 0; index < this.bones.length; index++) {
  74527. var bone = this.bones[index];
  74528. var parent_2 = bone.getParent();
  74529. var serializedBone = {
  74530. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74531. name: bone.name,
  74532. matrix: bone.getBaseMatrix().toArray(),
  74533. rest: bone.getRestPose().toArray()
  74534. };
  74535. serializationObject.bones.push(serializedBone);
  74536. if (bone.length) {
  74537. serializedBone.length = bone.length;
  74538. }
  74539. if (bone.animations && bone.animations.length > 0) {
  74540. serializedBone.animation = bone.animations[0].serialize();
  74541. }
  74542. serializationObject.ranges = [];
  74543. for (var name in this._ranges) {
  74544. var source = this._ranges[name];
  74545. if (!source) {
  74546. continue;
  74547. }
  74548. var range = {};
  74549. range.name = name;
  74550. range.from = source.from;
  74551. range.to = source.to;
  74552. serializationObject.ranges.push(range);
  74553. }
  74554. }
  74555. return serializationObject;
  74556. };
  74557. Skeleton.Parse = function (parsedSkeleton, scene) {
  74558. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74559. if (parsedSkeleton.dimensionsAtRest) {
  74560. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74561. }
  74562. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74563. var index;
  74564. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74565. var parsedBone = parsedSkeleton.bones[index];
  74566. var parentBone = null;
  74567. if (parsedBone.parentBoneIndex > -1) {
  74568. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74569. }
  74570. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74571. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74572. if (parsedBone.length) {
  74573. bone.length = parsedBone.length;
  74574. }
  74575. if (parsedBone.animation) {
  74576. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74577. }
  74578. }
  74579. // placed after bones, so createAnimationRange can cascade down
  74580. if (parsedSkeleton.ranges) {
  74581. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74582. var data = parsedSkeleton.ranges[index];
  74583. skeleton.createAnimationRange(data.name, data.from, data.to);
  74584. }
  74585. }
  74586. return skeleton;
  74587. };
  74588. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74589. if (forceUpdate === void 0) { forceUpdate = false; }
  74590. var renderId = this._scene.getRenderId();
  74591. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74592. this.bones[0].computeAbsoluteTransforms();
  74593. this._lastAbsoluteTransformsUpdateId = renderId;
  74594. }
  74595. };
  74596. Skeleton.prototype.getPoseMatrix = function () {
  74597. var poseMatrix = null;
  74598. if (this._meshesWithPoseMatrix.length > 0) {
  74599. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74600. }
  74601. return poseMatrix;
  74602. };
  74603. Skeleton.prototype.sortBones = function () {
  74604. var bones = new Array();
  74605. var visited = new Array(this.bones.length);
  74606. for (var index = 0; index < this.bones.length; index++) {
  74607. this._sortBones(index, bones, visited);
  74608. }
  74609. this.bones = bones;
  74610. };
  74611. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74612. if (visited[index]) {
  74613. return;
  74614. }
  74615. visited[index] = true;
  74616. var bone = this.bones[index];
  74617. if (bone._index === undefined) {
  74618. bone._index = index;
  74619. }
  74620. var parentBone = bone.getParent();
  74621. if (parentBone) {
  74622. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74623. }
  74624. bones.push(bone);
  74625. };
  74626. return Skeleton;
  74627. }());
  74628. BABYLON.Skeleton = Skeleton;
  74629. })(BABYLON || (BABYLON = {}));
  74630. //# sourceMappingURL=babylon.skeleton.js.map
  74631. "use strict";
  74632. var BABYLON;
  74633. (function (BABYLON) {
  74634. var SphericalPolynomial = /** @class */ (function () {
  74635. function SphericalPolynomial() {
  74636. this.x = BABYLON.Vector3.Zero();
  74637. this.y = BABYLON.Vector3.Zero();
  74638. this.z = BABYLON.Vector3.Zero();
  74639. this.xx = BABYLON.Vector3.Zero();
  74640. this.yy = BABYLON.Vector3.Zero();
  74641. this.zz = BABYLON.Vector3.Zero();
  74642. this.xy = BABYLON.Vector3.Zero();
  74643. this.yz = BABYLON.Vector3.Zero();
  74644. this.zx = BABYLON.Vector3.Zero();
  74645. }
  74646. SphericalPolynomial.prototype.addAmbient = function (color) {
  74647. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74648. this.xx = this.xx.add(colorVector);
  74649. this.yy = this.yy.add(colorVector);
  74650. this.zz = this.zz.add(colorVector);
  74651. };
  74652. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74653. var result = new SphericalPolynomial();
  74654. result.x = harmonics.L11.scale(1.02333);
  74655. result.y = harmonics.L1_1.scale(1.02333);
  74656. result.z = harmonics.L10.scale(1.02333);
  74657. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74658. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74659. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74660. result.yz = harmonics.L2_1.scale(0.858086);
  74661. result.zx = harmonics.L21.scale(0.858086);
  74662. result.xy = harmonics.L2_2.scale(0.858086);
  74663. result.scale(1.0 / Math.PI);
  74664. return result;
  74665. };
  74666. SphericalPolynomial.prototype.scale = function (scale) {
  74667. this.x = this.x.scale(scale);
  74668. this.y = this.y.scale(scale);
  74669. this.z = this.z.scale(scale);
  74670. this.xx = this.xx.scale(scale);
  74671. this.yy = this.yy.scale(scale);
  74672. this.zz = this.zz.scale(scale);
  74673. this.yz = this.yz.scale(scale);
  74674. this.zx = this.zx.scale(scale);
  74675. this.xy = this.xy.scale(scale);
  74676. };
  74677. return SphericalPolynomial;
  74678. }());
  74679. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74680. var SphericalHarmonics = /** @class */ (function () {
  74681. function SphericalHarmonics() {
  74682. this.L00 = BABYLON.Vector3.Zero();
  74683. this.L1_1 = BABYLON.Vector3.Zero();
  74684. this.L10 = BABYLON.Vector3.Zero();
  74685. this.L11 = BABYLON.Vector3.Zero();
  74686. this.L2_2 = BABYLON.Vector3.Zero();
  74687. this.L2_1 = BABYLON.Vector3.Zero();
  74688. this.L20 = BABYLON.Vector3.Zero();
  74689. this.L21 = BABYLON.Vector3.Zero();
  74690. this.L22 = BABYLON.Vector3.Zero();
  74691. }
  74692. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74693. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74694. var c = colorVector.scale(deltaSolidAngle);
  74695. this.L00 = this.L00.add(c.scale(0.282095));
  74696. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74697. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74698. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74699. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74700. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74701. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74702. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74703. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74704. };
  74705. SphericalHarmonics.prototype.scale = function (scale) {
  74706. this.L00 = this.L00.scale(scale);
  74707. this.L1_1 = this.L1_1.scale(scale);
  74708. this.L10 = this.L10.scale(scale);
  74709. this.L11 = this.L11.scale(scale);
  74710. this.L2_2 = this.L2_2.scale(scale);
  74711. this.L2_1 = this.L2_1.scale(scale);
  74712. this.L20 = this.L20.scale(scale);
  74713. this.L21 = this.L21.scale(scale);
  74714. this.L22 = this.L22.scale(scale);
  74715. };
  74716. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74717. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74718. //
  74719. // E_lm = A_l * L_lm
  74720. //
  74721. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74722. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74723. // the scaling factors are given in equation 9.
  74724. // Constant (Band 0)
  74725. this.L00 = this.L00.scale(3.141593);
  74726. // Linear (Band 1)
  74727. this.L1_1 = this.L1_1.scale(2.094395);
  74728. this.L10 = this.L10.scale(2.094395);
  74729. this.L11 = this.L11.scale(2.094395);
  74730. // Quadratic (Band 2)
  74731. this.L2_2 = this.L2_2.scale(0.785398);
  74732. this.L2_1 = this.L2_1.scale(0.785398);
  74733. this.L20 = this.L20.scale(0.785398);
  74734. this.L21 = this.L21.scale(0.785398);
  74735. this.L22 = this.L22.scale(0.785398);
  74736. };
  74737. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74738. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74739. // L = (1/pi) * E * rho
  74740. //
  74741. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74742. this.scale(1.0 / Math.PI);
  74743. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74744. // (The pixel shader must apply albedo after texture fetches, etc).
  74745. };
  74746. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74747. var result = new SphericalHarmonics();
  74748. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74749. result.L1_1 = polynomial.y.scale(0.977204);
  74750. result.L10 = polynomial.z.scale(0.977204);
  74751. result.L11 = polynomial.x.scale(0.977204);
  74752. result.L2_2 = polynomial.xy.scale(1.16538);
  74753. result.L2_1 = polynomial.yz.scale(1.16538);
  74754. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74755. result.L21 = polynomial.zx.scale(1.16538);
  74756. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74757. result.scale(Math.PI);
  74758. return result;
  74759. };
  74760. return SphericalHarmonics;
  74761. }());
  74762. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74763. })(BABYLON || (BABYLON = {}));
  74764. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74765. "use strict";
  74766. var BABYLON;
  74767. (function (BABYLON) {
  74768. var FileFaceOrientation = /** @class */ (function () {
  74769. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74770. this.name = name;
  74771. this.worldAxisForNormal = worldAxisForNormal;
  74772. this.worldAxisForFileX = worldAxisForFileX;
  74773. this.worldAxisForFileY = worldAxisForFileY;
  74774. }
  74775. return FileFaceOrientation;
  74776. }());
  74777. ;
  74778. /**
  74779. * Helper class dealing with the extraction of spherical polynomial dataArray
  74780. * from a cube map.
  74781. */
  74782. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74783. function CubeMapToSphericalPolynomialTools() {
  74784. }
  74785. /**
  74786. * Converts a texture to the according Spherical Polynomial data.
  74787. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74788. *
  74789. * @param texture The texture to extract the information from.
  74790. * @return The Spherical Polynomial data.
  74791. */
  74792. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74793. if (!texture.isCube) {
  74794. // Only supports cube Textures currently.
  74795. return null;
  74796. }
  74797. var size = texture.getSize().width;
  74798. var right = texture.readPixels(0);
  74799. var left = texture.readPixels(1);
  74800. var up;
  74801. var down;
  74802. if (texture.isRenderTarget) {
  74803. up = texture.readPixels(3);
  74804. down = texture.readPixels(2);
  74805. }
  74806. else {
  74807. up = texture.readPixels(2);
  74808. down = texture.readPixels(3);
  74809. }
  74810. var front = texture.readPixels(4);
  74811. var back = texture.readPixels(5);
  74812. var gammaSpace = texture.gammaSpace;
  74813. // Always read as RGBA.
  74814. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74815. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74816. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74817. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74818. }
  74819. var cubeInfo = {
  74820. size: size,
  74821. right: right,
  74822. left: left,
  74823. up: up,
  74824. down: down,
  74825. front: front,
  74826. back: back,
  74827. format: format,
  74828. type: type,
  74829. gammaSpace: gammaSpace,
  74830. };
  74831. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74832. };
  74833. /**
  74834. * Converts a cubemap to the according Spherical Polynomial data.
  74835. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74836. *
  74837. * @param cubeInfo The Cube map to extract the information from.
  74838. * @return The Spherical Polynomial data.
  74839. */
  74840. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74841. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74842. var totalSolidAngle = 0.0;
  74843. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74844. var du = 2.0 / cubeInfo.size;
  74845. var dv = du;
  74846. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74847. var minUV = du * 0.5 - 1.0;
  74848. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74849. var fileFace = this.FileFaces[faceIndex];
  74850. var dataArray = cubeInfo[fileFace.name];
  74851. var v = minUV;
  74852. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74853. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74854. // Because SP is still linear, so summation is fine in that basis.
  74855. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74856. for (var y = 0; y < cubeInfo.size; y++) {
  74857. var u = minUV;
  74858. for (var x = 0; x < cubeInfo.size; x++) {
  74859. // World direction (not normalised)
  74860. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74861. worldDirection.normalize();
  74862. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74863. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74864. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74865. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74866. // Handle Integer types.
  74867. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74868. r /= 255;
  74869. g /= 255;
  74870. b /= 255;
  74871. }
  74872. // Handle Gamma space textures.
  74873. if (cubeInfo.gammaSpace) {
  74874. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74875. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74876. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74877. }
  74878. var color = new BABYLON.Color3(r, g, b);
  74879. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74880. totalSolidAngle += deltaSolidAngle;
  74881. u += du;
  74882. }
  74883. v += dv;
  74884. }
  74885. }
  74886. // Solid angle for entire sphere is 4*pi
  74887. var sphereSolidAngle = 4.0 * Math.PI;
  74888. // Adjust the solid angle to allow for how many faces we processed.
  74889. var facesProcessed = 6.0;
  74890. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74891. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74892. // This is needed because the numerical integration over the cube uses a
  74893. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74894. // and also to compensate for accumulative error due to float precision in the summation.
  74895. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74896. sphericalHarmonics.scale(correctionFactor);
  74897. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74898. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74899. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74900. };
  74901. CubeMapToSphericalPolynomialTools.FileFaces = [
  74902. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74903. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74904. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74905. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74906. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74907. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74908. ];
  74909. return CubeMapToSphericalPolynomialTools;
  74910. }());
  74911. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74912. })(BABYLON || (BABYLON = {}));
  74913. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74914. "use strict";
  74915. var BABYLON;
  74916. (function (BABYLON) {
  74917. /**
  74918. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74919. */
  74920. var PanoramaToCubeMapTools = /** @class */ (function () {
  74921. function PanoramaToCubeMapTools() {
  74922. }
  74923. /**
  74924. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74925. *
  74926. * @param float32Array The source data.
  74927. * @param inputWidth The width of the input panorama.
  74928. * @param inputhHeight The height of the input panorama.
  74929. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74930. * @return The cubemap data
  74931. */
  74932. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74933. if (!float32Array) {
  74934. throw "ConvertPanoramaToCubemap: input cannot be null";
  74935. }
  74936. if (float32Array.length != inputWidth * inputHeight * 3) {
  74937. throw "ConvertPanoramaToCubemap: input size is wrong";
  74938. }
  74939. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74940. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74941. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74942. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74943. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74944. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74945. return {
  74946. front: textureFront,
  74947. back: textureBack,
  74948. left: textureLeft,
  74949. right: textureRight,
  74950. up: textureUp,
  74951. down: textureDown,
  74952. size: size,
  74953. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74954. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74955. gammaSpace: false,
  74956. };
  74957. };
  74958. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74959. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74960. var textureArray = new Float32Array(buffer);
  74961. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74962. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74963. var dy = 1 / texSize;
  74964. var fy = 0;
  74965. for (var y = 0; y < texSize; y++) {
  74966. var xv1 = faceData[0];
  74967. var xv2 = faceData[2];
  74968. for (var x = 0; x < texSize; x++) {
  74969. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74970. v.normalize();
  74971. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74972. // 3 channels per pixels
  74973. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74974. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74975. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74976. xv1 = xv1.add(rotDX1);
  74977. xv2 = xv2.add(rotDX2);
  74978. }
  74979. fy += dy;
  74980. }
  74981. return textureArray;
  74982. };
  74983. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74984. var theta = Math.atan2(vDir.z, vDir.x);
  74985. var phi = Math.acos(vDir.y);
  74986. while (theta < -Math.PI)
  74987. theta += 2 * Math.PI;
  74988. while (theta > Math.PI)
  74989. theta -= 2 * Math.PI;
  74990. var dx = theta / Math.PI;
  74991. var dy = phi / Math.PI;
  74992. // recenter.
  74993. dx = dx * 0.5 + 0.5;
  74994. var px = Math.round(dx * inputWidth);
  74995. if (px < 0)
  74996. px = 0;
  74997. else if (px >= inputWidth)
  74998. px = inputWidth - 1;
  74999. var py = Math.round(dy * inputHeight);
  75000. if (py < 0)
  75001. py = 0;
  75002. else if (py >= inputHeight)
  75003. py = inputHeight - 1;
  75004. var inputY = (inputHeight - py - 1);
  75005. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  75006. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  75007. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  75008. return {
  75009. r: r,
  75010. g: g,
  75011. b: b
  75012. };
  75013. };
  75014. PanoramaToCubeMapTools.FACE_FRONT = [
  75015. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75016. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75017. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75018. new BABYLON.Vector3(1.0, 1.0, -1.0)
  75019. ];
  75020. PanoramaToCubeMapTools.FACE_BACK = [
  75021. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75022. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75023. new BABYLON.Vector3(1.0, 1.0, 1.0),
  75024. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  75025. ];
  75026. PanoramaToCubeMapTools.FACE_RIGHT = [
  75027. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75028. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75029. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75030. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75031. ];
  75032. PanoramaToCubeMapTools.FACE_LEFT = [
  75033. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75034. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75035. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75036. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  75037. ];
  75038. PanoramaToCubeMapTools.FACE_DOWN = [
  75039. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75040. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75041. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75042. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75043. ];
  75044. PanoramaToCubeMapTools.FACE_UP = [
  75045. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75046. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75047. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75048. new BABYLON.Vector3(1.0, -1.0, -1.0)
  75049. ];
  75050. return PanoramaToCubeMapTools;
  75051. }());
  75052. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  75053. })(BABYLON || (BABYLON = {}));
  75054. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  75055. "use strict";
  75056. var BABYLON;
  75057. (function (BABYLON) {
  75058. ;
  75059. /**
  75060. * This groups tools to convert HDR texture to native colors array.
  75061. */
  75062. var HDRTools = /** @class */ (function () {
  75063. function HDRTools() {
  75064. }
  75065. HDRTools.Ldexp = function (mantissa, exponent) {
  75066. if (exponent > 1023) {
  75067. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  75068. }
  75069. if (exponent < -1074) {
  75070. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  75071. }
  75072. return mantissa * Math.pow(2, exponent);
  75073. };
  75074. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  75075. if (exponent > 0) {
  75076. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  75077. float32array[index + 0] = red * exponent;
  75078. float32array[index + 1] = green * exponent;
  75079. float32array[index + 2] = blue * exponent;
  75080. }
  75081. else {
  75082. float32array[index + 0] = 0;
  75083. float32array[index + 1] = 0;
  75084. float32array[index + 2] = 0;
  75085. }
  75086. };
  75087. HDRTools.readStringLine = function (uint8array, startIndex) {
  75088. var line = "";
  75089. var character = "";
  75090. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  75091. character = String.fromCharCode(uint8array[i]);
  75092. if (character == "\n") {
  75093. break;
  75094. }
  75095. line += character;
  75096. }
  75097. return line;
  75098. };
  75099. /**
  75100. * Reads header information from an RGBE texture stored in a native array.
  75101. * More information on this format are available here:
  75102. * https://en.wikipedia.org/wiki/RGBE_image_format
  75103. *
  75104. * @param uint8array The binary file stored in native array.
  75105. * @return The header information.
  75106. */
  75107. HDRTools.RGBE_ReadHeader = function (uint8array) {
  75108. var height = 0;
  75109. var width = 0;
  75110. var line = this.readStringLine(uint8array, 0);
  75111. if (line[0] != '#' || line[1] != '?') {
  75112. throw "Bad HDR Format.";
  75113. }
  75114. var endOfHeader = false;
  75115. var findFormat = false;
  75116. var lineIndex = 0;
  75117. do {
  75118. lineIndex += (line.length + 1);
  75119. line = this.readStringLine(uint8array, lineIndex);
  75120. if (line == "FORMAT=32-bit_rle_rgbe") {
  75121. findFormat = true;
  75122. }
  75123. else if (line.length == 0) {
  75124. endOfHeader = true;
  75125. }
  75126. } while (!endOfHeader);
  75127. if (!findFormat) {
  75128. throw "HDR Bad header format, unsupported FORMAT";
  75129. }
  75130. lineIndex += (line.length + 1);
  75131. line = this.readStringLine(uint8array, lineIndex);
  75132. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  75133. var match = sizeRegexp.exec(line);
  75134. // TODO. Support +Y and -X if needed.
  75135. if (!match || match.length < 3) {
  75136. throw "HDR Bad header format, no size";
  75137. }
  75138. width = parseInt(match[2]);
  75139. height = parseInt(match[1]);
  75140. if (width < 8 || width > 0x7fff) {
  75141. throw "HDR Bad header format, unsupported size";
  75142. }
  75143. lineIndex += (line.length + 1);
  75144. return {
  75145. height: height,
  75146. width: width,
  75147. dataPosition: lineIndex
  75148. };
  75149. };
  75150. /**
  75151. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  75152. * This RGBE texture needs to store the information as a panorama.
  75153. *
  75154. * More information on this format are available here:
  75155. * https://en.wikipedia.org/wiki/RGBE_image_format
  75156. *
  75157. * @param buffer The binary file stored in an array buffer.
  75158. * @param size The expected size of the extracted cubemap.
  75159. * @return The Cube Map information.
  75160. */
  75161. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  75162. var uint8array = new Uint8Array(buffer);
  75163. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  75164. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75165. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75166. return cubeMapData;
  75167. };
  75168. /**
  75169. * Returns the pixels data extracted from an RGBE texture.
  75170. * This pixels will be stored left to right up to down in the R G B order in one array.
  75171. *
  75172. * More information on this format are available here:
  75173. * https://en.wikipedia.org/wiki/RGBE_image_format
  75174. *
  75175. * @param uint8array The binary file stored in an array buffer.
  75176. * @param hdrInfo The header information of the file.
  75177. * @return The pixels data in RGB right to left up to down order.
  75178. */
  75179. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75180. // Keep for multi format supports.
  75181. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75182. };
  75183. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75184. var num_scanlines = hdrInfo.height;
  75185. var scanline_width = hdrInfo.width;
  75186. var a, b, c, d, count;
  75187. var dataIndex = hdrInfo.dataPosition;
  75188. var index = 0, endIndex = 0, i = 0;
  75189. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75190. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75191. // 3 channels of 4 bytes per pixel in float.
  75192. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75193. var resultArray = new Float32Array(resultBuffer);
  75194. // read in each successive scanline
  75195. while (num_scanlines > 0) {
  75196. a = uint8array[dataIndex++];
  75197. b = uint8array[dataIndex++];
  75198. c = uint8array[dataIndex++];
  75199. d = uint8array[dataIndex++];
  75200. if (a != 2 || b != 2 || (c & 0x80)) {
  75201. // this file is not run length encoded
  75202. throw "HDR Bad header format, not RLE";
  75203. }
  75204. if (((c << 8) | d) != scanline_width) {
  75205. throw "HDR Bad header format, wrong scan line width";
  75206. }
  75207. index = 0;
  75208. // read each of the four channels for the scanline into the buffer
  75209. for (i = 0; i < 4; i++) {
  75210. endIndex = (i + 1) * scanline_width;
  75211. while (index < endIndex) {
  75212. a = uint8array[dataIndex++];
  75213. b = uint8array[dataIndex++];
  75214. if (a > 128) {
  75215. // a run of the same value
  75216. count = a - 128;
  75217. if ((count == 0) || (count > endIndex - index)) {
  75218. throw "HDR Bad Format, bad scanline data (run)";
  75219. }
  75220. while (count-- > 0) {
  75221. scanLineArray[index++] = b;
  75222. }
  75223. }
  75224. else {
  75225. // a non-run
  75226. count = a;
  75227. if ((count == 0) || (count > endIndex - index)) {
  75228. throw "HDR Bad Format, bad scanline data (non-run)";
  75229. }
  75230. scanLineArray[index++] = b;
  75231. if (--count > 0) {
  75232. for (var j = 0; j < count; j++) {
  75233. scanLineArray[index++] = uint8array[dataIndex++];
  75234. }
  75235. }
  75236. }
  75237. }
  75238. }
  75239. // now convert data from buffer into floats
  75240. for (i = 0; i < scanline_width; i++) {
  75241. a = scanLineArray[i];
  75242. b = scanLineArray[i + scanline_width];
  75243. c = scanLineArray[i + 2 * scanline_width];
  75244. d = scanLineArray[i + 3 * scanline_width];
  75245. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75246. }
  75247. num_scanlines--;
  75248. }
  75249. return resultArray;
  75250. };
  75251. return HDRTools;
  75252. }());
  75253. BABYLON.HDRTools = HDRTools;
  75254. })(BABYLON || (BABYLON = {}));
  75255. //# sourceMappingURL=babylon.hdr.js.map
  75256. "use strict";
  75257. var BABYLON;
  75258. (function (BABYLON) {
  75259. /**
  75260. * This represents a texture coming from an HDR input.
  75261. *
  75262. * The only supported format is currently panorama picture stored in RGBE format.
  75263. * Example of such files can be found on HDRLib: http://hdrlib.com/
  75264. */
  75265. var HDRCubeTexture = /** @class */ (function (_super) {
  75266. __extends(HDRCubeTexture, _super);
  75267. /**
  75268. * Instantiates an HDRTexture from the following parameters.
  75269. *
  75270. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  75271. * @param scene The scene the texture will be used in
  75272. * @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.
  75273. * @param noMipmap Forces to not generate the mipmap if true
  75274. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  75275. * @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)
  75276. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  75277. */
  75278. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  75279. if (noMipmap === void 0) { noMipmap = false; }
  75280. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75281. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75282. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75283. if (onLoad === void 0) { onLoad = null; }
  75284. if (onError === void 0) { onError = null; }
  75285. var _this = _super.call(this, scene) || this;
  75286. _this._useInGammaSpace = false;
  75287. _this._generateHarmonics = true;
  75288. _this._isBABYLONPreprocessed = false;
  75289. _this._onLoad = null;
  75290. _this._onError = null;
  75291. /**
  75292. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  75293. */
  75294. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  75295. /**
  75296. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  75297. * This is usefull at run time to apply the good shader.
  75298. */
  75299. _this.isPMREM = false;
  75300. _this._isBlocking = true;
  75301. /**
  75302. * Gets or sets the center of the bounding box associated with the cube texture
  75303. * It must define where the camera used to render the texture was set
  75304. */
  75305. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  75306. if (!url) {
  75307. return _this;
  75308. }
  75309. _this.name = url;
  75310. _this.url = url;
  75311. _this.hasAlpha = false;
  75312. _this.isCube = true;
  75313. _this._textureMatrix = BABYLON.Matrix.Identity();
  75314. _this._onLoad = onLoad;
  75315. _this._onError = onError;
  75316. _this.gammaSpace = false;
  75317. var caps = scene.getEngine().getCaps();
  75318. if (size) {
  75319. _this._isBABYLONPreprocessed = false;
  75320. _this._noMipmap = noMipmap;
  75321. _this._size = size;
  75322. _this._useInGammaSpace = useInGammaSpace;
  75323. _this._usePMREMGenerator = usePMREMGenerator &&
  75324. caps.textureLOD &&
  75325. caps.textureFloat &&
  75326. !_this._useInGammaSpace;
  75327. }
  75328. else {
  75329. _this._isBABYLONPreprocessed = true;
  75330. _this._noMipmap = false;
  75331. _this._useInGammaSpace = false;
  75332. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75333. !_this._useInGammaSpace;
  75334. }
  75335. _this.isPMREM = _this._usePMREMGenerator;
  75336. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75337. if (!_this._texture) {
  75338. if (!scene.useDelayedTextureLoading) {
  75339. _this.loadTexture();
  75340. }
  75341. else {
  75342. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75343. }
  75344. }
  75345. return _this;
  75346. }
  75347. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75348. /**
  75349. * Gets wether or not the texture is blocking during loading.
  75350. */
  75351. get: function () {
  75352. return this._isBlocking;
  75353. },
  75354. /**
  75355. * Sets wether or not the texture is blocking during loading.
  75356. */
  75357. set: function (value) {
  75358. this._isBlocking = value;
  75359. },
  75360. enumerable: true,
  75361. configurable: true
  75362. });
  75363. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75364. get: function () {
  75365. return this._boundingBoxSize;
  75366. },
  75367. /**
  75368. * Gets or sets the size of the bounding box associated with the cube texture
  75369. * When defined, the cubemap will switch to local mode
  75370. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75371. * @example https://www.babylonjs-playground.com/#RNASML
  75372. */
  75373. set: function (value) {
  75374. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75375. return;
  75376. }
  75377. this._boundingBoxSize = value;
  75378. var scene = this.getScene();
  75379. if (scene) {
  75380. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75381. }
  75382. },
  75383. enumerable: true,
  75384. configurable: true
  75385. });
  75386. /**
  75387. * Occurs when the file is a preprocessed .babylon.hdr file.
  75388. */
  75389. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75390. var _this = this;
  75391. var mipLevels = 0;
  75392. var floatArrayView = null;
  75393. var scene = this.getScene();
  75394. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75395. var mips = new Array();
  75396. if (!floatArrayView) {
  75397. return mips;
  75398. }
  75399. var startIndex = 30;
  75400. for (var level = 0; level < mipLevels; level++) {
  75401. mips.push([]);
  75402. // Fill each pixel of the mip level.
  75403. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75404. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75405. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75406. mips[level].push(faceData);
  75407. startIndex += faceSize;
  75408. }
  75409. }
  75410. return mips;
  75411. } : null;
  75412. var callback = function (buffer) {
  75413. var scene = _this.getScene();
  75414. if (!scene) {
  75415. return null;
  75416. }
  75417. // Create Native Array Views
  75418. var intArrayView = new Int32Array(buffer);
  75419. floatArrayView = new Float32Array(buffer);
  75420. // Fill header.
  75421. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75422. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75423. // Update Texture Information.
  75424. if (!_this._texture) {
  75425. return null;
  75426. }
  75427. _this._texture.updateSize(_this._size, _this._size);
  75428. // Fill polynomial information.
  75429. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75430. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75431. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75432. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75433. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75434. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75435. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75436. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75437. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75438. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75439. _this.sphericalPolynomial = sphericalPolynomial;
  75440. // Fill pixel data.
  75441. mipLevels = intArrayView[29]; // Number of mip levels.
  75442. var startIndex = 30;
  75443. var data = [];
  75444. var faceSize = Math.pow(_this._size, 2) * 3;
  75445. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75446. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75447. startIndex += faceSize;
  75448. }
  75449. var results = [];
  75450. var byteArray = null;
  75451. // Push each faces.
  75452. for (var k = 0; k < 6; k++) {
  75453. var dataFace = null;
  75454. // To be deprecated.
  75455. if (version === 1) {
  75456. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75457. dataFace = data[j];
  75458. }
  75459. // If special cases.
  75460. if (!mipmapGenerator && dataFace) {
  75461. if (!scene.getEngine().getCaps().textureFloat) {
  75462. // 3 channels of 1 bytes per pixel in bytes.
  75463. var byteBuffer = new ArrayBuffer(faceSize);
  75464. byteArray = new Uint8Array(byteBuffer);
  75465. }
  75466. for (var i = 0; i < _this._size * _this._size; i++) {
  75467. // Put in gamma space if requested.
  75468. if (_this._useInGammaSpace) {
  75469. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75470. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75471. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75472. }
  75473. // Convert to int texture for fallback.
  75474. if (byteArray) {
  75475. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75476. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75477. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75478. // May use luminance instead if the result is not accurate.
  75479. var max = Math.max(Math.max(r, g), b);
  75480. if (max > 255) {
  75481. var scale = 255 / max;
  75482. r *= scale;
  75483. g *= scale;
  75484. b *= scale;
  75485. }
  75486. byteArray[(i * 3) + 0] = r;
  75487. byteArray[(i * 3) + 1] = g;
  75488. byteArray[(i * 3) + 2] = b;
  75489. }
  75490. }
  75491. }
  75492. // Fill the array accordingly.
  75493. if (byteArray) {
  75494. results.push(byteArray);
  75495. }
  75496. else {
  75497. results.push(dataFace);
  75498. }
  75499. }
  75500. return results;
  75501. };
  75502. if (scene) {
  75503. 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);
  75504. }
  75505. };
  75506. /**
  75507. * Occurs when the file is raw .hdr file.
  75508. */
  75509. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75510. var _this = this;
  75511. var callback = function (buffer) {
  75512. var scene = _this.getScene();
  75513. if (!scene) {
  75514. return null;
  75515. }
  75516. // Extract the raw linear data.
  75517. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75518. // Generate harmonics if needed.
  75519. if (_this._generateHarmonics) {
  75520. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75521. _this.sphericalPolynomial = sphericalPolynomial;
  75522. }
  75523. var results = [];
  75524. var byteArray = null;
  75525. // Push each faces.
  75526. for (var j = 0; j < 6; j++) {
  75527. // Create uintarray fallback.
  75528. if (!scene.getEngine().getCaps().textureFloat) {
  75529. // 3 channels of 1 bytes per pixel in bytes.
  75530. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75531. byteArray = new Uint8Array(byteBuffer);
  75532. }
  75533. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75534. // If special cases.
  75535. if (_this._useInGammaSpace || byteArray) {
  75536. for (var i = 0; i < _this._size * _this._size; i++) {
  75537. // Put in gamma space if requested.
  75538. if (_this._useInGammaSpace) {
  75539. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75540. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75541. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75542. }
  75543. // Convert to int texture for fallback.
  75544. if (byteArray) {
  75545. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75546. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75547. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75548. // May use luminance instead if the result is not accurate.
  75549. var max = Math.max(Math.max(r, g), b);
  75550. if (max > 255) {
  75551. var scale = 255 / max;
  75552. r *= scale;
  75553. g *= scale;
  75554. b *= scale;
  75555. }
  75556. byteArray[(i * 3) + 0] = r;
  75557. byteArray[(i * 3) + 1] = g;
  75558. byteArray[(i * 3) + 2] = b;
  75559. }
  75560. }
  75561. }
  75562. if (byteArray) {
  75563. results.push(byteArray);
  75564. }
  75565. else {
  75566. results.push(dataFace);
  75567. }
  75568. }
  75569. return results;
  75570. };
  75571. var mipmapGenerator = null;
  75572. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75573. // if (!this._noMipmap &&
  75574. // this._usePMREMGenerator) {
  75575. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75576. // // Custom setup of the generator matching with the PBR shader values.
  75577. // var generator = new BABYLON.PMREMGenerator(data,
  75578. // this._size,
  75579. // this._size,
  75580. // 0,
  75581. // 3,
  75582. // this.getScene().getEngine().getCaps().textureFloat,
  75583. // 2048,
  75584. // 0.25,
  75585. // false,
  75586. // true);
  75587. // return generator.filterCubeMap();
  75588. // };
  75589. // }
  75590. var scene = this.getScene();
  75591. if (scene) {
  75592. 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);
  75593. }
  75594. };
  75595. /**
  75596. * Starts the loading process of the texture.
  75597. */
  75598. HDRCubeTexture.prototype.loadTexture = function () {
  75599. if (this._isBABYLONPreprocessed) {
  75600. this.loadBabylonTexture();
  75601. }
  75602. else {
  75603. this.loadHDRTexture();
  75604. }
  75605. };
  75606. HDRCubeTexture.prototype.clone = function () {
  75607. var scene = this.getScene();
  75608. if (!scene) {
  75609. return this;
  75610. }
  75611. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75612. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75613. // Base texture
  75614. newTexture.level = this.level;
  75615. newTexture.wrapU = this.wrapU;
  75616. newTexture.wrapV = this.wrapV;
  75617. newTexture.coordinatesIndex = this.coordinatesIndex;
  75618. newTexture.coordinatesMode = this.coordinatesMode;
  75619. return newTexture;
  75620. };
  75621. // Methods
  75622. HDRCubeTexture.prototype.delayLoad = function () {
  75623. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75624. return;
  75625. }
  75626. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75627. this._texture = this._getFromCache(this.url, this._noMipmap);
  75628. if (!this._texture) {
  75629. this.loadTexture();
  75630. }
  75631. };
  75632. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75633. return this._textureMatrix;
  75634. };
  75635. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75636. this._textureMatrix = value;
  75637. };
  75638. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75639. var texture = null;
  75640. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75641. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75642. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75643. texture.name = parsedTexture.name;
  75644. texture.hasAlpha = parsedTexture.hasAlpha;
  75645. texture.level = parsedTexture.level;
  75646. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75647. texture.isBlocking = parsedTexture.isBlocking;
  75648. }
  75649. if (texture) {
  75650. if (parsedTexture.boundingBoxPosition) {
  75651. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75652. }
  75653. if (parsedTexture.boundingBoxSize) {
  75654. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75655. }
  75656. }
  75657. return texture;
  75658. };
  75659. HDRCubeTexture.prototype.serialize = function () {
  75660. if (!this.name) {
  75661. return null;
  75662. }
  75663. var serializationObject = {};
  75664. serializationObject.name = this.name;
  75665. serializationObject.hasAlpha = this.hasAlpha;
  75666. serializationObject.isCube = true;
  75667. serializationObject.level = this.level;
  75668. serializationObject.size = this._size;
  75669. serializationObject.coordinatesMode = this.coordinatesMode;
  75670. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75671. serializationObject.generateHarmonics = this._generateHarmonics;
  75672. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75673. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75674. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75675. serializationObject.noMipmap = this._noMipmap;
  75676. serializationObject.isBlocking = this._isBlocking;
  75677. return serializationObject;
  75678. };
  75679. /**
  75680. * Saves as a file the data contained in the texture in a binary format.
  75681. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75682. * as the spherical used in the lighting.
  75683. * @param url The HDR file url.
  75684. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75685. * @param onError Method called if any error happens during download.
  75686. * @return The packed binary data.
  75687. */
  75688. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75689. if (onError === void 0) { onError = null; }
  75690. var callback = function (buffer) {
  75691. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75692. // Returns a URL you can use as a href.
  75693. var objUrl = window.URL.createObjectURL(data);
  75694. // Simulates a link to it and click to dowload.
  75695. var a = document.createElement("a");
  75696. document.body.appendChild(a);
  75697. a.style.display = "none";
  75698. a.href = objUrl;
  75699. a.download = "envmap.babylon.hdr";
  75700. a.click();
  75701. };
  75702. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75703. };
  75704. /**
  75705. * Serializes the data contained in the texture in a binary format.
  75706. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75707. * as the spherical used in the lighting.
  75708. * @param url The HDR file url.
  75709. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75710. * @param onError Method called if any error happens during download.
  75711. * @return The packed binary data.
  75712. */
  75713. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75714. if (onError === void 0) { onError = null; }
  75715. // Needs the url tho create the texture.
  75716. if (!url) {
  75717. return;
  75718. }
  75719. // Check Power of two size.
  75720. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75721. return;
  75722. }
  75723. // Coming Back in 3.x.
  75724. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75725. };
  75726. HDRCubeTexture._facesMapping = [
  75727. "right",
  75728. "left",
  75729. "up",
  75730. "down",
  75731. "front",
  75732. "back"
  75733. ];
  75734. return HDRCubeTexture;
  75735. }(BABYLON.BaseTexture));
  75736. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75737. })(BABYLON || (BABYLON = {}));
  75738. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75739. "use strict";
  75740. var BABYLON;
  75741. (function (BABYLON) {
  75742. var IndexedVector2 = /** @class */ (function (_super) {
  75743. __extends(IndexedVector2, _super);
  75744. function IndexedVector2(original, index) {
  75745. var _this = _super.call(this, original.x, original.y) || this;
  75746. _this.index = index;
  75747. return _this;
  75748. }
  75749. return IndexedVector2;
  75750. }(BABYLON.Vector2));
  75751. var PolygonPoints = /** @class */ (function () {
  75752. function PolygonPoints() {
  75753. this.elements = new Array();
  75754. }
  75755. PolygonPoints.prototype.add = function (originalPoints) {
  75756. var _this = this;
  75757. var result = new Array();
  75758. originalPoints.forEach(function (point) {
  75759. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75760. var newPoint = new IndexedVector2(point, _this.elements.length);
  75761. result.push(newPoint);
  75762. _this.elements.push(newPoint);
  75763. }
  75764. });
  75765. return result;
  75766. };
  75767. PolygonPoints.prototype.computeBounds = function () {
  75768. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75769. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75770. this.elements.forEach(function (point) {
  75771. // x
  75772. if (point.x < lmin.x) {
  75773. lmin.x = point.x;
  75774. }
  75775. else if (point.x > lmax.x) {
  75776. lmax.x = point.x;
  75777. }
  75778. // y
  75779. if (point.y < lmin.y) {
  75780. lmin.y = point.y;
  75781. }
  75782. else if (point.y > lmax.y) {
  75783. lmax.y = point.y;
  75784. }
  75785. });
  75786. return {
  75787. min: lmin,
  75788. max: lmax,
  75789. width: lmax.x - lmin.x,
  75790. height: lmax.y - lmin.y
  75791. };
  75792. };
  75793. return PolygonPoints;
  75794. }());
  75795. var Polygon = /** @class */ (function () {
  75796. function Polygon() {
  75797. }
  75798. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75799. return [
  75800. new BABYLON.Vector2(xmin, ymin),
  75801. new BABYLON.Vector2(xmax, ymin),
  75802. new BABYLON.Vector2(xmax, ymax),
  75803. new BABYLON.Vector2(xmin, ymax)
  75804. ];
  75805. };
  75806. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75807. if (cx === void 0) { cx = 0; }
  75808. if (cy === void 0) { cy = 0; }
  75809. if (numberOfSides === void 0) { numberOfSides = 32; }
  75810. var result = new Array();
  75811. var angle = 0;
  75812. var increment = (Math.PI * 2) / numberOfSides;
  75813. for (var i = 0; i < numberOfSides; i++) {
  75814. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75815. angle -= increment;
  75816. }
  75817. return result;
  75818. };
  75819. Polygon.Parse = function (input) {
  75820. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75821. var i, result = [];
  75822. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75823. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75824. }
  75825. return result;
  75826. };
  75827. Polygon.StartingAt = function (x, y) {
  75828. return BABYLON.Path2.StartingAt(x, y);
  75829. };
  75830. return Polygon;
  75831. }());
  75832. BABYLON.Polygon = Polygon;
  75833. var PolygonMeshBuilder = /** @class */ (function () {
  75834. function PolygonMeshBuilder(name, contours, scene) {
  75835. this._points = new PolygonPoints();
  75836. this._outlinepoints = new PolygonPoints();
  75837. this._holes = new Array();
  75838. this._epoints = new Array();
  75839. this._eholes = new Array();
  75840. this._name = name;
  75841. this._scene = scene;
  75842. var points;
  75843. if (contours instanceof BABYLON.Path2) {
  75844. points = contours.getPoints();
  75845. }
  75846. else {
  75847. points = contours;
  75848. }
  75849. this._addToepoint(points);
  75850. this._points.add(points);
  75851. this._outlinepoints.add(points);
  75852. if (typeof earcut === 'undefined') {
  75853. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  75854. }
  75855. }
  75856. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75857. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75858. var p = points_1[_i];
  75859. this._epoints.push(p.x, p.y);
  75860. }
  75861. };
  75862. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75863. this._points.add(hole);
  75864. var holepoints = new PolygonPoints();
  75865. holepoints.add(hole);
  75866. this._holes.push(holepoints);
  75867. this._eholes.push(this._epoints.length / 2);
  75868. this._addToepoint(hole);
  75869. return this;
  75870. };
  75871. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75872. var _this = this;
  75873. if (updatable === void 0) { updatable = false; }
  75874. if (depth === void 0) { depth = 0; }
  75875. var result = new BABYLON.Mesh(this._name, this._scene);
  75876. var normals = new Array();
  75877. var positions = new Array();
  75878. var uvs = new Array();
  75879. var bounds = this._points.computeBounds();
  75880. this._points.elements.forEach(function (p) {
  75881. normals.push(0, 1.0, 0);
  75882. positions.push(p.x, 0, p.y);
  75883. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75884. });
  75885. var indices = new Array();
  75886. var res = earcut(this._epoints, this._eholes, 2);
  75887. for (var i = 0; i < res.length; i++) {
  75888. indices.push(res[i]);
  75889. }
  75890. if (depth > 0) {
  75891. var positionscount = (positions.length / 3); //get the current pointcount
  75892. this._points.elements.forEach(function (p) {
  75893. normals.push(0, -1.0, 0);
  75894. positions.push(p.x, -depth, p.y);
  75895. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75896. });
  75897. var totalCount = indices.length;
  75898. for (var i = 0; i < totalCount; i += 3) {
  75899. var i0 = indices[i + 0];
  75900. var i1 = indices[i + 1];
  75901. var i2 = indices[i + 2];
  75902. indices.push(i2 + positionscount);
  75903. indices.push(i1 + positionscount);
  75904. indices.push(i0 + positionscount);
  75905. }
  75906. //Add the sides
  75907. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75908. this._holes.forEach(function (hole) {
  75909. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75910. });
  75911. }
  75912. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75913. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75914. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75915. result.setIndices(indices);
  75916. return result;
  75917. };
  75918. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75919. var StartIndex = positions.length / 3;
  75920. var ulength = 0;
  75921. for (var i = 0; i < points.elements.length; i++) {
  75922. var p = points.elements[i];
  75923. var p1;
  75924. if ((i + 1) > points.elements.length - 1) {
  75925. p1 = points.elements[0];
  75926. }
  75927. else {
  75928. p1 = points.elements[i + 1];
  75929. }
  75930. positions.push(p.x, 0, p.y);
  75931. positions.push(p.x, -depth, p.y);
  75932. positions.push(p1.x, 0, p1.y);
  75933. positions.push(p1.x, -depth, p1.y);
  75934. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75935. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75936. var v3 = v2.subtract(v1);
  75937. var v4 = new BABYLON.Vector3(0, 1, 0);
  75938. var vn = BABYLON.Vector3.Cross(v3, v4);
  75939. vn = vn.normalize();
  75940. uvs.push(ulength / bounds.width, 0);
  75941. uvs.push(ulength / bounds.width, 1);
  75942. ulength += v3.length();
  75943. uvs.push((ulength / bounds.width), 0);
  75944. uvs.push((ulength / bounds.width), 1);
  75945. if (!flip) {
  75946. normals.push(-vn.x, -vn.y, -vn.z);
  75947. normals.push(-vn.x, -vn.y, -vn.z);
  75948. normals.push(-vn.x, -vn.y, -vn.z);
  75949. normals.push(-vn.x, -vn.y, -vn.z);
  75950. indices.push(StartIndex);
  75951. indices.push(StartIndex + 1);
  75952. indices.push(StartIndex + 2);
  75953. indices.push(StartIndex + 1);
  75954. indices.push(StartIndex + 3);
  75955. indices.push(StartIndex + 2);
  75956. }
  75957. else {
  75958. normals.push(vn.x, vn.y, vn.z);
  75959. normals.push(vn.x, vn.y, vn.z);
  75960. normals.push(vn.x, vn.y, vn.z);
  75961. normals.push(vn.x, vn.y, vn.z);
  75962. indices.push(StartIndex);
  75963. indices.push(StartIndex + 2);
  75964. indices.push(StartIndex + 1);
  75965. indices.push(StartIndex + 1);
  75966. indices.push(StartIndex + 2);
  75967. indices.push(StartIndex + 3);
  75968. }
  75969. StartIndex += 4;
  75970. }
  75971. ;
  75972. };
  75973. return PolygonMeshBuilder;
  75974. }());
  75975. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75976. })(BABYLON || (BABYLON = {}));
  75977. //# sourceMappingURL=babylon.polygonMesh.js.map
  75978. "use strict";
  75979. var BABYLON;
  75980. (function (BABYLON) {
  75981. // Unique ID when we import meshes from Babylon to CSG
  75982. var currentCSGMeshId = 0;
  75983. // # class Vertex
  75984. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75985. // one to provide additional features like texture coordinates and vertex
  75986. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75987. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75988. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75989. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75990. // is not used anywhere else.
  75991. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75992. var Vertex = /** @class */ (function () {
  75993. function Vertex(pos, normal, uv) {
  75994. this.pos = pos;
  75995. this.normal = normal;
  75996. this.uv = uv;
  75997. }
  75998. Vertex.prototype.clone = function () {
  75999. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76000. };
  76001. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76002. // orientation of a polygon is flipped.
  76003. Vertex.prototype.flip = function () {
  76004. this.normal = this.normal.scale(-1);
  76005. };
  76006. // Create a new vertex between this vertex and `other` by linearly
  76007. // interpolating all properties using a parameter of `t`. Subclasses should
  76008. // override this to interpolate additional properties.
  76009. Vertex.prototype.interpolate = function (other, t) {
  76010. 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));
  76011. };
  76012. return Vertex;
  76013. }());
  76014. // # class Plane
  76015. // Represents a plane in 3D space.
  76016. var Plane = /** @class */ (function () {
  76017. function Plane(normal, w) {
  76018. this.normal = normal;
  76019. this.w = w;
  76020. }
  76021. Plane.FromPoints = function (a, b, c) {
  76022. var v0 = c.subtract(a);
  76023. var v1 = b.subtract(a);
  76024. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76025. return null;
  76026. }
  76027. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76028. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76029. };
  76030. Plane.prototype.clone = function () {
  76031. return new Plane(this.normal.clone(), this.w);
  76032. };
  76033. Plane.prototype.flip = function () {
  76034. this.normal.scaleInPlace(-1);
  76035. this.w = -this.w;
  76036. };
  76037. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76038. // fragments in the appropriate lists. Coplanar polygons go into either
  76039. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76040. // respect to this plane. Polygons in front or in back of this plane go into
  76041. // either `front` or `back`.
  76042. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76043. var COPLANAR = 0;
  76044. var FRONT = 1;
  76045. var BACK = 2;
  76046. var SPANNING = 3;
  76047. // Classify each point as well as the entire polygon into one of the above
  76048. // four classes.
  76049. var polygonType = 0;
  76050. var types = [];
  76051. var i;
  76052. var t;
  76053. for (i = 0; i < polygon.vertices.length; i++) {
  76054. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76055. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76056. polygonType |= type;
  76057. types.push(type);
  76058. }
  76059. // Put the polygon in the correct list, splitting it when necessary.
  76060. switch (polygonType) {
  76061. case COPLANAR:
  76062. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76063. break;
  76064. case FRONT:
  76065. front.push(polygon);
  76066. break;
  76067. case BACK:
  76068. back.push(polygon);
  76069. break;
  76070. case SPANNING:
  76071. var f = [], b = [];
  76072. for (i = 0; i < polygon.vertices.length; i++) {
  76073. var j = (i + 1) % polygon.vertices.length;
  76074. var ti = types[i], tj = types[j];
  76075. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76076. if (ti !== BACK)
  76077. f.push(vi);
  76078. if (ti !== FRONT)
  76079. b.push(ti !== BACK ? vi.clone() : vi);
  76080. if ((ti | tj) === SPANNING) {
  76081. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76082. var v = vi.interpolate(vj, t);
  76083. f.push(v);
  76084. b.push(v.clone());
  76085. }
  76086. }
  76087. var poly;
  76088. if (f.length >= 3) {
  76089. poly = new Polygon(f, polygon.shared);
  76090. if (poly.plane)
  76091. front.push(poly);
  76092. }
  76093. if (b.length >= 3) {
  76094. poly = new Polygon(b, polygon.shared);
  76095. if (poly.plane)
  76096. back.push(poly);
  76097. }
  76098. break;
  76099. }
  76100. };
  76101. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76102. // point is on the plane.
  76103. Plane.EPSILON = 1e-5;
  76104. return Plane;
  76105. }());
  76106. // # class Polygon
  76107. // Represents a convex polygon. The vertices used to initialize a polygon must
  76108. // be coplanar and form a convex loop.
  76109. //
  76110. // Each convex polygon has a `shared` property, which is shared between all
  76111. // polygons that are clones of each other or were split from the same polygon.
  76112. // This can be used to define per-polygon properties (such as surface color).
  76113. var Polygon = /** @class */ (function () {
  76114. function Polygon(vertices, shared) {
  76115. this.vertices = vertices;
  76116. this.shared = shared;
  76117. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76118. }
  76119. Polygon.prototype.clone = function () {
  76120. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76121. return new Polygon(vertices, this.shared);
  76122. };
  76123. Polygon.prototype.flip = function () {
  76124. this.vertices.reverse().map(function (v) { v.flip(); });
  76125. this.plane.flip();
  76126. };
  76127. return Polygon;
  76128. }());
  76129. // # class Node
  76130. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76131. // by picking a polygon to split along. That polygon (and all other coplanar
  76132. // polygons) are added directly to that node and the other polygons are added to
  76133. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76134. // no distinction between internal and leaf nodes.
  76135. var Node = /** @class */ (function () {
  76136. function Node(polygons) {
  76137. this.plane = null;
  76138. this.front = null;
  76139. this.back = null;
  76140. this.polygons = new Array();
  76141. if (polygons) {
  76142. this.build(polygons);
  76143. }
  76144. }
  76145. Node.prototype.clone = function () {
  76146. var node = new Node();
  76147. node.plane = this.plane && this.plane.clone();
  76148. node.front = this.front && this.front.clone();
  76149. node.back = this.back && this.back.clone();
  76150. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76151. return node;
  76152. };
  76153. // Convert solid space to empty space and empty space to solid space.
  76154. Node.prototype.invert = function () {
  76155. for (var i = 0; i < this.polygons.length; i++) {
  76156. this.polygons[i].flip();
  76157. }
  76158. if (this.plane) {
  76159. this.plane.flip();
  76160. }
  76161. if (this.front) {
  76162. this.front.invert();
  76163. }
  76164. if (this.back) {
  76165. this.back.invert();
  76166. }
  76167. var temp = this.front;
  76168. this.front = this.back;
  76169. this.back = temp;
  76170. };
  76171. // Recursively remove all polygons in `polygons` that are inside this BSP
  76172. // tree.
  76173. Node.prototype.clipPolygons = function (polygons) {
  76174. if (!this.plane)
  76175. return polygons.slice();
  76176. var front = new Array(), back = new Array();
  76177. for (var i = 0; i < polygons.length; i++) {
  76178. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76179. }
  76180. if (this.front) {
  76181. front = this.front.clipPolygons(front);
  76182. }
  76183. if (this.back) {
  76184. back = this.back.clipPolygons(back);
  76185. }
  76186. else {
  76187. back = [];
  76188. }
  76189. return front.concat(back);
  76190. };
  76191. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76192. // `bsp`.
  76193. Node.prototype.clipTo = function (bsp) {
  76194. this.polygons = bsp.clipPolygons(this.polygons);
  76195. if (this.front)
  76196. this.front.clipTo(bsp);
  76197. if (this.back)
  76198. this.back.clipTo(bsp);
  76199. };
  76200. // Return a list of all polygons in this BSP tree.
  76201. Node.prototype.allPolygons = function () {
  76202. var polygons = this.polygons.slice();
  76203. if (this.front)
  76204. polygons = polygons.concat(this.front.allPolygons());
  76205. if (this.back)
  76206. polygons = polygons.concat(this.back.allPolygons());
  76207. return polygons;
  76208. };
  76209. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76210. // new polygons are filtered down to the bottom of the tree and become new
  76211. // nodes there. Each set of polygons is partitioned using the first polygon
  76212. // (no heuristic is used to pick a good split).
  76213. Node.prototype.build = function (polygons) {
  76214. if (!polygons.length)
  76215. return;
  76216. if (!this.plane)
  76217. this.plane = polygons[0].plane.clone();
  76218. var front = new Array(), back = new Array();
  76219. for (var i = 0; i < polygons.length; i++) {
  76220. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76221. }
  76222. if (front.length) {
  76223. if (!this.front)
  76224. this.front = new Node();
  76225. this.front.build(front);
  76226. }
  76227. if (back.length) {
  76228. if (!this.back)
  76229. this.back = new Node();
  76230. this.back.build(back);
  76231. }
  76232. };
  76233. return Node;
  76234. }());
  76235. var CSG = /** @class */ (function () {
  76236. function CSG() {
  76237. this.polygons = new Array();
  76238. }
  76239. // Convert BABYLON.Mesh to BABYLON.CSG
  76240. CSG.FromMesh = function (mesh) {
  76241. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76242. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76243. if (mesh instanceof BABYLON.Mesh) {
  76244. mesh.computeWorldMatrix(true);
  76245. matrix = mesh.getWorldMatrix();
  76246. meshPosition = mesh.position.clone();
  76247. meshRotation = mesh.rotation.clone();
  76248. if (mesh.rotationQuaternion) {
  76249. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76250. }
  76251. meshScaling = mesh.scaling.clone();
  76252. }
  76253. else {
  76254. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76255. }
  76256. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76257. var subMeshes = mesh.subMeshes;
  76258. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76259. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76260. vertices = [];
  76261. for (var j = 0; j < 3; j++) {
  76262. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76263. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76264. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76265. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76266. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76267. vertex = new Vertex(position, normal, uv);
  76268. vertices.push(vertex);
  76269. }
  76270. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76271. // To handle the case of degenerated triangle
  76272. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76273. if (polygon.plane)
  76274. polygons.push(polygon);
  76275. }
  76276. }
  76277. var csg = CSG.FromPolygons(polygons);
  76278. csg.matrix = matrix;
  76279. csg.position = meshPosition;
  76280. csg.rotation = meshRotation;
  76281. csg.scaling = meshScaling;
  76282. csg.rotationQuaternion = meshRotationQuaternion;
  76283. currentCSGMeshId++;
  76284. return csg;
  76285. };
  76286. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76287. CSG.FromPolygons = function (polygons) {
  76288. var csg = new CSG();
  76289. csg.polygons = polygons;
  76290. return csg;
  76291. };
  76292. CSG.prototype.clone = function () {
  76293. var csg = new CSG();
  76294. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76295. csg.copyTransformAttributes(this);
  76296. return csg;
  76297. };
  76298. CSG.prototype.union = function (csg) {
  76299. var a = new Node(this.clone().polygons);
  76300. var b = new Node(csg.clone().polygons);
  76301. a.clipTo(b);
  76302. b.clipTo(a);
  76303. b.invert();
  76304. b.clipTo(a);
  76305. b.invert();
  76306. a.build(b.allPolygons());
  76307. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76308. };
  76309. CSG.prototype.unionInPlace = function (csg) {
  76310. var a = new Node(this.polygons);
  76311. var b = new Node(csg.polygons);
  76312. a.clipTo(b);
  76313. b.clipTo(a);
  76314. b.invert();
  76315. b.clipTo(a);
  76316. b.invert();
  76317. a.build(b.allPolygons());
  76318. this.polygons = a.allPolygons();
  76319. };
  76320. CSG.prototype.subtract = function (csg) {
  76321. var a = new Node(this.clone().polygons);
  76322. var b = new Node(csg.clone().polygons);
  76323. a.invert();
  76324. a.clipTo(b);
  76325. b.clipTo(a);
  76326. b.invert();
  76327. b.clipTo(a);
  76328. b.invert();
  76329. a.build(b.allPolygons());
  76330. a.invert();
  76331. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76332. };
  76333. CSG.prototype.subtractInPlace = function (csg) {
  76334. var a = new Node(this.polygons);
  76335. var b = new Node(csg.polygons);
  76336. a.invert();
  76337. a.clipTo(b);
  76338. b.clipTo(a);
  76339. b.invert();
  76340. b.clipTo(a);
  76341. b.invert();
  76342. a.build(b.allPolygons());
  76343. a.invert();
  76344. this.polygons = a.allPolygons();
  76345. };
  76346. CSG.prototype.intersect = function (csg) {
  76347. var a = new Node(this.clone().polygons);
  76348. var b = new Node(csg.clone().polygons);
  76349. a.invert();
  76350. b.clipTo(a);
  76351. b.invert();
  76352. a.clipTo(b);
  76353. b.clipTo(a);
  76354. a.build(b.allPolygons());
  76355. a.invert();
  76356. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76357. };
  76358. CSG.prototype.intersectInPlace = function (csg) {
  76359. var a = new Node(this.polygons);
  76360. var b = new Node(csg.polygons);
  76361. a.invert();
  76362. b.clipTo(a);
  76363. b.invert();
  76364. a.clipTo(b);
  76365. b.clipTo(a);
  76366. a.build(b.allPolygons());
  76367. a.invert();
  76368. this.polygons = a.allPolygons();
  76369. };
  76370. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76371. // not modified.
  76372. CSG.prototype.inverse = function () {
  76373. var csg = this.clone();
  76374. csg.inverseInPlace();
  76375. return csg;
  76376. };
  76377. CSG.prototype.inverseInPlace = function () {
  76378. this.polygons.map(function (p) { p.flip(); });
  76379. };
  76380. // This is used to keep meshes transformations so they can be restored
  76381. // when we build back a Babylon Mesh
  76382. // NB : All CSG operations are performed in world coordinates
  76383. CSG.prototype.copyTransformAttributes = function (csg) {
  76384. this.matrix = csg.matrix;
  76385. this.position = csg.position;
  76386. this.rotation = csg.rotation;
  76387. this.scaling = csg.scaling;
  76388. this.rotationQuaternion = csg.rotationQuaternion;
  76389. return this;
  76390. };
  76391. // Build Raw mesh from CSG
  76392. // Coordinates here are in world space
  76393. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76394. var matrix = this.matrix.clone();
  76395. matrix.invert();
  76396. 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;
  76397. if (keepSubMeshes) {
  76398. // Sort Polygons, since subMeshes are indices range
  76399. polygons.sort(function (a, b) {
  76400. if (a.shared.meshId === b.shared.meshId) {
  76401. return a.shared.subMeshId - b.shared.subMeshId;
  76402. }
  76403. else {
  76404. return a.shared.meshId - b.shared.meshId;
  76405. }
  76406. });
  76407. }
  76408. for (var i = 0, il = polygons.length; i < il; i++) {
  76409. polygon = polygons[i];
  76410. // Building SubMeshes
  76411. if (!subMesh_dict[polygon.shared.meshId]) {
  76412. subMesh_dict[polygon.shared.meshId] = {};
  76413. }
  76414. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76415. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76416. indexStart: +Infinity,
  76417. indexEnd: -Infinity,
  76418. materialIndex: polygon.shared.materialIndex
  76419. };
  76420. }
  76421. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76422. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76423. polygonIndices[0] = 0;
  76424. polygonIndices[1] = j - 1;
  76425. polygonIndices[2] = j;
  76426. for (var k = 0; k < 3; k++) {
  76427. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76428. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76429. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76430. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76431. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76432. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76433. // Check if 2 points can be merged
  76434. if (!(typeof vertex_idx !== 'undefined' &&
  76435. normals[vertex_idx * 3] === localNormal.x &&
  76436. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76437. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76438. uvs[vertex_idx * 2] === uv.x &&
  76439. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76440. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76441. uvs.push(uv.x, uv.y);
  76442. normals.push(normal.x, normal.y, normal.z);
  76443. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76444. }
  76445. indices.push(vertex_idx);
  76446. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76447. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76448. currentIndex++;
  76449. }
  76450. }
  76451. }
  76452. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76453. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76454. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76455. mesh.setIndices(indices, null);
  76456. if (keepSubMeshes) {
  76457. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76458. var materialIndexOffset = 0, materialMaxIndex;
  76459. mesh.subMeshes = new Array();
  76460. for (var m in subMesh_dict) {
  76461. materialMaxIndex = -1;
  76462. for (var sm in subMesh_dict[m]) {
  76463. subMesh_obj = subMesh_dict[m][sm];
  76464. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76465. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76466. }
  76467. materialIndexOffset += ++materialMaxIndex;
  76468. }
  76469. }
  76470. return mesh;
  76471. };
  76472. // Build Mesh from CSG taking material and transforms into account
  76473. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76474. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76475. mesh.material = material;
  76476. mesh.position.copyFrom(this.position);
  76477. mesh.rotation.copyFrom(this.rotation);
  76478. if (this.rotationQuaternion) {
  76479. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76480. }
  76481. mesh.scaling.copyFrom(this.scaling);
  76482. mesh.computeWorldMatrix(true);
  76483. return mesh;
  76484. };
  76485. return CSG;
  76486. }());
  76487. BABYLON.CSG = CSG;
  76488. })(BABYLON || (BABYLON = {}));
  76489. //# sourceMappingURL=babylon.csg.js.map
  76490. "use strict";
  76491. var BABYLON;
  76492. (function (BABYLON) {
  76493. var LensFlare = /** @class */ (function () {
  76494. function LensFlare(size, position, color, imgUrl, system) {
  76495. this.size = size;
  76496. this.position = position;
  76497. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76498. this.color = color || new BABYLON.Color3(1, 1, 1);
  76499. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76500. this._system = system;
  76501. system.lensFlares.push(this);
  76502. }
  76503. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76504. return new LensFlare(size, position, color, imgUrl, system);
  76505. };
  76506. LensFlare.prototype.dispose = function () {
  76507. if (this.texture) {
  76508. this.texture.dispose();
  76509. }
  76510. // Remove from scene
  76511. var index = this._system.lensFlares.indexOf(this);
  76512. this._system.lensFlares.splice(index, 1);
  76513. };
  76514. ;
  76515. return LensFlare;
  76516. }());
  76517. BABYLON.LensFlare = LensFlare;
  76518. })(BABYLON || (BABYLON = {}));
  76519. //# sourceMappingURL=babylon.lensFlare.js.map
  76520. "use strict";
  76521. var BABYLON;
  76522. (function (BABYLON) {
  76523. var LensFlareSystem = /** @class */ (function () {
  76524. function LensFlareSystem(name, emitter, scene) {
  76525. this.name = name;
  76526. this.lensFlares = new Array();
  76527. this.borderLimit = 300;
  76528. this.viewportBorder = 0;
  76529. this.layerMask = 0x0FFFFFFF;
  76530. this._vertexBuffers = {};
  76531. this._isEnabled = true;
  76532. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76533. this._emitter = emitter;
  76534. this.id = name;
  76535. scene.lensFlareSystems.push(this);
  76536. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76537. var engine = scene.getEngine();
  76538. // VBO
  76539. var vertices = [];
  76540. vertices.push(1, 1);
  76541. vertices.push(-1, 1);
  76542. vertices.push(-1, -1);
  76543. vertices.push(1, -1);
  76544. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76545. // Indices
  76546. var indices = [];
  76547. indices.push(0);
  76548. indices.push(1);
  76549. indices.push(2);
  76550. indices.push(0);
  76551. indices.push(2);
  76552. indices.push(3);
  76553. this._indexBuffer = engine.createIndexBuffer(indices);
  76554. // Effects
  76555. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76556. }
  76557. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76558. get: function () {
  76559. return this._isEnabled;
  76560. },
  76561. set: function (value) {
  76562. this._isEnabled = value;
  76563. },
  76564. enumerable: true,
  76565. configurable: true
  76566. });
  76567. LensFlareSystem.prototype.getScene = function () {
  76568. return this._scene;
  76569. };
  76570. LensFlareSystem.prototype.getEmitter = function () {
  76571. return this._emitter;
  76572. };
  76573. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76574. this._emitter = newEmitter;
  76575. };
  76576. LensFlareSystem.prototype.getEmitterPosition = function () {
  76577. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76578. };
  76579. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76580. var position = this.getEmitterPosition();
  76581. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76582. this._positionX = position.x;
  76583. this._positionY = position.y;
  76584. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76585. if (this.viewportBorder > 0) {
  76586. globalViewport.x -= this.viewportBorder;
  76587. globalViewport.y -= this.viewportBorder;
  76588. globalViewport.width += this.viewportBorder * 2;
  76589. globalViewport.height += this.viewportBorder * 2;
  76590. position.x += this.viewportBorder;
  76591. position.y += this.viewportBorder;
  76592. this._positionX += this.viewportBorder;
  76593. this._positionY += this.viewportBorder;
  76594. }
  76595. if (position.z > 0) {
  76596. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76597. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76598. return true;
  76599. }
  76600. return true;
  76601. }
  76602. return false;
  76603. };
  76604. LensFlareSystem.prototype._isVisible = function () {
  76605. if (!this._isEnabled || !this._scene.activeCamera) {
  76606. return false;
  76607. }
  76608. var emitterPosition = this.getEmitterPosition();
  76609. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76610. var distance = direction.length();
  76611. direction.normalize();
  76612. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76613. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76614. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76615. };
  76616. LensFlareSystem.prototype.render = function () {
  76617. if (!this._effect.isReady() || !this._scene.activeCamera)
  76618. return false;
  76619. var engine = this._scene.getEngine();
  76620. var viewport = this._scene.activeCamera.viewport;
  76621. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76622. // Position
  76623. if (!this.computeEffectivePosition(globalViewport)) {
  76624. return false;
  76625. }
  76626. // Visibility
  76627. if (!this._isVisible()) {
  76628. return false;
  76629. }
  76630. // Intensity
  76631. var awayX;
  76632. var awayY;
  76633. if (this._positionX < this.borderLimit + globalViewport.x) {
  76634. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76635. }
  76636. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76637. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76638. }
  76639. else {
  76640. awayX = 0;
  76641. }
  76642. if (this._positionY < this.borderLimit + globalViewport.y) {
  76643. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76644. }
  76645. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76646. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76647. }
  76648. else {
  76649. awayY = 0;
  76650. }
  76651. var away = (awayX > awayY) ? awayX : awayY;
  76652. away -= this.viewportBorder;
  76653. if (away > this.borderLimit) {
  76654. away = this.borderLimit;
  76655. }
  76656. var intensity = 1.0 - (away / this.borderLimit);
  76657. if (intensity < 0) {
  76658. return false;
  76659. }
  76660. if (intensity > 1.0) {
  76661. intensity = 1.0;
  76662. }
  76663. if (this.viewportBorder > 0) {
  76664. globalViewport.x += this.viewportBorder;
  76665. globalViewport.y += this.viewportBorder;
  76666. globalViewport.width -= this.viewportBorder * 2;
  76667. globalViewport.height -= this.viewportBorder * 2;
  76668. this._positionX -= this.viewportBorder;
  76669. this._positionY -= this.viewportBorder;
  76670. }
  76671. // Position
  76672. var centerX = globalViewport.x + globalViewport.width / 2;
  76673. var centerY = globalViewport.y + globalViewport.height / 2;
  76674. var distX = centerX - this._positionX;
  76675. var distY = centerY - this._positionY;
  76676. // Effects
  76677. engine.enableEffect(this._effect);
  76678. engine.setState(false);
  76679. engine.setDepthBuffer(false);
  76680. // VBOs
  76681. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76682. // Flares
  76683. for (var index = 0; index < this.lensFlares.length; index++) {
  76684. var flare = this.lensFlares[index];
  76685. engine.setAlphaMode(flare.alphaMode);
  76686. var x = centerX - (distX * flare.position);
  76687. var y = centerY - (distY * flare.position);
  76688. var cw = flare.size;
  76689. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76690. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76691. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76692. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76693. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76694. // Texture
  76695. this._effect.setTexture("textureSampler", flare.texture);
  76696. // Color
  76697. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76698. // Draw order
  76699. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76700. }
  76701. engine.setDepthBuffer(true);
  76702. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76703. return true;
  76704. };
  76705. LensFlareSystem.prototype.dispose = function () {
  76706. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76707. if (vertexBuffer) {
  76708. vertexBuffer.dispose();
  76709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76710. }
  76711. if (this._indexBuffer) {
  76712. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76713. this._indexBuffer = null;
  76714. }
  76715. while (this.lensFlares.length) {
  76716. this.lensFlares[0].dispose();
  76717. }
  76718. // Remove from scene
  76719. var index = this._scene.lensFlareSystems.indexOf(this);
  76720. this._scene.lensFlareSystems.splice(index, 1);
  76721. };
  76722. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76723. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76724. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76725. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76726. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76727. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76728. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76729. var parsedFlare = parsedLensFlareSystem.flares[index];
  76730. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76731. }
  76732. return lensFlareSystem;
  76733. };
  76734. LensFlareSystem.prototype.serialize = function () {
  76735. var serializationObject = {};
  76736. serializationObject.id = this.id;
  76737. serializationObject.name = this.name;
  76738. serializationObject.emitterId = this.getEmitter().id;
  76739. serializationObject.borderLimit = this.borderLimit;
  76740. serializationObject.flares = [];
  76741. for (var index = 0; index < this.lensFlares.length; index++) {
  76742. var flare = this.lensFlares[index];
  76743. serializationObject.flares.push({
  76744. size: flare.size,
  76745. position: flare.position,
  76746. color: flare.color.asArray(),
  76747. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76748. });
  76749. }
  76750. return serializationObject;
  76751. };
  76752. return LensFlareSystem;
  76753. }());
  76754. BABYLON.LensFlareSystem = LensFlareSystem;
  76755. })(BABYLON || (BABYLON = {}));
  76756. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76757. "use strict";
  76758. var BABYLON;
  76759. (function (BABYLON) {
  76760. /**
  76761. * This is a holder class for the physics joint created by the physics plugin.
  76762. * It holds a set of functions to control the underlying joint.
  76763. */
  76764. var PhysicsJoint = /** @class */ (function () {
  76765. function PhysicsJoint(type, jointData) {
  76766. this.type = type;
  76767. this.jointData = jointData;
  76768. jointData.nativeParams = jointData.nativeParams || {};
  76769. }
  76770. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76771. get: function () {
  76772. return this._physicsJoint;
  76773. },
  76774. set: function (newJoint) {
  76775. if (this._physicsJoint) {
  76776. //remove from the wolrd
  76777. }
  76778. this._physicsJoint = newJoint;
  76779. },
  76780. enumerable: true,
  76781. configurable: true
  76782. });
  76783. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76784. set: function (physicsPlugin) {
  76785. this._physicsPlugin = physicsPlugin;
  76786. },
  76787. enumerable: true,
  76788. configurable: true
  76789. });
  76790. /**
  76791. * Execute a function that is physics-plugin specific.
  76792. * @param {Function} func the function that will be executed.
  76793. * It accepts two parameters: the physics world and the physics joint.
  76794. */
  76795. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76796. func(this._physicsPlugin.world, this._physicsJoint);
  76797. };
  76798. //TODO check if the native joints are the same
  76799. //Joint Types
  76800. PhysicsJoint.DistanceJoint = 0;
  76801. PhysicsJoint.HingeJoint = 1;
  76802. PhysicsJoint.BallAndSocketJoint = 2;
  76803. PhysicsJoint.WheelJoint = 3;
  76804. PhysicsJoint.SliderJoint = 4;
  76805. //OIMO
  76806. PhysicsJoint.PrismaticJoint = 5;
  76807. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76808. PhysicsJoint.UniversalJoint = 6;
  76809. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76810. //Cannon
  76811. //Similar to a Ball-Joint. Different in params
  76812. PhysicsJoint.PointToPointJoint = 8;
  76813. //Cannon only at the moment
  76814. PhysicsJoint.SpringJoint = 9;
  76815. PhysicsJoint.LockJoint = 10;
  76816. return PhysicsJoint;
  76817. }());
  76818. BABYLON.PhysicsJoint = PhysicsJoint;
  76819. /**
  76820. * A class representing a physics distance joint.
  76821. */
  76822. var DistanceJoint = /** @class */ (function (_super) {
  76823. __extends(DistanceJoint, _super);
  76824. function DistanceJoint(jointData) {
  76825. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76826. }
  76827. /**
  76828. * Update the predefined distance.
  76829. */
  76830. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76831. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76832. };
  76833. return DistanceJoint;
  76834. }(PhysicsJoint));
  76835. BABYLON.DistanceJoint = DistanceJoint;
  76836. var MotorEnabledJoint = /** @class */ (function (_super) {
  76837. __extends(MotorEnabledJoint, _super);
  76838. function MotorEnabledJoint(type, jointData) {
  76839. return _super.call(this, type, jointData) || this;
  76840. }
  76841. /**
  76842. * Set the motor values.
  76843. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76844. * @param {number} force the force to apply
  76845. * @param {number} maxForce max force for this motor.
  76846. */
  76847. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76848. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76849. };
  76850. /**
  76851. * Set the motor's limits.
  76852. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76853. */
  76854. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76855. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76856. };
  76857. return MotorEnabledJoint;
  76858. }(PhysicsJoint));
  76859. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76860. /**
  76861. * This class represents a single hinge physics joint
  76862. */
  76863. var HingeJoint = /** @class */ (function (_super) {
  76864. __extends(HingeJoint, _super);
  76865. function HingeJoint(jointData) {
  76866. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76867. }
  76868. /**
  76869. * Set the motor values.
  76870. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76871. * @param {number} force the force to apply
  76872. * @param {number} maxForce max force for this motor.
  76873. */
  76874. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76875. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76876. };
  76877. /**
  76878. * Set the motor's limits.
  76879. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76880. */
  76881. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76882. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76883. };
  76884. return HingeJoint;
  76885. }(MotorEnabledJoint));
  76886. BABYLON.HingeJoint = HingeJoint;
  76887. /**
  76888. * This class represents a dual hinge physics joint (same as wheel joint)
  76889. */
  76890. var Hinge2Joint = /** @class */ (function (_super) {
  76891. __extends(Hinge2Joint, _super);
  76892. function Hinge2Joint(jointData) {
  76893. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76894. }
  76895. /**
  76896. * Set the motor values.
  76897. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76898. * @param {number} force the force to apply
  76899. * @param {number} maxForce max force for this motor.
  76900. * @param {motorIndex} the motor's index, 0 or 1.
  76901. */
  76902. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76903. if (motorIndex === void 0) { motorIndex = 0; }
  76904. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76905. };
  76906. /**
  76907. * Set the motor limits.
  76908. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76909. * @param {number} upperLimit the upper limit
  76910. * @param {number} lowerLimit lower limit
  76911. * @param {motorIndex} the motor's index, 0 or 1.
  76912. */
  76913. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76914. if (motorIndex === void 0) { motorIndex = 0; }
  76915. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76916. };
  76917. return Hinge2Joint;
  76918. }(MotorEnabledJoint));
  76919. BABYLON.Hinge2Joint = Hinge2Joint;
  76920. })(BABYLON || (BABYLON = {}));
  76921. //# sourceMappingURL=babylon.physicsJoint.js.map
  76922. "use strict";
  76923. var BABYLON;
  76924. (function (BABYLON) {
  76925. var PhysicsImpostor = /** @class */ (function () {
  76926. function PhysicsImpostor(object, type, _options, _scene) {
  76927. if (_options === void 0) { _options = { mass: 0 }; }
  76928. var _this = this;
  76929. this.object = object;
  76930. this.type = type;
  76931. this._options = _options;
  76932. this._scene = _scene;
  76933. this._bodyUpdateRequired = false;
  76934. this._onBeforePhysicsStepCallbacks = new Array();
  76935. this._onAfterPhysicsStepCallbacks = new Array();
  76936. this._onPhysicsCollideCallbacks = [];
  76937. this._deltaPosition = BABYLON.Vector3.Zero();
  76938. this._isDisposed = false;
  76939. //temp variables for parent rotation calculations
  76940. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76941. this._tmpQuat = new BABYLON.Quaternion();
  76942. this._tmpQuat2 = new BABYLON.Quaternion();
  76943. /**
  76944. * this function is executed by the physics engine.
  76945. */
  76946. this.beforeStep = function () {
  76947. if (!_this._physicsEngine) {
  76948. return;
  76949. }
  76950. _this.object.translate(_this._deltaPosition, -1);
  76951. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76952. _this.object.computeWorldMatrix(false);
  76953. if (_this.object.parent && _this.object.rotationQuaternion) {
  76954. _this.getParentsRotation();
  76955. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76956. }
  76957. else {
  76958. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76959. }
  76960. if (!_this._options.disableBidirectionalTransformation) {
  76961. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76962. }
  76963. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76964. func(_this);
  76965. });
  76966. };
  76967. /**
  76968. * this function is executed by the physics engine.
  76969. */
  76970. this.afterStep = function () {
  76971. if (!_this._physicsEngine) {
  76972. return;
  76973. }
  76974. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76975. func(_this);
  76976. });
  76977. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76978. // object has now its world rotation. needs to be converted to local.
  76979. if (_this.object.parent && _this.object.rotationQuaternion) {
  76980. _this.getParentsRotation();
  76981. _this._tmpQuat.conjugateInPlace();
  76982. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76983. }
  76984. // take the position set and make it the absolute position of this object.
  76985. _this.object.setAbsolutePosition(_this.object.position);
  76986. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76987. _this.object.translate(_this._deltaPosition, 1);
  76988. };
  76989. /**
  76990. * Legacy collision detection event support
  76991. */
  76992. this.onCollideEvent = null;
  76993. //event and body object due to cannon's event-based architecture.
  76994. this.onCollide = function (e) {
  76995. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76996. return;
  76997. }
  76998. if (!_this._physicsEngine) {
  76999. return;
  77000. }
  77001. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77002. if (otherImpostor) {
  77003. // Legacy collision detection event support
  77004. if (_this.onCollideEvent) {
  77005. _this.onCollideEvent(_this, otherImpostor);
  77006. }
  77007. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77008. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77009. }).forEach(function (obj) {
  77010. obj.callback(_this, otherImpostor);
  77011. });
  77012. }
  77013. };
  77014. //sanity check!
  77015. if (!this.object) {
  77016. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77017. return;
  77018. }
  77019. //legacy support for old syntax.
  77020. if (!this._scene && object.getScene) {
  77021. this._scene = object.getScene();
  77022. }
  77023. if (!this._scene) {
  77024. return;
  77025. }
  77026. this._physicsEngine = this._scene.getPhysicsEngine();
  77027. if (!this._physicsEngine) {
  77028. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77029. }
  77030. else {
  77031. //set the object's quaternion, if not set
  77032. if (!this.object.rotationQuaternion) {
  77033. if (this.object.rotation) {
  77034. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77035. }
  77036. else {
  77037. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77038. }
  77039. }
  77040. //default options params
  77041. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77042. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77043. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77044. this._joints = [];
  77045. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77046. if (!this.object.parent || this._options.ignoreParent) {
  77047. this._init();
  77048. }
  77049. else if (this.object.parent.physicsImpostor) {
  77050. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77051. }
  77052. }
  77053. }
  77054. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77055. get: function () {
  77056. return this._isDisposed;
  77057. },
  77058. enumerable: true,
  77059. configurable: true
  77060. });
  77061. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77062. get: function () {
  77063. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77064. },
  77065. set: function (value) {
  77066. this.setMass(value);
  77067. },
  77068. enumerable: true,
  77069. configurable: true
  77070. });
  77071. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77072. get: function () {
  77073. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77074. },
  77075. set: function (value) {
  77076. if (!this._physicsEngine) {
  77077. return;
  77078. }
  77079. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77080. },
  77081. enumerable: true,
  77082. configurable: true
  77083. });
  77084. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77085. get: function () {
  77086. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77087. },
  77088. set: function (value) {
  77089. if (!this._physicsEngine) {
  77090. return;
  77091. }
  77092. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77093. },
  77094. enumerable: true,
  77095. configurable: true
  77096. });
  77097. /**
  77098. * This function will completly initialize this impostor.
  77099. * It will create a new body - but only if this mesh has no parent.
  77100. * If it has, this impostor will not be used other than to define the impostor
  77101. * of the child mesh.
  77102. */
  77103. PhysicsImpostor.prototype._init = function () {
  77104. if (!this._physicsEngine) {
  77105. return;
  77106. }
  77107. this._physicsEngine.removeImpostor(this);
  77108. this.physicsBody = null;
  77109. this._parent = this._parent || this._getPhysicsParent();
  77110. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77111. this._physicsEngine.addImpostor(this);
  77112. }
  77113. };
  77114. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77115. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77116. var parentMesh = this.object.parent;
  77117. return parentMesh.physicsImpostor;
  77118. }
  77119. return null;
  77120. };
  77121. /**
  77122. * Should a new body be generated.
  77123. */
  77124. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77125. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77126. };
  77127. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77128. this.forceUpdate();
  77129. };
  77130. /**
  77131. * Force a regeneration of this or the parent's impostor's body.
  77132. * Use under cautious - This will remove all joints already implemented.
  77133. */
  77134. PhysicsImpostor.prototype.forceUpdate = function () {
  77135. this._init();
  77136. if (this.parent && !this._options.ignoreParent) {
  77137. this.parent.forceUpdate();
  77138. }
  77139. };
  77140. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77141. /*public get mesh(): AbstractMesh {
  77142. return this._mesh;
  77143. }*/
  77144. /**
  77145. * Gets the body that holds this impostor. Either its own, or its parent.
  77146. */
  77147. get: function () {
  77148. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77149. },
  77150. /**
  77151. * Set the physics body. Used mainly by the physics engine/plugin
  77152. */
  77153. set: function (physicsBody) {
  77154. if (this._physicsBody && this._physicsEngine) {
  77155. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77156. }
  77157. this._physicsBody = physicsBody;
  77158. this.resetUpdateFlags();
  77159. },
  77160. enumerable: true,
  77161. configurable: true
  77162. });
  77163. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77164. get: function () {
  77165. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77166. },
  77167. set: function (value) {
  77168. this._parent = value;
  77169. },
  77170. enumerable: true,
  77171. configurable: true
  77172. });
  77173. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77174. this._bodyUpdateRequired = false;
  77175. };
  77176. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77177. if (this.object.getBoundingInfo) {
  77178. var q = this.object.rotationQuaternion;
  77179. //reset rotation
  77180. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77181. //calculate the world matrix with no rotation
  77182. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77183. var boundingInfo = this.object.getBoundingInfo();
  77184. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77185. //bring back the rotation
  77186. this.object.rotationQuaternion = q;
  77187. //calculate the world matrix with the new rotation
  77188. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77189. return size;
  77190. }
  77191. else {
  77192. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77193. }
  77194. };
  77195. PhysicsImpostor.prototype.getObjectCenter = function () {
  77196. if (this.object.getBoundingInfo) {
  77197. var boundingInfo = this.object.getBoundingInfo();
  77198. return boundingInfo.boundingBox.centerWorld;
  77199. }
  77200. else {
  77201. return this.object.position;
  77202. }
  77203. };
  77204. /**
  77205. * Get a specific parametes from the options parameter.
  77206. */
  77207. PhysicsImpostor.prototype.getParam = function (paramName) {
  77208. return this._options[paramName];
  77209. };
  77210. /**
  77211. * Sets a specific parameter in the options given to the physics plugin
  77212. */
  77213. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77214. this._options[paramName] = value;
  77215. this._bodyUpdateRequired = true;
  77216. };
  77217. /**
  77218. * Specifically change the body's mass option. Won't recreate the physics body object
  77219. */
  77220. PhysicsImpostor.prototype.setMass = function (mass) {
  77221. if (this.getParam("mass") !== mass) {
  77222. this.setParam("mass", mass);
  77223. }
  77224. if (this._physicsEngine) {
  77225. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77226. }
  77227. };
  77228. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77229. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77230. };
  77231. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77232. if (this._physicsEngine) {
  77233. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77234. }
  77235. };
  77236. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77237. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77238. };
  77239. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77240. if (this._physicsEngine) {
  77241. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77242. }
  77243. };
  77244. /**
  77245. * Execute a function with the physics plugin native code.
  77246. * Provide a function the will have two variables - the world object and the physics body object.
  77247. */
  77248. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77249. if (this._physicsEngine) {
  77250. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77251. }
  77252. };
  77253. /**
  77254. * Register a function that will be executed before the physics world is stepping forward.
  77255. */
  77256. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77257. this._onBeforePhysicsStepCallbacks.push(func);
  77258. };
  77259. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77260. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77261. if (index > -1) {
  77262. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77263. }
  77264. else {
  77265. BABYLON.Tools.Warn("Function to remove was not found");
  77266. }
  77267. };
  77268. /**
  77269. * Register a function that will be executed after the physics step
  77270. */
  77271. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77272. this._onAfterPhysicsStepCallbacks.push(func);
  77273. };
  77274. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77275. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77276. if (index > -1) {
  77277. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77278. }
  77279. else {
  77280. BABYLON.Tools.Warn("Function to remove was not found");
  77281. }
  77282. };
  77283. /**
  77284. * register a function that will be executed when this impostor collides against a different body.
  77285. */
  77286. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77287. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77288. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77289. };
  77290. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77291. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77292. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77293. if (index > -1) {
  77294. this._onPhysicsCollideCallbacks.splice(index, 1);
  77295. }
  77296. else {
  77297. BABYLON.Tools.Warn("Function to remove was not found");
  77298. }
  77299. };
  77300. PhysicsImpostor.prototype.getParentsRotation = function () {
  77301. var parent = this.object.parent;
  77302. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77303. while (parent) {
  77304. if (parent.rotationQuaternion) {
  77305. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77306. }
  77307. else {
  77308. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77309. }
  77310. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77311. parent = parent.parent;
  77312. }
  77313. return this._tmpQuat;
  77314. };
  77315. /**
  77316. * Apply a force
  77317. */
  77318. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77319. if (this._physicsEngine) {
  77320. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77321. }
  77322. return this;
  77323. };
  77324. /**
  77325. * Apply an impulse
  77326. */
  77327. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77328. if (this._physicsEngine) {
  77329. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77330. }
  77331. return this;
  77332. };
  77333. /**
  77334. * A help function to create a joint.
  77335. */
  77336. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77337. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77338. this.addJoint(otherImpostor, joint);
  77339. return this;
  77340. };
  77341. /**
  77342. * Add a joint to this impostor with a different impostor.
  77343. */
  77344. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77345. this._joints.push({
  77346. otherImpostor: otherImpostor,
  77347. joint: joint
  77348. });
  77349. if (this._physicsEngine) {
  77350. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77351. }
  77352. return this;
  77353. };
  77354. /**
  77355. * Will keep this body still, in a sleep mode.
  77356. */
  77357. PhysicsImpostor.prototype.sleep = function () {
  77358. if (this._physicsEngine) {
  77359. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77360. }
  77361. return this;
  77362. };
  77363. /**
  77364. * Wake the body up.
  77365. */
  77366. PhysicsImpostor.prototype.wakeUp = function () {
  77367. if (this._physicsEngine) {
  77368. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77369. }
  77370. return this;
  77371. };
  77372. PhysicsImpostor.prototype.clone = function (newObject) {
  77373. if (!newObject)
  77374. return null;
  77375. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77376. };
  77377. PhysicsImpostor.prototype.dispose = function () {
  77378. var _this = this;
  77379. //no dispose if no physics engine is available.
  77380. if (!this._physicsEngine) {
  77381. return;
  77382. }
  77383. this._joints.forEach(function (j) {
  77384. if (_this._physicsEngine) {
  77385. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77386. }
  77387. });
  77388. //dispose the physics body
  77389. this._physicsEngine.removeImpostor(this);
  77390. if (this.parent) {
  77391. this.parent.forceUpdate();
  77392. }
  77393. else {
  77394. /*this._object.getChildMeshes().forEach(function(mesh) {
  77395. if (mesh.physicsImpostor) {
  77396. if (disposeChildren) {
  77397. mesh.physicsImpostor.dispose();
  77398. mesh.physicsImpostor = null;
  77399. }
  77400. }
  77401. })*/
  77402. }
  77403. this._isDisposed = true;
  77404. };
  77405. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77406. this._deltaPosition.copyFrom(position);
  77407. };
  77408. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77409. if (!this._deltaRotation) {
  77410. this._deltaRotation = new BABYLON.Quaternion();
  77411. }
  77412. this._deltaRotation.copyFrom(rotation);
  77413. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77414. };
  77415. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77416. if (this._physicsEngine) {
  77417. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77418. }
  77419. return this;
  77420. };
  77421. PhysicsImpostor.prototype.getRadius = function () {
  77422. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77423. };
  77424. /**
  77425. * Sync a bone with this impostor
  77426. * @param bone The bone to sync to the impostor.
  77427. * @param boneMesh The mesh that the bone is influencing.
  77428. * @param jointPivot The pivot of the joint / bone in local space.
  77429. * @param distToJoint Optional distance from the impostor to the joint.
  77430. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77431. */
  77432. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77433. var tempVec = PhysicsImpostor._tmpVecs[0];
  77434. var mesh = this.object;
  77435. if (mesh.rotationQuaternion) {
  77436. if (adjustRotation) {
  77437. var tempQuat = PhysicsImpostor._tmpQuat;
  77438. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77439. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77440. }
  77441. else {
  77442. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77443. }
  77444. }
  77445. tempVec.x = 0;
  77446. tempVec.y = 0;
  77447. tempVec.z = 0;
  77448. if (jointPivot) {
  77449. tempVec.x = jointPivot.x;
  77450. tempVec.y = jointPivot.y;
  77451. tempVec.z = jointPivot.z;
  77452. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77453. if (distToJoint === undefined || distToJoint === null) {
  77454. distToJoint = jointPivot.length();
  77455. }
  77456. tempVec.x *= distToJoint;
  77457. tempVec.y *= distToJoint;
  77458. tempVec.z *= distToJoint;
  77459. }
  77460. if (bone.getParent()) {
  77461. tempVec.addInPlace(mesh.getAbsolutePosition());
  77462. bone.setAbsolutePosition(tempVec, boneMesh);
  77463. }
  77464. else {
  77465. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77466. boneMesh.position.x -= tempVec.x;
  77467. boneMesh.position.y -= tempVec.y;
  77468. boneMesh.position.z -= tempVec.z;
  77469. }
  77470. };
  77471. /**
  77472. * Sync impostor to a bone
  77473. * @param bone The bone that the impostor will be synced to.
  77474. * @param boneMesh The mesh that the bone is influencing.
  77475. * @param jointPivot The pivot of the joint / bone in local space.
  77476. * @param distToJoint Optional distance from the impostor to the joint.
  77477. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77478. * @param boneAxis Optional vector3 axis the bone is aligned with
  77479. */
  77480. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77481. var mesh = this.object;
  77482. if (mesh.rotationQuaternion) {
  77483. if (adjustRotation) {
  77484. var tempQuat = PhysicsImpostor._tmpQuat;
  77485. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77486. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77487. }
  77488. else {
  77489. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77490. }
  77491. }
  77492. var pos = PhysicsImpostor._tmpVecs[0];
  77493. var boneDir = PhysicsImpostor._tmpVecs[1];
  77494. if (!boneAxis) {
  77495. boneAxis = PhysicsImpostor._tmpVecs[2];
  77496. boneAxis.x = 0;
  77497. boneAxis.y = 1;
  77498. boneAxis.z = 0;
  77499. }
  77500. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77501. bone.getAbsolutePositionToRef(boneMesh, pos);
  77502. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77503. distToJoint = jointPivot.length();
  77504. }
  77505. if (distToJoint !== undefined && distToJoint !== null) {
  77506. pos.x += boneDir.x * distToJoint;
  77507. pos.y += boneDir.y * distToJoint;
  77508. pos.z += boneDir.z * distToJoint;
  77509. }
  77510. mesh.setAbsolutePosition(pos);
  77511. };
  77512. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77513. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77514. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77515. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77516. //Impostor types
  77517. PhysicsImpostor.NoImpostor = 0;
  77518. PhysicsImpostor.SphereImpostor = 1;
  77519. PhysicsImpostor.BoxImpostor = 2;
  77520. PhysicsImpostor.PlaneImpostor = 3;
  77521. PhysicsImpostor.MeshImpostor = 4;
  77522. PhysicsImpostor.CylinderImpostor = 7;
  77523. PhysicsImpostor.ParticleImpostor = 8;
  77524. PhysicsImpostor.HeightmapImpostor = 9;
  77525. return PhysicsImpostor;
  77526. }());
  77527. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77528. })(BABYLON || (BABYLON = {}));
  77529. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77530. "use strict";
  77531. var BABYLON;
  77532. (function (BABYLON) {
  77533. var PhysicsEngine = /** @class */ (function () {
  77534. function PhysicsEngine(gravity, _physicsPlugin) {
  77535. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77536. this._physicsPlugin = _physicsPlugin;
  77537. //new methods and parameters
  77538. this._impostors = [];
  77539. this._joints = [];
  77540. if (!this._physicsPlugin.isSupported()) {
  77541. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77542. + "Please make sure it is included.");
  77543. }
  77544. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77545. this.setGravity(gravity);
  77546. this.setTimeStep();
  77547. }
  77548. PhysicsEngine.prototype.setGravity = function (gravity) {
  77549. this.gravity = gravity;
  77550. this._physicsPlugin.setGravity(this.gravity);
  77551. };
  77552. /**
  77553. * Set the time step of the physics engine.
  77554. * default is 1/60.
  77555. * To slow it down, enter 1/600 for example.
  77556. * To speed it up, 1/30
  77557. * @param {number} newTimeStep the new timestep to apply to this world.
  77558. */
  77559. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77560. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77561. this._physicsPlugin.setTimeStep(newTimeStep);
  77562. };
  77563. /**
  77564. * Get the time step of the physics engine.
  77565. */
  77566. PhysicsEngine.prototype.getTimeStep = function () {
  77567. return this._physicsPlugin.getTimeStep();
  77568. };
  77569. PhysicsEngine.prototype.dispose = function () {
  77570. this._impostors.forEach(function (impostor) {
  77571. impostor.dispose();
  77572. });
  77573. this._physicsPlugin.dispose();
  77574. };
  77575. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77576. return this._physicsPlugin.name;
  77577. };
  77578. /**
  77579. * Adding a new impostor for the impostor tracking.
  77580. * This will be done by the impostor itself.
  77581. * @param {PhysicsImpostor} impostor the impostor to add
  77582. */
  77583. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77584. impostor.uniqueId = this._impostors.push(impostor);
  77585. //if no parent, generate the body
  77586. if (!impostor.parent) {
  77587. this._physicsPlugin.generatePhysicsBody(impostor);
  77588. }
  77589. };
  77590. /**
  77591. * Remove an impostor from the engine.
  77592. * This impostor and its mesh will not longer be updated by the physics engine.
  77593. * @param {PhysicsImpostor} impostor the impostor to remove
  77594. */
  77595. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77596. var index = this._impostors.indexOf(impostor);
  77597. if (index > -1) {
  77598. var removed = this._impostors.splice(index, 1);
  77599. //Is it needed?
  77600. if (removed.length) {
  77601. //this will also remove it from the world.
  77602. removed[0].physicsBody = null;
  77603. }
  77604. }
  77605. };
  77606. /**
  77607. * Add a joint to the physics engine
  77608. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77609. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77610. * @param {PhysicsJoint} the joint that will connect both impostors.
  77611. */
  77612. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77613. var impostorJoint = {
  77614. mainImpostor: mainImpostor,
  77615. connectedImpostor: connectedImpostor,
  77616. joint: joint
  77617. };
  77618. joint.physicsPlugin = this._physicsPlugin;
  77619. this._joints.push(impostorJoint);
  77620. this._physicsPlugin.generateJoint(impostorJoint);
  77621. };
  77622. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77623. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77624. return (impostorJoint.connectedImpostor === connectedImpostor
  77625. && impostorJoint.joint === joint
  77626. && impostorJoint.mainImpostor === mainImpostor);
  77627. });
  77628. if (matchingJoints.length) {
  77629. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77630. //TODO remove it from the list as well
  77631. }
  77632. };
  77633. /**
  77634. * Called by the scene. no need to call it.
  77635. */
  77636. PhysicsEngine.prototype._step = function (delta) {
  77637. var _this = this;
  77638. //check if any mesh has no body / requires an update
  77639. this._impostors.forEach(function (impostor) {
  77640. if (impostor.isBodyInitRequired()) {
  77641. _this._physicsPlugin.generatePhysicsBody(impostor);
  77642. }
  77643. });
  77644. if (delta > 0.1) {
  77645. delta = 0.1;
  77646. }
  77647. else if (delta <= 0) {
  77648. delta = 1.0 / 60.0;
  77649. }
  77650. this._physicsPlugin.executeStep(delta, this._impostors);
  77651. };
  77652. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77653. return this._physicsPlugin;
  77654. };
  77655. PhysicsEngine.prototype.getImpostors = function () {
  77656. return this._impostors;
  77657. };
  77658. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77659. for (var i = 0; i < this._impostors.length; ++i) {
  77660. if (this._impostors[i].object === object) {
  77661. return this._impostors[i];
  77662. }
  77663. }
  77664. return null;
  77665. };
  77666. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77667. for (var i = 0; i < this._impostors.length; ++i) {
  77668. if (this._impostors[i].physicsBody === body) {
  77669. return this._impostors[i];
  77670. }
  77671. }
  77672. return null;
  77673. };
  77674. // Statics
  77675. PhysicsEngine.Epsilon = 0.001;
  77676. return PhysicsEngine;
  77677. }());
  77678. BABYLON.PhysicsEngine = PhysicsEngine;
  77679. })(BABYLON || (BABYLON = {}));
  77680. //# sourceMappingURL=babylon.physicsEngine.js.map
  77681. "use strict";
  77682. var BABYLON;
  77683. (function (BABYLON) {
  77684. var PhysicsHelper = /** @class */ (function () {
  77685. function PhysicsHelper(scene) {
  77686. this._scene = scene;
  77687. this._physicsEngine = this._scene.getPhysicsEngine();
  77688. if (!this._physicsEngine) {
  77689. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77690. }
  77691. }
  77692. /**
  77693. * @param {Vector3} origin the origin of the explosion
  77694. * @param {number} radius the explosion radius
  77695. * @param {number} strength the explosion strength
  77696. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77697. */
  77698. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77699. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77700. if (!this._physicsEngine) {
  77701. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77702. return null;
  77703. }
  77704. var impostors = this._physicsEngine.getImpostors();
  77705. if (impostors.length === 0) {
  77706. return null;
  77707. }
  77708. var event = new PhysicsRadialExplosionEvent(this._scene);
  77709. impostors.forEach(function (impostor) {
  77710. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77711. if (!impostorForceAndContactPoint) {
  77712. return;
  77713. }
  77714. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77715. });
  77716. event.dispose(false);
  77717. return event;
  77718. };
  77719. /**
  77720. * @param {Vector3} origin the origin of the explosion
  77721. * @param {number} radius the explosion radius
  77722. * @param {number} strength the explosion strength
  77723. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77724. */
  77725. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77726. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77727. if (!this._physicsEngine) {
  77728. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77729. return null;
  77730. }
  77731. var impostors = this._physicsEngine.getImpostors();
  77732. if (impostors.length === 0) {
  77733. return null;
  77734. }
  77735. var event = new PhysicsRadialExplosionEvent(this._scene);
  77736. impostors.forEach(function (impostor) {
  77737. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77738. if (!impostorForceAndContactPoint) {
  77739. return;
  77740. }
  77741. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77742. });
  77743. event.dispose(false);
  77744. return event;
  77745. };
  77746. /**
  77747. * @param {Vector3} origin the origin of the explosion
  77748. * @param {number} radius the explosion radius
  77749. * @param {number} strength the explosion strength
  77750. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77751. */
  77752. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77753. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77754. if (!this._physicsEngine) {
  77755. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77756. return null;
  77757. }
  77758. var impostors = this._physicsEngine.getImpostors();
  77759. if (impostors.length === 0) {
  77760. return null;
  77761. }
  77762. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77763. event.dispose(false);
  77764. return event;
  77765. };
  77766. /**
  77767. * @param {Vector3} origin the origin of the updraft
  77768. * @param {number} radius the radius of the updraft
  77769. * @param {number} strength the strength of the updraft
  77770. * @param {number} height the height of the updraft
  77771. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77772. */
  77773. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77774. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77775. if (!this._physicsEngine) {
  77776. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77777. return null;
  77778. }
  77779. if (this._physicsEngine.getImpostors().length === 0) {
  77780. return null;
  77781. }
  77782. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77783. event.dispose(false);
  77784. return event;
  77785. };
  77786. /**
  77787. * @param {Vector3} origin the of the vortex
  77788. * @param {number} radius the radius of the vortex
  77789. * @param {number} strength the strength of the vortex
  77790. * @param {number} height the height of the vortex
  77791. */
  77792. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77793. if (!this._physicsEngine) {
  77794. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77795. return null;
  77796. }
  77797. if (this._physicsEngine.getImpostors().length === 0) {
  77798. return null;
  77799. }
  77800. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77801. event.dispose(false);
  77802. return event;
  77803. };
  77804. return PhysicsHelper;
  77805. }());
  77806. BABYLON.PhysicsHelper = PhysicsHelper;
  77807. /***** Radial explosion *****/
  77808. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77809. function PhysicsRadialExplosionEvent(scene) {
  77810. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77811. this._rays = [];
  77812. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77813. this._scene = scene;
  77814. }
  77815. /**
  77816. * Returns the data related to the radial explosion event (sphere & rays).
  77817. * @returns {PhysicsRadialExplosionEventData}
  77818. */
  77819. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77820. this._dataFetched = true;
  77821. return {
  77822. sphere: this._sphere,
  77823. rays: this._rays,
  77824. };
  77825. };
  77826. /**
  77827. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77828. * @param impostor
  77829. * @param {Vector3} origin the origin of the explosion
  77830. * @param {number} radius the explosion radius
  77831. * @param {number} strength the explosion strength
  77832. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77833. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77834. */
  77835. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77836. if (impostor.mass === 0) {
  77837. return null;
  77838. }
  77839. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77840. return null;
  77841. }
  77842. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  77843. return null;
  77844. }
  77845. var impostorObjectCenter = impostor.getObjectCenter();
  77846. var direction = impostorObjectCenter.subtract(origin);
  77847. var ray = new BABYLON.Ray(origin, direction, radius);
  77848. this._rays.push(ray);
  77849. var hit = ray.intersectsMesh(impostor.object);
  77850. var contactPoint = hit.pickedPoint;
  77851. if (!contactPoint) {
  77852. return null;
  77853. }
  77854. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77855. if (distanceFromOrigin > radius) {
  77856. return null;
  77857. }
  77858. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77859. ? strength
  77860. : strength * (1 - (distanceFromOrigin / radius));
  77861. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77862. return { force: force, contactPoint: contactPoint };
  77863. };
  77864. /**
  77865. * Disposes the sphere.
  77866. * @param {bolean} force
  77867. */
  77868. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77869. var _this = this;
  77870. if (force === void 0) { force = true; }
  77871. if (force) {
  77872. this._sphere.dispose();
  77873. }
  77874. else {
  77875. setTimeout(function () {
  77876. if (!_this._dataFetched) {
  77877. _this._sphere.dispose();
  77878. }
  77879. }, 0);
  77880. }
  77881. };
  77882. /*** Helpers ***/
  77883. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77884. if (!this._sphere) {
  77885. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77886. this._sphere.isVisible = false;
  77887. }
  77888. };
  77889. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77890. var impostorObject = impostor.object;
  77891. this._prepareSphere();
  77892. this._sphere.position = origin;
  77893. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77894. this._sphere._updateBoundingInfo();
  77895. this._sphere.computeWorldMatrix(true);
  77896. return this._sphere.intersectsMesh(impostorObject, true);
  77897. };
  77898. return PhysicsRadialExplosionEvent;
  77899. }());
  77900. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77901. /***** Gravitational Field *****/
  77902. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77903. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77904. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77905. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77906. this._physicsHelper = physicsHelper;
  77907. this._scene = scene;
  77908. this._origin = origin;
  77909. this._radius = radius;
  77910. this._strength = strength;
  77911. this._falloff = falloff;
  77912. this._tickCallback = this._tick.bind(this);
  77913. }
  77914. /**
  77915. * Returns the data related to the gravitational field event (sphere).
  77916. * @returns {PhysicsGravitationalFieldEventData}
  77917. */
  77918. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77919. this._dataFetched = true;
  77920. return {
  77921. sphere: this._sphere,
  77922. };
  77923. };
  77924. /**
  77925. * Enables the gravitational field.
  77926. */
  77927. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77928. this._tickCallback.call(this);
  77929. this._scene.registerBeforeRender(this._tickCallback);
  77930. };
  77931. /**
  77932. * Disables the gravitational field.
  77933. */
  77934. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77935. this._scene.unregisterBeforeRender(this._tickCallback);
  77936. };
  77937. /**
  77938. * Disposes the sphere.
  77939. * @param {bolean} force
  77940. */
  77941. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77942. var _this = this;
  77943. if (force === void 0) { force = true; }
  77944. if (force) {
  77945. this._sphere.dispose();
  77946. }
  77947. else {
  77948. setTimeout(function () {
  77949. if (!_this._dataFetched) {
  77950. _this._sphere.dispose();
  77951. }
  77952. }, 0);
  77953. }
  77954. };
  77955. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77956. // Since the params won't change, we fetch the event only once
  77957. if (this._sphere) {
  77958. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77959. }
  77960. else {
  77961. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77962. if (radialExplosionEvent) {
  77963. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77964. }
  77965. }
  77966. };
  77967. return PhysicsGravitationalFieldEvent;
  77968. }());
  77969. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77970. /***** Updraft *****/
  77971. var PhysicsUpdraftEvent = /** @class */ (function () {
  77972. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77973. this._scene = _scene;
  77974. this._origin = _origin;
  77975. this._radius = _radius;
  77976. this._strength = _strength;
  77977. this._height = _height;
  77978. this._updraftMode = _updraftMode;
  77979. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77980. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77981. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77982. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77983. this._physicsEngine = this._scene.getPhysicsEngine();
  77984. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77985. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77986. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77987. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77988. }
  77989. this._tickCallback = this._tick.bind(this);
  77990. }
  77991. /**
  77992. * Returns the data related to the updraft event (cylinder).
  77993. * @returns {PhysicsUpdraftEventData}
  77994. */
  77995. PhysicsUpdraftEvent.prototype.getData = function () {
  77996. this._dataFetched = true;
  77997. return {
  77998. cylinder: this._cylinder,
  77999. };
  78000. };
  78001. /**
  78002. * Enables the updraft.
  78003. */
  78004. PhysicsUpdraftEvent.prototype.enable = function () {
  78005. this._tickCallback.call(this);
  78006. this._scene.registerBeforeRender(this._tickCallback);
  78007. };
  78008. /**
  78009. * Disables the cortex.
  78010. */
  78011. PhysicsUpdraftEvent.prototype.disable = function () {
  78012. this._scene.unregisterBeforeRender(this._tickCallback);
  78013. };
  78014. /**
  78015. * Disposes the sphere.
  78016. * @param {bolean} force
  78017. */
  78018. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78019. var _this = this;
  78020. if (force === void 0) { force = true; }
  78021. if (force) {
  78022. this._cylinder.dispose();
  78023. }
  78024. else {
  78025. setTimeout(function () {
  78026. if (!_this._dataFetched) {
  78027. _this._cylinder.dispose();
  78028. }
  78029. }, 0);
  78030. }
  78031. };
  78032. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78033. if (impostor.mass === 0) {
  78034. return null;
  78035. }
  78036. if (!this._intersectsWithCylinder(impostor)) {
  78037. return null;
  78038. }
  78039. var impostorObjectCenter = impostor.getObjectCenter();
  78040. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78041. var direction = this._originDirection;
  78042. }
  78043. else {
  78044. var direction = impostorObjectCenter.subtract(this._originTop);
  78045. }
  78046. var multiplier = this._strength * -1;
  78047. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78048. return { force: force, contactPoint: impostorObjectCenter };
  78049. };
  78050. PhysicsUpdraftEvent.prototype._tick = function () {
  78051. var _this = this;
  78052. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78053. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78054. if (!impostorForceAndContactPoint) {
  78055. return;
  78056. }
  78057. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78058. });
  78059. };
  78060. /*** Helpers ***/
  78061. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78062. if (!this._cylinder) {
  78063. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78064. height: this._height,
  78065. diameter: this._radius * 2,
  78066. }, this._scene);
  78067. this._cylinder.isVisible = false;
  78068. }
  78069. };
  78070. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78071. var impostorObject = impostor.object;
  78072. this._prepareCylinder();
  78073. this._cylinder.position = this._cylinderPosition;
  78074. return this._cylinder.intersectsMesh(impostorObject, true);
  78075. };
  78076. return PhysicsUpdraftEvent;
  78077. }());
  78078. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78079. /***** Vortex *****/
  78080. var PhysicsVortexEvent = /** @class */ (function () {
  78081. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78082. this._scene = _scene;
  78083. this._origin = _origin;
  78084. this._radius = _radius;
  78085. this._strength = _strength;
  78086. this._height = _height;
  78087. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78088. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78089. this._updraftMultiplier = 0.02;
  78090. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78091. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78092. this._physicsEngine = this._scene.getPhysicsEngine();
  78093. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78094. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78095. this._tickCallback = this._tick.bind(this);
  78096. }
  78097. /**
  78098. * Returns the data related to the vortex event (cylinder).
  78099. * @returns {PhysicsVortexEventData}
  78100. */
  78101. PhysicsVortexEvent.prototype.getData = function () {
  78102. this._dataFetched = true;
  78103. return {
  78104. cylinder: this._cylinder,
  78105. };
  78106. };
  78107. /**
  78108. * Enables the vortex.
  78109. */
  78110. PhysicsVortexEvent.prototype.enable = function () {
  78111. this._tickCallback.call(this);
  78112. this._scene.registerBeforeRender(this._tickCallback);
  78113. };
  78114. /**
  78115. * Disables the cortex.
  78116. */
  78117. PhysicsVortexEvent.prototype.disable = function () {
  78118. this._scene.unregisterBeforeRender(this._tickCallback);
  78119. };
  78120. /**
  78121. * Disposes the sphere.
  78122. * @param {bolean} force
  78123. */
  78124. PhysicsVortexEvent.prototype.dispose = function (force) {
  78125. var _this = this;
  78126. if (force === void 0) { force = true; }
  78127. if (force) {
  78128. this._cylinder.dispose();
  78129. }
  78130. else {
  78131. setTimeout(function () {
  78132. if (!_this._dataFetched) {
  78133. _this._cylinder.dispose();
  78134. }
  78135. }, 0);
  78136. }
  78137. };
  78138. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78139. if (impostor.mass === 0) {
  78140. return null;
  78141. }
  78142. if (!this._intersectsWithCylinder(impostor)) {
  78143. return null;
  78144. }
  78145. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78146. return null;
  78147. }
  78148. var impostorObjectCenter = impostor.getObjectCenter();
  78149. 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)
  78150. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78151. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78152. var hit = ray.intersectsMesh(impostor.object);
  78153. var contactPoint = hit.pickedPoint;
  78154. if (!contactPoint) {
  78155. return null;
  78156. }
  78157. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78158. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78159. var directionToOrigin = contactPoint.normalize();
  78160. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78161. directionToOrigin = directionToOrigin.negate();
  78162. }
  78163. // TODO: find a more physically based solution
  78164. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78165. var forceX = directionToOrigin.x * this._strength / 8;
  78166. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78167. var forceZ = directionToOrigin.z * this._strength / 8;
  78168. }
  78169. else {
  78170. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78171. var forceY = this._originTop.y * this._updraftMultiplier;
  78172. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78173. }
  78174. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78175. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78176. return { force: force, contactPoint: impostorObjectCenter };
  78177. };
  78178. PhysicsVortexEvent.prototype._tick = function () {
  78179. var _this = this;
  78180. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78181. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78182. if (!impostorForceAndContactPoint) {
  78183. return;
  78184. }
  78185. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78186. });
  78187. };
  78188. /*** Helpers ***/
  78189. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78190. if (!this._cylinder) {
  78191. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78192. height: this._height,
  78193. diameter: this._radius * 2,
  78194. }, this._scene);
  78195. this._cylinder.isVisible = false;
  78196. }
  78197. };
  78198. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78199. var impostorObject = impostor.object;
  78200. this._prepareCylinder();
  78201. this._cylinder.position = this._cylinderPosition;
  78202. return this._cylinder.intersectsMesh(impostorObject, true);
  78203. };
  78204. return PhysicsVortexEvent;
  78205. }());
  78206. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78207. /***** Enums *****/
  78208. /**
  78209. * The strenght of the force in correspondence to the distance of the affected object
  78210. */
  78211. var PhysicsRadialImpulseFalloff;
  78212. (function (PhysicsRadialImpulseFalloff) {
  78213. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78214. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78215. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78216. /**
  78217. * The strenght of the force in correspondence to the distance of the affected object
  78218. */
  78219. var PhysicsUpdraftMode;
  78220. (function (PhysicsUpdraftMode) {
  78221. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78222. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78223. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78224. })(BABYLON || (BABYLON = {}));
  78225. //# sourceMappingURL=babylon.physicsHelper.js.map
  78226. "use strict";
  78227. var BABYLON;
  78228. (function (BABYLON) {
  78229. var CannonJSPlugin = /** @class */ (function () {
  78230. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78231. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78232. if (iterations === void 0) { iterations = 10; }
  78233. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78234. this.name = "CannonJSPlugin";
  78235. this._physicsMaterials = new Array();
  78236. this._fixedTimeStep = 1 / 60;
  78237. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78238. this.BJSCANNON = CANNON;
  78239. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78240. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78241. this._tmpPosition = BABYLON.Vector3.Zero();
  78242. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78243. this._tmpUnityRotation = new BABYLON.Quaternion();
  78244. if (!this.isSupported()) {
  78245. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78246. return;
  78247. }
  78248. this._extendNamespace();
  78249. this.world = new this.BJSCANNON.World();
  78250. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78251. this.world.solver.iterations = iterations;
  78252. }
  78253. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78254. this.world.gravity.copy(gravity);
  78255. };
  78256. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78257. this._fixedTimeStep = timeStep;
  78258. };
  78259. CannonJSPlugin.prototype.getTimeStep = function () {
  78260. return this._fixedTimeStep;
  78261. };
  78262. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78263. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78264. };
  78265. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78266. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78267. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78268. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78269. };
  78270. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78271. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78272. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78273. impostor.physicsBody.applyForce(impulse, worldPoint);
  78274. };
  78275. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78276. //parent-child relationship. Does this impostor has a parent impostor?
  78277. if (impostor.parent) {
  78278. if (impostor.physicsBody) {
  78279. this.removePhysicsBody(impostor);
  78280. //TODO is that needed?
  78281. impostor.forceUpdate();
  78282. }
  78283. return;
  78284. }
  78285. //should a new body be created for this impostor?
  78286. if (impostor.isBodyInitRequired()) {
  78287. var shape = this._createShape(impostor);
  78288. //unregister events, if body is being changed
  78289. var oldBody = impostor.physicsBody;
  78290. if (oldBody) {
  78291. this.removePhysicsBody(impostor);
  78292. }
  78293. //create the body and material
  78294. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78295. var bodyCreationObject = {
  78296. mass: impostor.getParam("mass"),
  78297. material: material
  78298. };
  78299. // A simple extend, in case native options were used.
  78300. var nativeOptions = impostor.getParam("nativeOptions");
  78301. for (var key in nativeOptions) {
  78302. if (nativeOptions.hasOwnProperty(key)) {
  78303. bodyCreationObject[key] = nativeOptions[key];
  78304. }
  78305. }
  78306. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78307. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78308. this.world.addEventListener("preStep", impostor.beforeStep);
  78309. this.world.addEventListener("postStep", impostor.afterStep);
  78310. impostor.physicsBody.addShape(shape);
  78311. this.world.add(impostor.physicsBody);
  78312. //try to keep the body moving in the right direction by taking old properties.
  78313. //Should be tested!
  78314. if (oldBody) {
  78315. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78316. impostor.physicsBody[param].copy(oldBody[param]);
  78317. });
  78318. }
  78319. this._processChildMeshes(impostor);
  78320. }
  78321. //now update the body's transformation
  78322. this._updatePhysicsBodyTransformation(impostor);
  78323. };
  78324. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78325. var _this = this;
  78326. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78327. var currentRotation = mainImpostor.object.rotationQuaternion;
  78328. if (meshChildren.length) {
  78329. var processMesh = function (localPosition, mesh) {
  78330. if (!currentRotation || !mesh.rotationQuaternion) {
  78331. return;
  78332. }
  78333. var childImpostor = mesh.getPhysicsImpostor();
  78334. if (childImpostor) {
  78335. var parent = childImpostor.parent;
  78336. if (parent !== mainImpostor) {
  78337. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78338. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78339. if (childImpostor.physicsBody) {
  78340. _this.removePhysicsBody(childImpostor);
  78341. childImpostor.physicsBody = null;
  78342. }
  78343. childImpostor.parent = mainImpostor;
  78344. childImpostor.resetUpdateFlags();
  78345. 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));
  78346. //Add the mass of the children.
  78347. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78348. }
  78349. }
  78350. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78351. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78352. };
  78353. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78354. }
  78355. };
  78356. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78357. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78358. this.world.removeEventListener("preStep", impostor.beforeStep);
  78359. this.world.removeEventListener("postStep", impostor.afterStep);
  78360. this.world.remove(impostor.physicsBody);
  78361. };
  78362. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78363. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78364. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78365. if (!mainBody || !connectedBody) {
  78366. return;
  78367. }
  78368. var constraint;
  78369. var jointData = impostorJoint.joint.jointData;
  78370. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78371. var constraintData = {
  78372. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78373. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78374. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78375. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78376. maxForce: jointData.nativeParams.maxForce,
  78377. collideConnected: !!jointData.collision
  78378. };
  78379. switch (impostorJoint.joint.type) {
  78380. case BABYLON.PhysicsJoint.HingeJoint:
  78381. case BABYLON.PhysicsJoint.Hinge2Joint:
  78382. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78383. break;
  78384. case BABYLON.PhysicsJoint.DistanceJoint:
  78385. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78386. break;
  78387. case BABYLON.PhysicsJoint.SpringJoint:
  78388. var springData = jointData;
  78389. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78390. restLength: springData.length,
  78391. stiffness: springData.stiffness,
  78392. damping: springData.damping,
  78393. localAnchorA: constraintData.pivotA,
  78394. localAnchorB: constraintData.pivotB
  78395. });
  78396. break;
  78397. case BABYLON.PhysicsJoint.LockJoint:
  78398. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78399. break;
  78400. case BABYLON.PhysicsJoint.PointToPointJoint:
  78401. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78402. default:
  78403. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78404. break;
  78405. }
  78406. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78407. constraint.collideConnected = !!jointData.collision;
  78408. impostorJoint.joint.physicsJoint = constraint;
  78409. //don't add spring as constraint, as it is not one.
  78410. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78411. this.world.addConstraint(constraint);
  78412. }
  78413. else {
  78414. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78415. constraint.applyForce();
  78416. });
  78417. }
  78418. };
  78419. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78420. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78421. };
  78422. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78423. var index;
  78424. var mat;
  78425. for (index = 0; index < this._physicsMaterials.length; index++) {
  78426. mat = this._physicsMaterials[index];
  78427. if (mat.friction === friction && mat.restitution === restitution) {
  78428. return mat;
  78429. }
  78430. }
  78431. var currentMat = new this.BJSCANNON.Material(name);
  78432. currentMat.friction = friction;
  78433. currentMat.restitution = restitution;
  78434. this._physicsMaterials.push(currentMat);
  78435. return currentMat;
  78436. };
  78437. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78438. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78439. };
  78440. CannonJSPlugin.prototype._createShape = function (impostor) {
  78441. var object = impostor.object;
  78442. var returnValue;
  78443. var extendSize = impostor.getObjectExtendSize();
  78444. switch (impostor.type) {
  78445. case BABYLON.PhysicsImpostor.SphereImpostor:
  78446. var radiusX = extendSize.x;
  78447. var radiusY = extendSize.y;
  78448. var radiusZ = extendSize.z;
  78449. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78450. break;
  78451. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78452. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78453. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78454. break;
  78455. case BABYLON.PhysicsImpostor.BoxImpostor:
  78456. var box = extendSize.scale(0.5);
  78457. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78458. break;
  78459. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78460. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78461. returnValue = new this.BJSCANNON.Plane();
  78462. break;
  78463. case BABYLON.PhysicsImpostor.MeshImpostor:
  78464. // should transform the vertex data to world coordinates!!
  78465. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78466. var rawFaces = object.getIndices ? object.getIndices() : [];
  78467. if (!rawVerts)
  78468. return;
  78469. // get only scale! so the object could transform correctly.
  78470. var oldPosition = object.position.clone();
  78471. var oldRotation = object.rotation && object.rotation.clone();
  78472. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78473. object.position.copyFromFloats(0, 0, 0);
  78474. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78475. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78476. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78477. var transform = object.computeWorldMatrix(true);
  78478. // convert rawVerts to object space
  78479. var temp = new Array();
  78480. var index;
  78481. for (index = 0; index < rawVerts.length; index += 3) {
  78482. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78483. }
  78484. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78485. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78486. //now set back the transformation!
  78487. object.position.copyFrom(oldPosition);
  78488. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78489. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78490. break;
  78491. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78492. var oldPosition2 = object.position.clone();
  78493. var oldRotation2 = object.rotation && object.rotation.clone();
  78494. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78495. object.position.copyFromFloats(0, 0, 0);
  78496. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78497. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78498. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78499. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78500. returnValue = this._createHeightmap(object);
  78501. object.position.copyFrom(oldPosition2);
  78502. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78503. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78504. object.computeWorldMatrix(true);
  78505. break;
  78506. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78507. returnValue = new this.BJSCANNON.Particle();
  78508. break;
  78509. }
  78510. return returnValue;
  78511. };
  78512. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78513. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78514. var transform = object.computeWorldMatrix(true);
  78515. // convert rawVerts to object space
  78516. var temp = new Array();
  78517. var index;
  78518. for (index = 0; index < pos.length; index += 3) {
  78519. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78520. }
  78521. pos = temp;
  78522. var matrix = new Array();
  78523. //For now pointDepth will not be used and will be automatically calculated.
  78524. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78525. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78526. var boundingInfo = object.getBoundingInfo();
  78527. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78528. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78529. var elementSize = dim * 2 / arraySize;
  78530. for (var i = 0; i < pos.length; i = i + 3) {
  78531. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78532. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78533. var y = -pos[i + 2] + minY;
  78534. if (!matrix[x]) {
  78535. matrix[x] = [];
  78536. }
  78537. if (!matrix[x][z]) {
  78538. matrix[x][z] = y;
  78539. }
  78540. matrix[x][z] = Math.max(y, matrix[x][z]);
  78541. }
  78542. for (var x = 0; x <= arraySize; ++x) {
  78543. if (!matrix[x]) {
  78544. var loc = 1;
  78545. while (!matrix[(x + loc) % arraySize]) {
  78546. loc++;
  78547. }
  78548. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78549. //console.log("missing x", x);
  78550. }
  78551. for (var z = 0; z <= arraySize; ++z) {
  78552. if (!matrix[x][z]) {
  78553. var loc = 1;
  78554. var newValue;
  78555. while (newValue === undefined) {
  78556. newValue = matrix[x][(z + loc++) % arraySize];
  78557. }
  78558. matrix[x][z] = newValue;
  78559. }
  78560. }
  78561. }
  78562. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78563. elementSize: elementSize
  78564. });
  78565. //For future reference, needed for body transformation
  78566. shape.minY = minY;
  78567. return shape;
  78568. };
  78569. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78570. var object = impostor.object;
  78571. //make sure it is updated...
  78572. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78573. // The delta between the mesh position and the mesh bounding box center
  78574. var bInfo = object.getBoundingInfo();
  78575. if (!bInfo)
  78576. return;
  78577. var center = impostor.getObjectCenter();
  78578. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78579. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78580. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78581. this._tmpPosition.copyFrom(center);
  78582. var quaternion = object.rotationQuaternion;
  78583. if (!quaternion) {
  78584. return;
  78585. }
  78586. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78587. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78588. //-90 DEG in X, precalculated
  78589. quaternion = quaternion.multiply(this._minus90X);
  78590. //Invert! (Precalculated, 90 deg in X)
  78591. //No need to clone. this will never change.
  78592. impostor.setDeltaRotation(this._plus90X);
  78593. }
  78594. //If it is a heightfield, if should be centered.
  78595. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78596. var mesh = object;
  78597. var boundingInfo = mesh.getBoundingInfo();
  78598. //calculate the correct body position:
  78599. var rotationQuaternion = mesh.rotationQuaternion;
  78600. mesh.rotationQuaternion = this._tmpUnityRotation;
  78601. mesh.computeWorldMatrix(true);
  78602. //get original center with no rotation
  78603. var c = center.clone();
  78604. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78605. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78606. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78607. mesh.setPreTransformMatrix(p);
  78608. mesh.computeWorldMatrix(true);
  78609. //calculate the translation
  78610. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78611. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78612. //add it inverted to the delta
  78613. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78614. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78615. //rotation is back
  78616. mesh.rotationQuaternion = rotationQuaternion;
  78617. mesh.setPreTransformMatrix(oldPivot);
  78618. mesh.computeWorldMatrix(true);
  78619. }
  78620. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78621. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78622. //this._tmpPosition.copyFrom(object.position);
  78623. }
  78624. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78625. //Now update the impostor object
  78626. impostor.physicsBody.position.copy(this._tmpPosition);
  78627. impostor.physicsBody.quaternion.copy(quaternion);
  78628. };
  78629. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78630. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78631. if (impostor.object.rotationQuaternion) {
  78632. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78633. }
  78634. };
  78635. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78636. impostor.physicsBody.position.copy(newPosition);
  78637. impostor.physicsBody.quaternion.copy(newRotation);
  78638. };
  78639. CannonJSPlugin.prototype.isSupported = function () {
  78640. return this.BJSCANNON !== undefined;
  78641. };
  78642. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78643. impostor.physicsBody.velocity.copy(velocity);
  78644. };
  78645. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78646. impostor.physicsBody.angularVelocity.copy(velocity);
  78647. };
  78648. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78649. var v = impostor.physicsBody.velocity;
  78650. if (!v) {
  78651. return null;
  78652. }
  78653. return new BABYLON.Vector3(v.x, v.y, v.z);
  78654. };
  78655. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78656. var v = impostor.physicsBody.angularVelocity;
  78657. if (!v) {
  78658. return null;
  78659. }
  78660. return new BABYLON.Vector3(v.x, v.y, v.z);
  78661. };
  78662. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78663. impostor.physicsBody.mass = mass;
  78664. impostor.physicsBody.updateMassProperties();
  78665. };
  78666. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78667. return impostor.physicsBody.mass;
  78668. };
  78669. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78670. return impostor.physicsBody.material.friction;
  78671. };
  78672. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78673. impostor.physicsBody.material.friction = friction;
  78674. };
  78675. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78676. return impostor.physicsBody.material.restitution;
  78677. };
  78678. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78679. impostor.physicsBody.material.restitution = restitution;
  78680. };
  78681. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78682. impostor.physicsBody.sleep();
  78683. };
  78684. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78685. impostor.physicsBody.wakeUp();
  78686. };
  78687. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78688. joint.physicsJoint.distance = maxDistance;
  78689. };
  78690. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78691. // if (!motorIndex) {
  78692. // joint.physicsJoint.enableMotor();
  78693. // }
  78694. // }
  78695. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78696. // if (!motorIndex) {
  78697. // joint.physicsJoint.disableMotor();
  78698. // }
  78699. // }
  78700. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78701. if (!motorIndex) {
  78702. joint.physicsJoint.enableMotor();
  78703. joint.physicsJoint.setMotorSpeed(speed);
  78704. if (maxForce) {
  78705. this.setLimit(joint, maxForce);
  78706. }
  78707. }
  78708. };
  78709. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78710. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78711. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78712. };
  78713. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78714. var body = impostor.physicsBody;
  78715. mesh.position.x = body.position.x;
  78716. mesh.position.y = body.position.y;
  78717. mesh.position.z = body.position.z;
  78718. if (mesh.rotationQuaternion) {
  78719. mesh.rotationQuaternion.x = body.quaternion.x;
  78720. mesh.rotationQuaternion.y = body.quaternion.y;
  78721. mesh.rotationQuaternion.z = body.quaternion.z;
  78722. mesh.rotationQuaternion.w = body.quaternion.w;
  78723. }
  78724. };
  78725. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78726. var shape = impostor.physicsBody.shapes[0];
  78727. return shape.boundingSphereRadius;
  78728. };
  78729. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78730. var shape = impostor.physicsBody.shapes[0];
  78731. result.x = shape.halfExtents.x * 2;
  78732. result.y = shape.halfExtents.y * 2;
  78733. result.z = shape.halfExtents.z * 2;
  78734. };
  78735. CannonJSPlugin.prototype.dispose = function () {
  78736. };
  78737. CannonJSPlugin.prototype._extendNamespace = function () {
  78738. //this will force cannon to execute at least one step when using interpolation
  78739. var step_tmp1 = new this.BJSCANNON.Vec3();
  78740. var Engine = this.BJSCANNON;
  78741. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78742. maxSubSteps = maxSubSteps || 10;
  78743. timeSinceLastCalled = timeSinceLastCalled || 0;
  78744. if (timeSinceLastCalled === 0) {
  78745. this.internalStep(dt);
  78746. this.time += dt;
  78747. }
  78748. else {
  78749. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78750. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78751. var t0 = performance.now();
  78752. for (var i = 0; i !== internalSteps; i++) {
  78753. this.internalStep(dt);
  78754. if (performance.now() - t0 > dt * 1000) {
  78755. break;
  78756. }
  78757. }
  78758. this.time += timeSinceLastCalled;
  78759. var h = this.time % dt;
  78760. var h_div_dt = h / dt;
  78761. var interpvelo = step_tmp1;
  78762. var bodies = this.bodies;
  78763. for (var j = 0; j !== bodies.length; j++) {
  78764. var b = bodies[j];
  78765. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78766. b.position.vsub(b.previousPosition, interpvelo);
  78767. interpvelo.scale(h_div_dt, interpvelo);
  78768. b.position.vadd(interpvelo, b.interpolatedPosition);
  78769. }
  78770. else {
  78771. b.interpolatedPosition.copy(b.position);
  78772. b.interpolatedQuaternion.copy(b.quaternion);
  78773. }
  78774. }
  78775. }
  78776. };
  78777. };
  78778. return CannonJSPlugin;
  78779. }());
  78780. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78781. })(BABYLON || (BABYLON = {}));
  78782. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78783. "use strict";
  78784. var BABYLON;
  78785. (function (BABYLON) {
  78786. var OimoJSPlugin = /** @class */ (function () {
  78787. function OimoJSPlugin(iterations) {
  78788. this.name = "OimoJSPlugin";
  78789. this._tmpImpostorsArray = [];
  78790. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78791. this.BJSOIMO = OIMO;
  78792. this.world = new this.BJSOIMO.World({
  78793. iterations: iterations
  78794. });
  78795. this.world.clear();
  78796. }
  78797. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78798. this.world.gravity.copy(gravity);
  78799. };
  78800. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78801. this.world.timeStep = timeStep;
  78802. };
  78803. OimoJSPlugin.prototype.getTimeStep = function () {
  78804. return this.world.timeStep;
  78805. };
  78806. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78807. var _this = this;
  78808. impostors.forEach(function (impostor) {
  78809. impostor.beforeStep();
  78810. });
  78811. this.world.step();
  78812. impostors.forEach(function (impostor) {
  78813. impostor.afterStep();
  78814. //update the ordered impostors array
  78815. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78816. });
  78817. //check for collisions
  78818. var contact = this.world.contacts;
  78819. while (contact !== null) {
  78820. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78821. contact = contact.next;
  78822. continue;
  78823. }
  78824. //is this body colliding with any other? get the impostor
  78825. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78826. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78827. if (!mainImpostor || !collidingImpostor) {
  78828. contact = contact.next;
  78829. continue;
  78830. }
  78831. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78832. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78833. contact = contact.next;
  78834. }
  78835. };
  78836. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78837. var mass = impostor.physicsBody.mass;
  78838. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  78839. };
  78840. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78841. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78842. this.applyImpulse(impostor, force, contactPoint);
  78843. };
  78844. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78845. var _this = this;
  78846. //parent-child relationship. Does this impostor has a parent impostor?
  78847. if (impostor.parent) {
  78848. if (impostor.physicsBody) {
  78849. this.removePhysicsBody(impostor);
  78850. //TODO is that needed?
  78851. impostor.forceUpdate();
  78852. }
  78853. return;
  78854. }
  78855. if (impostor.isBodyInitRequired()) {
  78856. var bodyConfig = {
  78857. name: impostor.uniqueId,
  78858. //Oimo must have mass, also for static objects.
  78859. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78860. size: [],
  78861. type: [],
  78862. pos: [],
  78863. posShape: [],
  78864. rot: [],
  78865. rotShape: [],
  78866. move: impostor.getParam("mass") !== 0,
  78867. density: impostor.getParam("mass"),
  78868. friction: impostor.getParam("friction"),
  78869. restitution: impostor.getParam("restitution"),
  78870. //Supporting older versions of Oimo
  78871. world: this.world
  78872. };
  78873. var impostors = [impostor];
  78874. var addToArray = function (parent) {
  78875. if (!parent.getChildMeshes)
  78876. return;
  78877. parent.getChildMeshes().forEach(function (m) {
  78878. if (m.physicsImpostor) {
  78879. impostors.push(m.physicsImpostor);
  78880. //m.physicsImpostor._init();
  78881. }
  78882. });
  78883. };
  78884. addToArray(impostor.object);
  78885. var checkWithEpsilon_1 = function (value) {
  78886. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78887. };
  78888. impostors.forEach(function (i) {
  78889. if (!i.object.rotationQuaternion) {
  78890. return;
  78891. }
  78892. //get the correct bounding box
  78893. var oldQuaternion = i.object.rotationQuaternion;
  78894. var rot = oldQuaternion.toEulerAngles();
  78895. var extendSize = i.getObjectExtendSize();
  78896. var radToDeg = 57.295779513082320876;
  78897. if (i === impostor) {
  78898. var center = impostor.getObjectCenter();
  78899. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78900. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78901. //Can also use Array.prototype.push.apply
  78902. bodyConfig.pos.push(center.x);
  78903. bodyConfig.pos.push(center.y);
  78904. bodyConfig.pos.push(center.z);
  78905. bodyConfig.posShape.push(0, 0, 0);
  78906. //tmp solution
  78907. bodyConfig.rot.push(rot.x * radToDeg);
  78908. bodyConfig.rot.push(rot.y * radToDeg);
  78909. bodyConfig.rot.push(rot.z * radToDeg);
  78910. bodyConfig.rotShape.push(0, 0, 0);
  78911. }
  78912. else {
  78913. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78914. bodyConfig.posShape.push(localPosition.x);
  78915. bodyConfig.posShape.push(localPosition.y);
  78916. bodyConfig.posShape.push(localPosition.z);
  78917. bodyConfig.pos.push(0, 0, 0);
  78918. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78919. bodyConfig.rot.push(0);
  78920. bodyConfig.rot.push(0);
  78921. bodyConfig.rot.push(0);
  78922. bodyConfig.rotShape.push(rot.x * radToDeg);
  78923. bodyConfig.rotShape.push(rot.y * radToDeg);
  78924. bodyConfig.rotShape.push(rot.z * radToDeg);
  78925. }
  78926. // register mesh
  78927. switch (i.type) {
  78928. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78929. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  78930. case BABYLON.PhysicsImpostor.SphereImpostor:
  78931. var radiusX = extendSize.x;
  78932. var radiusY = extendSize.y;
  78933. var radiusZ = extendSize.z;
  78934. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78935. bodyConfig.type.push('sphere');
  78936. //due to the way oimo works with compounds, add 3 times
  78937. bodyConfig.size.push(size);
  78938. bodyConfig.size.push(size);
  78939. bodyConfig.size.push(size);
  78940. break;
  78941. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78942. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78943. var sizeY = checkWithEpsilon_1(extendSize.y);
  78944. bodyConfig.type.push('cylinder');
  78945. bodyConfig.size.push(sizeX);
  78946. bodyConfig.size.push(sizeY);
  78947. //due to the way oimo works with compounds, add one more value.
  78948. bodyConfig.size.push(sizeY);
  78949. break;
  78950. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78951. case BABYLON.PhysicsImpostor.BoxImpostor:
  78952. default:
  78953. var sizeX = checkWithEpsilon_1(extendSize.x);
  78954. var sizeY = checkWithEpsilon_1(extendSize.y);
  78955. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78956. bodyConfig.type.push('box');
  78957. //if (i === impostor) {
  78958. bodyConfig.size.push(sizeX);
  78959. bodyConfig.size.push(sizeY);
  78960. bodyConfig.size.push(sizeZ);
  78961. //} else {
  78962. // bodyConfig.size.push(0,0,0);
  78963. //}
  78964. break;
  78965. }
  78966. //actually not needed, but hey...
  78967. i.object.rotationQuaternion = oldQuaternion;
  78968. });
  78969. impostor.physicsBody = this.world.add(bodyConfig);
  78970. }
  78971. else {
  78972. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78973. }
  78974. impostor.setDeltaPosition(this._tmpPositionVector);
  78975. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78976. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78977. };
  78978. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78979. //impostor.physicsBody.dispose();
  78980. //Same as : (older oimo versions)
  78981. this.world.removeRigidBody(impostor.physicsBody);
  78982. };
  78983. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78984. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78985. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78986. if (!mainBody || !connectedBody) {
  78987. return;
  78988. }
  78989. var jointData = impostorJoint.joint.jointData;
  78990. var options = jointData.nativeParams || {};
  78991. var type;
  78992. var nativeJointData = {
  78993. body1: mainBody,
  78994. body2: connectedBody,
  78995. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78996. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78997. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78998. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78999. min: options.min,
  79000. max: options.max,
  79001. collision: options.collision || jointData.collision,
  79002. spring: options.spring,
  79003. //supporting older version of Oimo
  79004. world: this.world
  79005. };
  79006. switch (impostorJoint.joint.type) {
  79007. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79008. type = "jointBall";
  79009. break;
  79010. case BABYLON.PhysicsJoint.SpringJoint:
  79011. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79012. var springData = jointData;
  79013. nativeJointData.min = springData.length || nativeJointData.min;
  79014. //Max should also be set, just make sure it is at least min
  79015. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79016. case BABYLON.PhysicsJoint.DistanceJoint:
  79017. type = "jointDistance";
  79018. nativeJointData.max = jointData.maxDistance;
  79019. break;
  79020. case BABYLON.PhysicsJoint.PrismaticJoint:
  79021. type = "jointPrisme";
  79022. break;
  79023. case BABYLON.PhysicsJoint.SliderJoint:
  79024. type = "jointSlide";
  79025. break;
  79026. case BABYLON.PhysicsJoint.WheelJoint:
  79027. type = "jointWheel";
  79028. break;
  79029. case BABYLON.PhysicsJoint.HingeJoint:
  79030. default:
  79031. type = "jointHinge";
  79032. break;
  79033. }
  79034. nativeJointData.type = type;
  79035. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79036. };
  79037. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79038. //Bug in Oimo prevents us from disposing a joint in the playground
  79039. //joint.joint.physicsJoint.dispose();
  79040. //So we will bruteforce it!
  79041. try {
  79042. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79043. }
  79044. catch (e) {
  79045. BABYLON.Tools.Warn(e);
  79046. }
  79047. };
  79048. OimoJSPlugin.prototype.isSupported = function () {
  79049. return this.BJSOIMO !== undefined;
  79050. };
  79051. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79052. if (!impostor.physicsBody.sleeping) {
  79053. //TODO check that
  79054. /*if (impostor.physicsBody.shapes.next) {
  79055. var parentShape = this._getLastShape(impostor.physicsBody);
  79056. impostor.object.position.copyFrom(parentShape.position);
  79057. console.log(parentShape.position);
  79058. } else {*/
  79059. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79060. //}
  79061. if (impostor.object.rotationQuaternion) {
  79062. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79063. }
  79064. }
  79065. };
  79066. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79067. var body = impostor.physicsBody;
  79068. body.position.copy(newPosition);
  79069. body.orientation.copy(newRotation);
  79070. body.syncShapes();
  79071. body.awake();
  79072. };
  79073. /*private _getLastShape(body: any): any {
  79074. var lastShape = body.shapes;
  79075. while (lastShape.next) {
  79076. lastShape = lastShape.next;
  79077. }
  79078. return lastShape;
  79079. }*/
  79080. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79081. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79082. };
  79083. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79084. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79085. };
  79086. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79087. var v = impostor.physicsBody.linearVelocity;
  79088. if (!v) {
  79089. return null;
  79090. }
  79091. return new BABYLON.Vector3(v.x, v.y, v.z);
  79092. };
  79093. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79094. var v = impostor.physicsBody.angularVelocity;
  79095. if (!v) {
  79096. return null;
  79097. }
  79098. return new BABYLON.Vector3(v.x, v.y, v.z);
  79099. };
  79100. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79101. var staticBody = mass === 0;
  79102. //this will actually set the body's density and not its mass.
  79103. //But this is how oimo treats the mass variable.
  79104. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79105. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79106. };
  79107. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79108. return impostor.physicsBody.shapes.density;
  79109. };
  79110. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79111. return impostor.physicsBody.shapes.friction;
  79112. };
  79113. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79114. impostor.physicsBody.shapes.friction = friction;
  79115. };
  79116. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79117. return impostor.physicsBody.shapes.restitution;
  79118. };
  79119. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79120. impostor.physicsBody.shapes.restitution = restitution;
  79121. };
  79122. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79123. impostor.physicsBody.sleep();
  79124. };
  79125. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79126. impostor.physicsBody.awake();
  79127. };
  79128. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79129. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79130. if (minDistance !== void 0) {
  79131. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79132. }
  79133. };
  79134. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79135. //TODO separate rotational and transational motors.
  79136. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79137. if (motor) {
  79138. motor.setMotor(speed, maxForce);
  79139. }
  79140. };
  79141. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79142. //TODO separate rotational and transational motors.
  79143. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79144. if (motor) {
  79145. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79146. }
  79147. };
  79148. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79149. var body = impostor.physicsBody;
  79150. mesh.position.x = body.position.x;
  79151. mesh.position.y = body.position.y;
  79152. mesh.position.z = body.position.z;
  79153. if (mesh.rotationQuaternion) {
  79154. mesh.rotationQuaternion.x = body.orientation.x;
  79155. mesh.rotationQuaternion.y = body.orientation.y;
  79156. mesh.rotationQuaternion.z = body.orientation.z;
  79157. mesh.rotationQuaternion.w = body.orientation.s;
  79158. }
  79159. };
  79160. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79161. return impostor.physicsBody.shapes.radius;
  79162. };
  79163. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79164. var shape = impostor.physicsBody.shapes;
  79165. result.x = shape.halfWidth * 2;
  79166. result.y = shape.halfHeight * 2;
  79167. result.z = shape.halfDepth * 2;
  79168. };
  79169. OimoJSPlugin.prototype.dispose = function () {
  79170. this.world.clear();
  79171. };
  79172. return OimoJSPlugin;
  79173. }());
  79174. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79175. })(BABYLON || (BABYLON = {}));
  79176. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79177. "use strict";
  79178. var BABYLON;
  79179. (function (BABYLON) {
  79180. /*
  79181. * Based on jsTGALoader - Javascript loader for TGA file
  79182. * By Vincent Thibault
  79183. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79184. */
  79185. var TGATools = /** @class */ (function () {
  79186. function TGATools() {
  79187. }
  79188. TGATools.GetTGAHeader = function (data) {
  79189. var offset = 0;
  79190. var header = {
  79191. id_length: data[offset++],
  79192. colormap_type: data[offset++],
  79193. image_type: data[offset++],
  79194. colormap_index: data[offset++] | data[offset++] << 8,
  79195. colormap_length: data[offset++] | data[offset++] << 8,
  79196. colormap_size: data[offset++],
  79197. origin: [
  79198. data[offset++] | data[offset++] << 8,
  79199. data[offset++] | data[offset++] << 8
  79200. ],
  79201. width: data[offset++] | data[offset++] << 8,
  79202. height: data[offset++] | data[offset++] << 8,
  79203. pixel_size: data[offset++],
  79204. flags: data[offset++]
  79205. };
  79206. return header;
  79207. };
  79208. TGATools.UploadContent = function (gl, data) {
  79209. // Not enough data to contain header ?
  79210. if (data.length < 19) {
  79211. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79212. return;
  79213. }
  79214. // Read Header
  79215. var offset = 18;
  79216. var header = TGATools.GetTGAHeader(data);
  79217. // Assume it's a valid Targa file.
  79218. if (header.id_length + offset > data.length) {
  79219. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79220. return;
  79221. }
  79222. // Skip not needed data
  79223. offset += header.id_length;
  79224. var use_rle = false;
  79225. var use_pal = false;
  79226. var use_grey = false;
  79227. // Get some informations.
  79228. switch (header.image_type) {
  79229. case TGATools._TYPE_RLE_INDEXED:
  79230. use_rle = true;
  79231. case TGATools._TYPE_INDEXED:
  79232. use_pal = true;
  79233. break;
  79234. case TGATools._TYPE_RLE_RGB:
  79235. use_rle = true;
  79236. case TGATools._TYPE_RGB:
  79237. // use_rgb = true;
  79238. break;
  79239. case TGATools._TYPE_RLE_GREY:
  79240. use_rle = true;
  79241. case TGATools._TYPE_GREY:
  79242. use_grey = true;
  79243. break;
  79244. }
  79245. var pixel_data;
  79246. // var numAlphaBits = header.flags & 0xf;
  79247. var pixel_size = header.pixel_size >> 3;
  79248. var pixel_total = header.width * header.height * pixel_size;
  79249. // Read palettes
  79250. var palettes;
  79251. if (use_pal) {
  79252. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79253. }
  79254. // Read LRE
  79255. if (use_rle) {
  79256. pixel_data = new Uint8Array(pixel_total);
  79257. var c, count, i;
  79258. var localOffset = 0;
  79259. var pixels = new Uint8Array(pixel_size);
  79260. while (offset < pixel_total && localOffset < pixel_total) {
  79261. c = data[offset++];
  79262. count = (c & 0x7f) + 1;
  79263. // RLE pixels
  79264. if (c & 0x80) {
  79265. // Bind pixel tmp array
  79266. for (i = 0; i < pixel_size; ++i) {
  79267. pixels[i] = data[offset++];
  79268. }
  79269. // Copy pixel array
  79270. for (i = 0; i < count; ++i) {
  79271. pixel_data.set(pixels, localOffset + i * pixel_size);
  79272. }
  79273. localOffset += pixel_size * count;
  79274. }
  79275. else {
  79276. count *= pixel_size;
  79277. for (i = 0; i < count; ++i) {
  79278. pixel_data[localOffset + i] = data[offset++];
  79279. }
  79280. localOffset += count;
  79281. }
  79282. }
  79283. }
  79284. else {
  79285. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79286. }
  79287. // Load to texture
  79288. var x_start, y_start, x_step, y_step, y_end, x_end;
  79289. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79290. default:
  79291. case TGATools._ORIGIN_UL:
  79292. x_start = 0;
  79293. x_step = 1;
  79294. x_end = header.width;
  79295. y_start = 0;
  79296. y_step = 1;
  79297. y_end = header.height;
  79298. break;
  79299. case TGATools._ORIGIN_BL:
  79300. x_start = 0;
  79301. x_step = 1;
  79302. x_end = header.width;
  79303. y_start = header.height - 1;
  79304. y_step = -1;
  79305. y_end = -1;
  79306. break;
  79307. case TGATools._ORIGIN_UR:
  79308. x_start = header.width - 1;
  79309. x_step = -1;
  79310. x_end = -1;
  79311. y_start = 0;
  79312. y_step = 1;
  79313. y_end = header.height;
  79314. break;
  79315. case TGATools._ORIGIN_BR:
  79316. x_start = header.width - 1;
  79317. x_step = -1;
  79318. x_end = -1;
  79319. y_start = header.height - 1;
  79320. y_step = -1;
  79321. y_end = -1;
  79322. break;
  79323. }
  79324. // Load the specify method
  79325. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79326. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79327. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79328. };
  79329. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79330. var image = pixel_data, colormap = palettes;
  79331. var width = header.width, height = header.height;
  79332. var color, i = 0, x, y;
  79333. var imageData = new Uint8Array(width * height * 4);
  79334. for (y = y_start; y !== y_end; y += y_step) {
  79335. for (x = x_start; x !== x_end; x += x_step, i++) {
  79336. color = image[i];
  79337. imageData[(x + width * y) * 4 + 3] = 255;
  79338. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79339. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79340. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79341. }
  79342. }
  79343. return imageData;
  79344. };
  79345. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79346. var image = pixel_data;
  79347. var width = header.width, height = header.height;
  79348. var color, i = 0, x, y;
  79349. var imageData = new Uint8Array(width * height * 4);
  79350. for (y = y_start; y !== y_end; y += y_step) {
  79351. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79352. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79353. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79354. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79355. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79356. imageData[(x + width * y) * 4 + 0] = r;
  79357. imageData[(x + width * y) * 4 + 1] = g;
  79358. imageData[(x + width * y) * 4 + 2] = b;
  79359. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79360. }
  79361. }
  79362. return imageData;
  79363. };
  79364. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79365. var image = pixel_data;
  79366. var width = header.width, height = header.height;
  79367. var i = 0, x, y;
  79368. var imageData = new Uint8Array(width * height * 4);
  79369. for (y = y_start; y !== y_end; y += y_step) {
  79370. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79371. imageData[(x + width * y) * 4 + 3] = 255;
  79372. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79373. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79374. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79375. }
  79376. }
  79377. return imageData;
  79378. };
  79379. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79380. var image = pixel_data;
  79381. var width = header.width, height = header.height;
  79382. var i = 0, x, y;
  79383. var imageData = new Uint8Array(width * height * 4);
  79384. for (y = y_start; y !== y_end; y += y_step) {
  79385. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79386. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79387. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79388. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79389. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79390. }
  79391. }
  79392. return imageData;
  79393. };
  79394. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79395. var image = pixel_data;
  79396. var width = header.width, height = header.height;
  79397. var color, i = 0, x, y;
  79398. var imageData = new Uint8Array(width * height * 4);
  79399. for (y = y_start; y !== y_end; y += y_step) {
  79400. for (x = x_start; x !== x_end; x += x_step, i++) {
  79401. color = image[i];
  79402. imageData[(x + width * y) * 4 + 0] = color;
  79403. imageData[(x + width * y) * 4 + 1] = color;
  79404. imageData[(x + width * y) * 4 + 2] = color;
  79405. imageData[(x + width * y) * 4 + 3] = 255;
  79406. }
  79407. }
  79408. return imageData;
  79409. };
  79410. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79411. var image = pixel_data;
  79412. var width = header.width, height = header.height;
  79413. var i = 0, x, y;
  79414. var imageData = new Uint8Array(width * height * 4);
  79415. for (y = y_start; y !== y_end; y += y_step) {
  79416. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79417. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79418. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79419. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79420. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79421. }
  79422. }
  79423. return imageData;
  79424. };
  79425. //private static _TYPE_NO_DATA = 0;
  79426. TGATools._TYPE_INDEXED = 1;
  79427. TGATools._TYPE_RGB = 2;
  79428. TGATools._TYPE_GREY = 3;
  79429. TGATools._TYPE_RLE_INDEXED = 9;
  79430. TGATools._TYPE_RLE_RGB = 10;
  79431. TGATools._TYPE_RLE_GREY = 11;
  79432. TGATools._ORIGIN_MASK = 0x30;
  79433. TGATools._ORIGIN_SHIFT = 0x04;
  79434. TGATools._ORIGIN_BL = 0x00;
  79435. TGATools._ORIGIN_BR = 0x01;
  79436. TGATools._ORIGIN_UL = 0x02;
  79437. TGATools._ORIGIN_UR = 0x03;
  79438. return TGATools;
  79439. }());
  79440. BABYLON.TGATools = TGATools;
  79441. })(BABYLON || (BABYLON = {}));
  79442. //# sourceMappingURL=babylon.tga.js.map
  79443. "use strict";
  79444. var BABYLON;
  79445. (function (BABYLON) {
  79446. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79447. // All values and structures referenced from:
  79448. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79449. var DDS_MAGIC = 0x20534444;
  79450. var
  79451. //DDSD_CAPS = 0x1,
  79452. //DDSD_HEIGHT = 0x2,
  79453. //DDSD_WIDTH = 0x4,
  79454. //DDSD_PITCH = 0x8,
  79455. //DDSD_PIXELFORMAT = 0x1000,
  79456. DDSD_MIPMAPCOUNT = 0x20000;
  79457. //DDSD_LINEARSIZE = 0x80000,
  79458. //DDSD_DEPTH = 0x800000;
  79459. // var DDSCAPS_COMPLEX = 0x8,
  79460. // DDSCAPS_MIPMAP = 0x400000,
  79461. // DDSCAPS_TEXTURE = 0x1000;
  79462. var DDSCAPS2_CUBEMAP = 0x200;
  79463. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79464. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79465. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79466. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79467. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79468. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79469. // DDSCAPS2_VOLUME = 0x200000;
  79470. var
  79471. //DDPF_ALPHAPIXELS = 0x1,
  79472. //DDPF_ALPHA = 0x2,
  79473. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79474. //DDPF_YUV = 0x200,
  79475. DDPF_LUMINANCE = 0x20000;
  79476. function FourCCToInt32(value) {
  79477. return value.charCodeAt(0) +
  79478. (value.charCodeAt(1) << 8) +
  79479. (value.charCodeAt(2) << 16) +
  79480. (value.charCodeAt(3) << 24);
  79481. }
  79482. function Int32ToFourCC(value) {
  79483. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79484. }
  79485. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79486. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79487. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79488. var FOURCC_DX10 = FourCCToInt32("DX10");
  79489. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79490. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79491. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79492. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79493. var headerLengthInt = 31; // The header length in 32 bit ints
  79494. // Offsets into the header array
  79495. var off_magic = 0;
  79496. var off_size = 1;
  79497. var off_flags = 2;
  79498. var off_height = 3;
  79499. var off_width = 4;
  79500. var off_mipmapCount = 7;
  79501. var off_pfFlags = 20;
  79502. var off_pfFourCC = 21;
  79503. var off_RGBbpp = 22;
  79504. var off_RMask = 23;
  79505. var off_GMask = 24;
  79506. var off_BMask = 25;
  79507. var off_AMask = 26;
  79508. // var off_caps1 = 27;
  79509. var off_caps2 = 28;
  79510. // var off_caps3 = 29;
  79511. // var off_caps4 = 30;
  79512. var off_dxgiFormat = 32;
  79513. ;
  79514. var DDSTools = /** @class */ (function () {
  79515. function DDSTools() {
  79516. }
  79517. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79518. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79519. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79520. var mipmapCount = 1;
  79521. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79522. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79523. }
  79524. var fourCC = header[off_pfFourCC];
  79525. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79526. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79527. switch (fourCC) {
  79528. case FOURCC_D3DFMT_R16G16B16A16F:
  79529. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79530. break;
  79531. case FOURCC_D3DFMT_R32G32B32A32F:
  79532. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79533. break;
  79534. case FOURCC_DX10:
  79535. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79536. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79537. break;
  79538. }
  79539. }
  79540. return {
  79541. width: header[off_width],
  79542. height: header[off_height],
  79543. mipmapCount: mipmapCount,
  79544. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79545. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79546. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79547. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79548. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79549. dxgiFormat: dxgiFormat,
  79550. textureType: textureType
  79551. };
  79552. };
  79553. DDSTools._ToHalfFloat = function (value) {
  79554. if (!DDSTools._FloatView) {
  79555. DDSTools._FloatView = new Float32Array(1);
  79556. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79557. }
  79558. DDSTools._FloatView[0] = value;
  79559. var x = DDSTools._Int32View[0];
  79560. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79561. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79562. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79563. /* If zero, or denormal, or exponent underflows too much for a denormal
  79564. * half, return signed zero. */
  79565. if (e < 103) {
  79566. return bits;
  79567. }
  79568. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79569. if (e > 142) {
  79570. bits |= 0x7c00;
  79571. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79572. * not Inf, so make sure we set one mantissa bit too. */
  79573. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79574. return bits;
  79575. }
  79576. /* If exponent underflows but not too much, return a denormal */
  79577. if (e < 113) {
  79578. m |= 0x0800;
  79579. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79580. * to 1, which is OK. */
  79581. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79582. return bits;
  79583. }
  79584. bits |= ((e - 112) << 10) | (m >> 1);
  79585. bits += m & 1;
  79586. return bits;
  79587. };
  79588. DDSTools._FromHalfFloat = function (value) {
  79589. var s = (value & 0x8000) >> 15;
  79590. var e = (value & 0x7C00) >> 10;
  79591. var f = value & 0x03FF;
  79592. if (e === 0) {
  79593. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79594. }
  79595. else if (e == 0x1F) {
  79596. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79597. }
  79598. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79599. };
  79600. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79601. var destArray = new Float32Array(dataLength);
  79602. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79603. var index = 0;
  79604. for (var y = 0; y < height; y++) {
  79605. for (var x = 0; x < width; x++) {
  79606. var srcPos = (x + y * width) * 4;
  79607. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79608. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79609. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79610. if (DDSTools.StoreLODInAlphaChannel) {
  79611. destArray[index + 3] = lod;
  79612. }
  79613. else {
  79614. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79615. }
  79616. index += 4;
  79617. }
  79618. }
  79619. return destArray;
  79620. };
  79621. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79622. if (DDSTools.StoreLODInAlphaChannel) {
  79623. var destArray = new Uint16Array(dataLength);
  79624. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79625. var index = 0;
  79626. for (var y = 0; y < height; y++) {
  79627. for (var x = 0; x < width; x++) {
  79628. var srcPos = (x + y * width) * 4;
  79629. destArray[index] = srcData[srcPos];
  79630. destArray[index + 1] = srcData[srcPos + 1];
  79631. destArray[index + 2] = srcData[srcPos + 2];
  79632. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79633. index += 4;
  79634. }
  79635. }
  79636. return destArray;
  79637. }
  79638. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79639. };
  79640. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79641. if (DDSTools.StoreLODInAlphaChannel) {
  79642. var destArray = new Float32Array(dataLength);
  79643. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79644. var index = 0;
  79645. for (var y = 0; y < height; y++) {
  79646. for (var x = 0; x < width; x++) {
  79647. var srcPos = (x + y * width) * 4;
  79648. destArray[index] = srcData[srcPos];
  79649. destArray[index + 1] = srcData[srcPos + 1];
  79650. destArray[index + 2] = srcData[srcPos + 2];
  79651. destArray[index + 3] = lod;
  79652. index += 4;
  79653. }
  79654. }
  79655. return destArray;
  79656. }
  79657. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79658. };
  79659. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79660. var destArray = new Uint8Array(dataLength);
  79661. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79662. var index = 0;
  79663. for (var y = 0; y < height; y++) {
  79664. for (var x = 0; x < width; x++) {
  79665. var srcPos = (x + y * width) * 4;
  79666. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79667. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79668. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79669. if (DDSTools.StoreLODInAlphaChannel) {
  79670. destArray[index + 3] = lod;
  79671. }
  79672. else {
  79673. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79674. }
  79675. index += 4;
  79676. }
  79677. }
  79678. return destArray;
  79679. };
  79680. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79681. var destArray = new Uint8Array(dataLength);
  79682. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79683. var index = 0;
  79684. for (var y = 0; y < height; y++) {
  79685. for (var x = 0; x < width; x++) {
  79686. var srcPos = (x + y * width) * 4;
  79687. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79688. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79689. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79690. if (DDSTools.StoreLODInAlphaChannel) {
  79691. destArray[index + 3] = lod;
  79692. }
  79693. else {
  79694. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79695. }
  79696. index += 4;
  79697. }
  79698. }
  79699. return destArray;
  79700. };
  79701. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79702. var byteArray = new Uint8Array(dataLength);
  79703. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79704. var index = 0;
  79705. for (var y = 0; y < height; y++) {
  79706. for (var x = 0; x < width; x++) {
  79707. var srcPos = (x + y * width) * 4;
  79708. byteArray[index] = srcData[srcPos + rOffset];
  79709. byteArray[index + 1] = srcData[srcPos + gOffset];
  79710. byteArray[index + 2] = srcData[srcPos + bOffset];
  79711. byteArray[index + 3] = srcData[srcPos + aOffset];
  79712. index += 4;
  79713. }
  79714. }
  79715. return byteArray;
  79716. };
  79717. DDSTools._ExtractLongWordOrder = function (value) {
  79718. if (value === 0 || value === 255 || value === -16777216) {
  79719. return 0;
  79720. }
  79721. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79722. };
  79723. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79724. var byteArray = new Uint8Array(dataLength);
  79725. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79726. var index = 0;
  79727. for (var y = 0; y < height; y++) {
  79728. for (var x = 0; x < width; x++) {
  79729. var srcPos = (x + y * width) * 3;
  79730. byteArray[index] = srcData[srcPos + rOffset];
  79731. byteArray[index + 1] = srcData[srcPos + gOffset];
  79732. byteArray[index + 2] = srcData[srcPos + bOffset];
  79733. index += 3;
  79734. }
  79735. }
  79736. return byteArray;
  79737. };
  79738. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79739. var byteArray = new Uint8Array(dataLength);
  79740. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79741. var index = 0;
  79742. for (var y = 0; y < height; y++) {
  79743. for (var x = 0; x < width; x++) {
  79744. var srcPos = (x + y * width);
  79745. byteArray[index] = srcData[srcPos];
  79746. index++;
  79747. }
  79748. }
  79749. return byteArray;
  79750. };
  79751. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79752. if (lodIndex === void 0) { lodIndex = -1; }
  79753. var ext = engine.getCaps().s3tc;
  79754. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79755. var fourCC, width, height, dataLength = 0, dataOffset;
  79756. var byteArray, mipmapCount, mip;
  79757. var internalFormat = 0;
  79758. var format = 0;
  79759. var blockBytes = 1;
  79760. if (header[off_magic] !== DDS_MAGIC) {
  79761. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79762. return;
  79763. }
  79764. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79765. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79766. return;
  79767. }
  79768. if (info.isCompressed && !ext) {
  79769. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79770. return;
  79771. }
  79772. var bpp = header[off_RGBbpp];
  79773. dataOffset = header[off_size] + 4;
  79774. var computeFormats = false;
  79775. if (info.isFourCC) {
  79776. fourCC = header[off_pfFourCC];
  79777. switch (fourCC) {
  79778. case FOURCC_DXT1:
  79779. blockBytes = 8;
  79780. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79781. break;
  79782. case FOURCC_DXT3:
  79783. blockBytes = 16;
  79784. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79785. break;
  79786. case FOURCC_DXT5:
  79787. blockBytes = 16;
  79788. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79789. break;
  79790. case FOURCC_D3DFMT_R16G16B16A16F:
  79791. computeFormats = true;
  79792. break;
  79793. case FOURCC_D3DFMT_R32G32B32A32F:
  79794. computeFormats = true;
  79795. break;
  79796. case FOURCC_DX10:
  79797. // There is an additionnal header so dataOffset need to be changed
  79798. dataOffset += 5 * 4; // 5 uints
  79799. var supported = false;
  79800. switch (info.dxgiFormat) {
  79801. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79802. computeFormats = true;
  79803. supported = true;
  79804. break;
  79805. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79806. info.isRGB = true;
  79807. info.isFourCC = false;
  79808. bpp = 32;
  79809. supported = true;
  79810. break;
  79811. }
  79812. if (supported) {
  79813. break;
  79814. }
  79815. default:
  79816. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79817. return;
  79818. }
  79819. }
  79820. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79821. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79822. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79823. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79824. if (computeFormats) {
  79825. format = engine._getWebGLTextureType(info.textureType);
  79826. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79827. }
  79828. mipmapCount = 1;
  79829. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79830. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79831. }
  79832. for (var face = 0; face < faces; face++) {
  79833. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79834. width = header[off_width];
  79835. height = header[off_height];
  79836. for (mip = 0; mip < mipmapCount; ++mip) {
  79837. if (lodIndex === -1 || lodIndex === mip) {
  79838. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79839. var i = (lodIndex === -1) ? mip : 0;
  79840. if (!info.isCompressed && info.isFourCC) {
  79841. dataLength = width * height * 4;
  79842. var floatArray = null;
  79843. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79844. if (bpp === 128) {
  79845. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79846. }
  79847. else if (bpp === 64) {
  79848. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79849. }
  79850. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79851. format = engine._getWebGLTextureType(info.textureType);
  79852. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79853. }
  79854. else {
  79855. if (bpp === 128) {
  79856. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79857. }
  79858. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79859. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79860. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79861. format = engine._getWebGLTextureType(info.textureType);
  79862. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79863. }
  79864. else {
  79865. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79866. }
  79867. }
  79868. if (floatArray) {
  79869. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79870. }
  79871. }
  79872. else if (info.isRGB) {
  79873. if (bpp === 24) {
  79874. dataLength = width * height * 3;
  79875. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79876. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79877. }
  79878. else {
  79879. dataLength = width * height * 4;
  79880. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79881. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79882. }
  79883. }
  79884. else if (info.isLuminance) {
  79885. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79886. var unpaddedRowSize = width;
  79887. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79888. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79889. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79890. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79891. }
  79892. else {
  79893. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79894. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79895. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79896. }
  79897. }
  79898. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79899. width *= 0.5;
  79900. height *= 0.5;
  79901. width = Math.max(1.0, width);
  79902. height = Math.max(1.0, height);
  79903. }
  79904. if (currentFace !== undefined) {
  79905. // Loading a single face
  79906. break;
  79907. }
  79908. }
  79909. };
  79910. DDSTools.StoreLODInAlphaChannel = false;
  79911. return DDSTools;
  79912. }());
  79913. BABYLON.DDSTools = DDSTools;
  79914. })(BABYLON || (BABYLON = {}));
  79915. //# sourceMappingURL=babylon.dds.js.map
  79916. "use strict";
  79917. var BABYLON;
  79918. (function (BABYLON) {
  79919. /**
  79920. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79921. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79922. */
  79923. var KhronosTextureContainer = /** @class */ (function () {
  79924. /**
  79925. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79926. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79927. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79928. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79929. */
  79930. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79931. this.arrayBuffer = arrayBuffer;
  79932. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79933. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79934. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79935. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79936. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79937. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79938. BABYLON.Tools.Error("texture missing KTX identifier");
  79939. return;
  79940. }
  79941. // load the reset of the header in native 32 bit int
  79942. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79943. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79944. var oppositeEndianess = header[0] === 0x01020304;
  79945. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79946. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79947. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79948. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79949. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79950. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79951. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79952. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79953. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79954. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79955. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79956. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79957. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79958. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79959. if (this.glType !== 0) {
  79960. BABYLON.Tools.Error("only compressed formats currently supported");
  79961. return;
  79962. }
  79963. else {
  79964. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79965. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79966. }
  79967. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79968. BABYLON.Tools.Error("only 2D textures currently supported");
  79969. return;
  79970. }
  79971. if (this.numberOfArrayElements !== 0) {
  79972. BABYLON.Tools.Error("texture arrays not currently supported");
  79973. return;
  79974. }
  79975. if (this.numberOfFaces !== facesExpected) {
  79976. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79977. return;
  79978. }
  79979. // we now have a completely validated file, so could use existence of loadType as success
  79980. // would need to make this more elaborate & adjust checks above to support more than one load type
  79981. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79982. }
  79983. // not as fast hardware based, but will probably never need to use
  79984. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79985. return ((val & 0xFF) << 24)
  79986. | ((val & 0xFF00) << 8)
  79987. | ((val >> 8) & 0xFF00)
  79988. | ((val >> 24) & 0xFF);
  79989. };
  79990. /**
  79991. * It is assumed that the texture has already been created & is currently bound
  79992. */
  79993. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79994. switch (this.loadType) {
  79995. case KhronosTextureContainer.COMPRESSED_2D:
  79996. this._upload2DCompressedLevels(gl, loadMipmaps);
  79997. break;
  79998. case KhronosTextureContainer.TEX_2D:
  79999. case KhronosTextureContainer.COMPRESSED_3D:
  80000. case KhronosTextureContainer.TEX_3D:
  80001. }
  80002. };
  80003. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80004. // initialize width & height for level 1
  80005. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80006. var width = this.pixelWidth;
  80007. var height = this.pixelHeight;
  80008. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80009. for (var level = 0; level < mipmapCount; level++) {
  80010. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80011. for (var face = 0; face < this.numberOfFaces; face++) {
  80012. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80013. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80014. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80015. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80016. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80017. }
  80018. width = Math.max(1.0, width * 0.5);
  80019. height = Math.max(1.0, height * 0.5);
  80020. }
  80021. };
  80022. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80023. // load types
  80024. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80025. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80026. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80027. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80028. return KhronosTextureContainer;
  80029. }());
  80030. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80031. })(BABYLON || (BABYLON = {}));
  80032. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80033. "use strict";
  80034. var BABYLON;
  80035. (function (BABYLON) {
  80036. var Debug = /** @class */ (function () {
  80037. function Debug() {
  80038. }
  80039. Debug.AxesViewer = /** @class */ (function () {
  80040. function AxesViewer(scene, scaleLines) {
  80041. if (scaleLines === void 0) { scaleLines = 1; }
  80042. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80043. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80044. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80045. this.scaleLines = 1;
  80046. this.scaleLines = scaleLines;
  80047. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80048. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80049. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80050. this._xmesh.renderingGroupId = 2;
  80051. this._ymesh.renderingGroupId = 2;
  80052. this._zmesh.renderingGroupId = 2;
  80053. this._xmesh.material.checkReadyOnlyOnce = true;
  80054. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80055. this._ymesh.material.checkReadyOnlyOnce = true;
  80056. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80057. this._zmesh.material.checkReadyOnlyOnce = true;
  80058. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80059. this.scene = scene;
  80060. }
  80061. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80062. var scaleLines = this.scaleLines;
  80063. if (this._xmesh) {
  80064. this._xmesh.position.copyFrom(position);
  80065. }
  80066. if (this._ymesh) {
  80067. this._ymesh.position.copyFrom(position);
  80068. }
  80069. if (this._zmesh) {
  80070. this._zmesh.position.copyFrom(position);
  80071. }
  80072. var point2 = this._xline[1];
  80073. point2.x = xaxis.x * scaleLines;
  80074. point2.y = xaxis.y * scaleLines;
  80075. point2.z = xaxis.z * scaleLines;
  80076. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80077. point2 = this._yline[1];
  80078. point2.x = yaxis.x * scaleLines;
  80079. point2.y = yaxis.y * scaleLines;
  80080. point2.z = yaxis.z * scaleLines;
  80081. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80082. point2 = this._zline[1];
  80083. point2.x = zaxis.x * scaleLines;
  80084. point2.y = zaxis.y * scaleLines;
  80085. point2.z = zaxis.z * scaleLines;
  80086. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80087. };
  80088. AxesViewer.prototype.dispose = function () {
  80089. if (this._xmesh) {
  80090. this._xmesh.dispose();
  80091. }
  80092. if (this._ymesh) {
  80093. this._ymesh.dispose();
  80094. }
  80095. if (this._zmesh) {
  80096. this._zmesh.dispose();
  80097. }
  80098. this._xmesh = null;
  80099. this._ymesh = null;
  80100. this._zmesh = null;
  80101. this.scene = null;
  80102. };
  80103. return AxesViewer;
  80104. }());
  80105. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80106. __extends(BoneAxesViewer, _super);
  80107. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80108. if (scaleLines === void 0) { scaleLines = 1; }
  80109. var _this = _super.call(this, scene, scaleLines) || this;
  80110. _this.pos = BABYLON.Vector3.Zero();
  80111. _this.xaxis = BABYLON.Vector3.Zero();
  80112. _this.yaxis = BABYLON.Vector3.Zero();
  80113. _this.zaxis = BABYLON.Vector3.Zero();
  80114. _this.mesh = mesh;
  80115. _this.bone = bone;
  80116. return _this;
  80117. }
  80118. BoneAxesViewer.prototype.update = function () {
  80119. if (!this.mesh || !this.bone) {
  80120. return;
  80121. }
  80122. var bone = this.bone;
  80123. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80124. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80125. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80126. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80127. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80128. };
  80129. BoneAxesViewer.prototype.dispose = function () {
  80130. if (this.mesh) {
  80131. this.mesh = null;
  80132. this.bone = null;
  80133. _super.prototype.dispose.call(this);
  80134. }
  80135. };
  80136. return BoneAxesViewer;
  80137. }(Debug.AxesViewer));
  80138. Debug.PhysicsViewer = /** @class */ (function () {
  80139. function PhysicsViewer(scene) {
  80140. this._impostors = [];
  80141. this._meshes = [];
  80142. this._numMeshes = 0;
  80143. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80144. var physicEngine = this._scene.getPhysicsEngine();
  80145. if (physicEngine) {
  80146. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80147. }
  80148. }
  80149. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80150. var plugin = this._physicsEnginePlugin;
  80151. for (var i = 0; i < this._numMeshes; i++) {
  80152. var impostor = this._impostors[i];
  80153. if (!impostor) {
  80154. continue;
  80155. }
  80156. if (impostor.isDisposed) {
  80157. this.hideImpostor(this._impostors[i--]);
  80158. }
  80159. else {
  80160. var mesh = this._meshes[i];
  80161. if (mesh && plugin) {
  80162. plugin.syncMeshWithImpostor(mesh, impostor);
  80163. }
  80164. }
  80165. }
  80166. };
  80167. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80168. if (!this._scene) {
  80169. return;
  80170. }
  80171. for (var i = 0; i < this._numMeshes; i++) {
  80172. if (this._impostors[i] == impostor) {
  80173. return;
  80174. }
  80175. }
  80176. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80177. if (debugMesh) {
  80178. this._impostors[this._numMeshes] = impostor;
  80179. this._meshes[this._numMeshes] = debugMesh;
  80180. if (this._numMeshes === 0) {
  80181. this._renderFunction = this._updateDebugMeshes.bind(this);
  80182. this._scene.registerBeforeRender(this._renderFunction);
  80183. }
  80184. this._numMeshes++;
  80185. }
  80186. };
  80187. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80188. if (!impostor || !this._scene) {
  80189. return;
  80190. }
  80191. var removed = false;
  80192. for (var i = 0; i < this._numMeshes; i++) {
  80193. if (this._impostors[i] == impostor) {
  80194. var mesh = this._meshes[i];
  80195. if (!mesh) {
  80196. continue;
  80197. }
  80198. this._scene.removeMesh(mesh);
  80199. mesh.dispose();
  80200. this._numMeshes--;
  80201. if (this._numMeshes > 0) {
  80202. this._meshes[i] = this._meshes[this._numMeshes];
  80203. this._impostors[i] = this._impostors[this._numMeshes];
  80204. this._meshes[this._numMeshes] = null;
  80205. this._impostors[this._numMeshes] = null;
  80206. }
  80207. else {
  80208. this._meshes[0] = null;
  80209. this._impostors[0] = null;
  80210. }
  80211. removed = true;
  80212. break;
  80213. }
  80214. }
  80215. if (removed && this._numMeshes === 0) {
  80216. this._scene.unregisterBeforeRender(this._renderFunction);
  80217. }
  80218. };
  80219. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80220. if (!this._debugMaterial) {
  80221. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80222. this._debugMaterial.wireframe = true;
  80223. }
  80224. return this._debugMaterial;
  80225. };
  80226. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80227. if (!this._debugBoxMesh) {
  80228. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80229. this._debugBoxMesh.renderingGroupId = 1;
  80230. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80231. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80232. scene.removeMesh(this._debugBoxMesh);
  80233. }
  80234. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80235. };
  80236. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80237. if (!this._debugSphereMesh) {
  80238. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80239. this._debugSphereMesh.renderingGroupId = 1;
  80240. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80241. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80242. scene.removeMesh(this._debugSphereMesh);
  80243. }
  80244. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80245. };
  80246. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80247. var mesh = null;
  80248. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80249. mesh = this._getDebugBoxMesh(scene);
  80250. impostor.getBoxSizeToRef(mesh.scaling);
  80251. }
  80252. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80253. mesh = this._getDebugSphereMesh(scene);
  80254. var radius = impostor.getRadius();
  80255. mesh.scaling.x = radius * 2;
  80256. mesh.scaling.y = radius * 2;
  80257. mesh.scaling.z = radius * 2;
  80258. }
  80259. return mesh;
  80260. };
  80261. PhysicsViewer.prototype.dispose = function () {
  80262. for (var i = 0; i < this._numMeshes; i++) {
  80263. this.hideImpostor(this._impostors[i]);
  80264. }
  80265. if (this._debugBoxMesh) {
  80266. this._debugBoxMesh.dispose();
  80267. }
  80268. if (this._debugSphereMesh) {
  80269. this._debugSphereMesh.dispose();
  80270. }
  80271. if (this._debugMaterial) {
  80272. this._debugMaterial.dispose();
  80273. }
  80274. this._impostors.length = 0;
  80275. this._scene = null;
  80276. this._physicsEnginePlugin = null;
  80277. };
  80278. return PhysicsViewer;
  80279. }());
  80280. Debug.SkeletonViewer = /** @class */ (function () {
  80281. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80282. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80283. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80284. this.skeleton = skeleton;
  80285. this.mesh = mesh;
  80286. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80287. this.renderingGroupId = renderingGroupId;
  80288. this.color = BABYLON.Color3.White();
  80289. this._debugLines = new Array();
  80290. this._isEnabled = false;
  80291. this._scene = scene;
  80292. this.update();
  80293. this._renderFunction = this.update.bind(this);
  80294. }
  80295. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80296. get: function () {
  80297. return this._isEnabled;
  80298. },
  80299. set: function (value) {
  80300. if (this._isEnabled === value) {
  80301. return;
  80302. }
  80303. this._isEnabled = value;
  80304. if (value) {
  80305. this._scene.registerBeforeRender(this._renderFunction);
  80306. }
  80307. else {
  80308. this._scene.unregisterBeforeRender(this._renderFunction);
  80309. }
  80310. },
  80311. enumerable: true,
  80312. configurable: true
  80313. });
  80314. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80315. if (x === void 0) { x = 0; }
  80316. if (y === void 0) { y = 0; }
  80317. if (z === void 0) { z = 0; }
  80318. var tmat = BABYLON.Tmp.Matrix[0];
  80319. var parentBone = bone.getParent();
  80320. tmat.copyFrom(bone.getLocalMatrix());
  80321. if (x !== 0 || y !== 0 || z !== 0) {
  80322. var tmat2 = BABYLON.Tmp.Matrix[1];
  80323. BABYLON.Matrix.IdentityToRef(tmat2);
  80324. tmat2.m[12] = x;
  80325. tmat2.m[13] = y;
  80326. tmat2.m[14] = z;
  80327. tmat2.multiplyToRef(tmat, tmat);
  80328. }
  80329. if (parentBone) {
  80330. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80331. }
  80332. tmat.multiplyToRef(meshMat, tmat);
  80333. position.x = tmat.m[12];
  80334. position.y = tmat.m[13];
  80335. position.z = tmat.m[14];
  80336. };
  80337. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80338. var len = bones.length;
  80339. var meshPos = this.mesh.position;
  80340. for (var i = 0; i < len; i++) {
  80341. var bone = bones[i];
  80342. var points = this._debugLines[i];
  80343. if (!points) {
  80344. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80345. this._debugLines[i] = points;
  80346. }
  80347. this._getBonePosition(points[0], bone, meshMat);
  80348. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80349. points[0].subtractInPlace(meshPos);
  80350. points[1].subtractInPlace(meshPos);
  80351. }
  80352. };
  80353. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80354. var len = bones.length;
  80355. var boneNum = 0;
  80356. var meshPos = this.mesh.position;
  80357. for (var i = len - 1; i >= 0; i--) {
  80358. var childBone = bones[i];
  80359. var parentBone = childBone.getParent();
  80360. if (!parentBone) {
  80361. continue;
  80362. }
  80363. var points = this._debugLines[boneNum];
  80364. if (!points) {
  80365. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80366. this._debugLines[boneNum] = points;
  80367. }
  80368. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80369. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80370. points[0].subtractInPlace(meshPos);
  80371. points[1].subtractInPlace(meshPos);
  80372. boneNum++;
  80373. }
  80374. };
  80375. SkeletonViewer.prototype.update = function () {
  80376. if (this.autoUpdateBonesMatrices) {
  80377. this.skeleton.computeAbsoluteTransforms();
  80378. }
  80379. if (this.skeleton.bones[0].length === undefined) {
  80380. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80381. }
  80382. else {
  80383. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80384. }
  80385. if (!this._debugMesh) {
  80386. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80387. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80388. }
  80389. else {
  80390. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80391. }
  80392. this._debugMesh.position.copyFrom(this.mesh.position);
  80393. this._debugMesh.color = this.color;
  80394. };
  80395. SkeletonViewer.prototype.dispose = function () {
  80396. if (this._debugMesh) {
  80397. this.isEnabled = false;
  80398. this._debugMesh.dispose();
  80399. this._debugMesh = null;
  80400. }
  80401. };
  80402. return SkeletonViewer;
  80403. }());
  80404. return Debug;
  80405. }());
  80406. BABYLON.Debug = Debug;
  80407. })(BABYLON || (BABYLON = {}));
  80408. //# sourceMappingURL=babylon.debugModules.js.map
  80409. "use strict";
  80410. var BABYLON;
  80411. (function (BABYLON) {
  80412. var RayHelper = /** @class */ (function () {
  80413. function RayHelper(ray) {
  80414. this.ray = ray;
  80415. }
  80416. RayHelper.CreateAndShow = function (ray, scene, color) {
  80417. var helper = new RayHelper(ray);
  80418. helper.show(scene, color);
  80419. return helper;
  80420. };
  80421. RayHelper.prototype.show = function (scene, color) {
  80422. if (!this._renderFunction && this.ray) {
  80423. var ray = this.ray;
  80424. this._renderFunction = this._render.bind(this);
  80425. this._scene = scene;
  80426. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80427. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80428. if (this._renderFunction) {
  80429. this._scene.registerBeforeRender(this._renderFunction);
  80430. }
  80431. }
  80432. if (color && this._renderLine) {
  80433. this._renderLine.color.copyFrom(color);
  80434. }
  80435. };
  80436. RayHelper.prototype.hide = function () {
  80437. if (this._renderFunction && this._scene) {
  80438. this._scene.unregisterBeforeRender(this._renderFunction);
  80439. this._scene = null;
  80440. this._renderFunction = null;
  80441. if (this._renderLine) {
  80442. this._renderLine.dispose();
  80443. this._renderLine = null;
  80444. }
  80445. this._renderPoints = [];
  80446. }
  80447. };
  80448. RayHelper.prototype._render = function () {
  80449. var ray = this.ray;
  80450. if (!ray) {
  80451. return;
  80452. }
  80453. var point = this._renderPoints[1];
  80454. var len = Math.min(ray.length, 1000000);
  80455. point.copyFrom(ray.direction);
  80456. point.scaleInPlace(len);
  80457. point.addInPlace(ray.origin);
  80458. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80459. };
  80460. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80461. this._attachedToMesh = mesh;
  80462. var ray = this.ray;
  80463. if (!ray) {
  80464. return;
  80465. }
  80466. if (!ray.direction) {
  80467. ray.direction = BABYLON.Vector3.Zero();
  80468. }
  80469. if (!ray.origin) {
  80470. ray.origin = BABYLON.Vector3.Zero();
  80471. }
  80472. if (length) {
  80473. ray.length = length;
  80474. }
  80475. if (!meshSpaceOrigin) {
  80476. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80477. }
  80478. if (!meshSpaceDirection) {
  80479. // -1 so that this will work with Mesh.lookAt
  80480. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80481. }
  80482. if (!this._meshSpaceDirection) {
  80483. this._meshSpaceDirection = meshSpaceDirection.clone();
  80484. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80485. }
  80486. else {
  80487. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80488. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80489. }
  80490. if (!this._updateToMeshFunction) {
  80491. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80492. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80493. }
  80494. this._updateToMesh();
  80495. };
  80496. RayHelper.prototype.detachFromMesh = function () {
  80497. if (this._attachedToMesh) {
  80498. if (this._updateToMeshFunction) {
  80499. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80500. }
  80501. this._attachedToMesh = null;
  80502. this._updateToMeshFunction = null;
  80503. }
  80504. };
  80505. RayHelper.prototype._updateToMesh = function () {
  80506. var ray = this.ray;
  80507. if (!this._attachedToMesh || !ray) {
  80508. return;
  80509. }
  80510. if (this._attachedToMesh._isDisposed) {
  80511. this.detachFromMesh();
  80512. return;
  80513. }
  80514. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80515. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80516. };
  80517. RayHelper.prototype.dispose = function () {
  80518. this.hide();
  80519. this.detachFromMesh();
  80520. this.ray = null;
  80521. };
  80522. return RayHelper;
  80523. }());
  80524. BABYLON.RayHelper = RayHelper;
  80525. })(BABYLON || (BABYLON = {}));
  80526. //# sourceMappingURL=babylon.rayHelper.js.map
  80527. "use strict";
  80528. var BABYLON;
  80529. (function (BABYLON) {
  80530. // load the inspector using require, if not present in the global namespace.
  80531. var DebugLayer = /** @class */ (function () {
  80532. function DebugLayer(scene) {
  80533. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80534. this._scene = scene;
  80535. // load inspector using require, if it doesn't exist on the global namespace.
  80536. }
  80537. /** Creates the inspector window. */
  80538. DebugLayer.prototype._createInspector = function (config) {
  80539. if (config === void 0) { config = {}; }
  80540. var popup = config.popup || false;
  80541. var initialTab = config.initialTab || 0;
  80542. var parentElement = config.parentElement || null;
  80543. if (!this._inspector) {
  80544. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80545. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80546. } // else nothing to do,; instance is already existing
  80547. };
  80548. DebugLayer.prototype.isVisible = function () {
  80549. if (!this._inspector) {
  80550. return false;
  80551. }
  80552. return true;
  80553. };
  80554. DebugLayer.prototype.hide = function () {
  80555. if (this._inspector) {
  80556. try {
  80557. this._inspector.dispose();
  80558. }
  80559. catch (e) {
  80560. // If the inspector has been removed directly from the inspector tool
  80561. }
  80562. this._inspector = null;
  80563. }
  80564. };
  80565. DebugLayer.prototype.show = function (config) {
  80566. if (config === void 0) { config = {}; }
  80567. if (typeof this.BJSINSPECTOR == 'undefined') {
  80568. // Load inspector and add it to the DOM
  80569. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80570. }
  80571. else {
  80572. // Otherwise creates the inspector
  80573. this._createInspector(config);
  80574. }
  80575. };
  80576. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80577. return DebugLayer;
  80578. }());
  80579. BABYLON.DebugLayer = DebugLayer;
  80580. })(BABYLON || (BABYLON = {}));
  80581. //# sourceMappingURL=babylon.debugLayer.js.map
  80582. "use strict";
  80583. var BABYLON;
  80584. (function (BABYLON) {
  80585. var BoundingBoxRenderer = /** @class */ (function () {
  80586. function BoundingBoxRenderer(scene) {
  80587. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80588. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80589. this.showBackLines = true;
  80590. this.renderList = new BABYLON.SmartArray(32);
  80591. this._vertexBuffers = {};
  80592. this._scene = scene;
  80593. }
  80594. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80595. if (this._colorShader) {
  80596. return;
  80597. }
  80598. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80599. attributes: [BABYLON.VertexBuffer.PositionKind],
  80600. uniforms: ["world", "viewProjection", "color"]
  80601. });
  80602. var engine = this._scene.getEngine();
  80603. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80604. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80605. this._createIndexBuffer();
  80606. };
  80607. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80608. var engine = this._scene.getEngine();
  80609. 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]);
  80610. };
  80611. BoundingBoxRenderer.prototype._rebuild = function () {
  80612. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80613. if (vb) {
  80614. vb._rebuild();
  80615. }
  80616. this._createIndexBuffer();
  80617. };
  80618. BoundingBoxRenderer.prototype.reset = function () {
  80619. this.renderList.reset();
  80620. };
  80621. BoundingBoxRenderer.prototype.render = function () {
  80622. if (this.renderList.length === 0) {
  80623. return;
  80624. }
  80625. this._prepareRessources();
  80626. if (!this._colorShader.isReady()) {
  80627. return;
  80628. }
  80629. var engine = this._scene.getEngine();
  80630. engine.setDepthWrite(false);
  80631. this._colorShader._preBind();
  80632. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80633. var boundingBox = this.renderList.data[boundingBoxIndex];
  80634. var min = boundingBox.minimum;
  80635. var max = boundingBox.maximum;
  80636. var diff = max.subtract(min);
  80637. var median = min.add(diff.scale(0.5));
  80638. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80639. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80640. .multiply(boundingBox.getWorldMatrix());
  80641. // VBOs
  80642. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80643. if (this.showBackLines) {
  80644. // Back
  80645. engine.setDepthFunctionToGreaterOrEqual();
  80646. this._scene.resetCachedMaterial();
  80647. this._colorShader.setColor4("color", this.backColor.toColor4());
  80648. this._colorShader.bind(worldMatrix);
  80649. // Draw order
  80650. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80651. }
  80652. // Front
  80653. engine.setDepthFunctionToLess();
  80654. this._scene.resetCachedMaterial();
  80655. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80656. this._colorShader.bind(worldMatrix);
  80657. // Draw order
  80658. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80659. }
  80660. this._colorShader.unbind();
  80661. engine.setDepthFunctionToLessOrEqual();
  80662. engine.setDepthWrite(true);
  80663. };
  80664. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80665. this._prepareRessources();
  80666. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80667. return;
  80668. }
  80669. var engine = this._scene.getEngine();
  80670. engine.setDepthWrite(false);
  80671. engine.setColorWrite(false);
  80672. this._colorShader._preBind();
  80673. var boundingBox = mesh._boundingInfo.boundingBox;
  80674. var min = boundingBox.minimum;
  80675. var max = boundingBox.maximum;
  80676. var diff = max.subtract(min);
  80677. var median = min.add(diff.scale(0.5));
  80678. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80679. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80680. .multiply(boundingBox.getWorldMatrix());
  80681. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80682. engine.setDepthFunctionToLess();
  80683. this._scene.resetCachedMaterial();
  80684. this._colorShader.bind(worldMatrix);
  80685. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80686. this._colorShader.unbind();
  80687. engine.setDepthFunctionToLessOrEqual();
  80688. engine.setDepthWrite(true);
  80689. engine.setColorWrite(true);
  80690. };
  80691. BoundingBoxRenderer.prototype.dispose = function () {
  80692. if (!this._colorShader) {
  80693. return;
  80694. }
  80695. this.renderList.dispose();
  80696. this._colorShader.dispose();
  80697. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80698. if (buffer) {
  80699. buffer.dispose();
  80700. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80701. }
  80702. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80703. };
  80704. return BoundingBoxRenderer;
  80705. }());
  80706. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80707. })(BABYLON || (BABYLON = {}));
  80708. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80709. "use strict";
  80710. var BABYLON;
  80711. (function (BABYLON) {
  80712. var MorphTarget = /** @class */ (function () {
  80713. function MorphTarget(name, influence) {
  80714. if (influence === void 0) { influence = 0; }
  80715. this.name = name;
  80716. this.animations = new Array();
  80717. this._positions = null;
  80718. this._normals = null;
  80719. this._tangents = null;
  80720. this.onInfluenceChanged = new BABYLON.Observable();
  80721. this.influence = influence;
  80722. }
  80723. Object.defineProperty(MorphTarget.prototype, "influence", {
  80724. get: function () {
  80725. return this._influence;
  80726. },
  80727. set: function (influence) {
  80728. if (this._influence === influence) {
  80729. return;
  80730. }
  80731. var previous = this._influence;
  80732. this._influence = influence;
  80733. if (this.onInfluenceChanged.hasObservers) {
  80734. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80735. }
  80736. },
  80737. enumerable: true,
  80738. configurable: true
  80739. });
  80740. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80741. get: function () {
  80742. return !!this._positions;
  80743. },
  80744. enumerable: true,
  80745. configurable: true
  80746. });
  80747. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80748. get: function () {
  80749. return !!this._normals;
  80750. },
  80751. enumerable: true,
  80752. configurable: true
  80753. });
  80754. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80755. get: function () {
  80756. return !!this._tangents;
  80757. },
  80758. enumerable: true,
  80759. configurable: true
  80760. });
  80761. MorphTarget.prototype.setPositions = function (data) {
  80762. this._positions = data;
  80763. };
  80764. MorphTarget.prototype.getPositions = function () {
  80765. return this._positions;
  80766. };
  80767. MorphTarget.prototype.setNormals = function (data) {
  80768. this._normals = data;
  80769. };
  80770. MorphTarget.prototype.getNormals = function () {
  80771. return this._normals;
  80772. };
  80773. MorphTarget.prototype.setTangents = function (data) {
  80774. this._tangents = data;
  80775. };
  80776. MorphTarget.prototype.getTangents = function () {
  80777. return this._tangents;
  80778. };
  80779. /**
  80780. * Serializes the current target into a Serialization object.
  80781. * Returns the serialized object.
  80782. */
  80783. MorphTarget.prototype.serialize = function () {
  80784. var serializationObject = {};
  80785. serializationObject.name = this.name;
  80786. serializationObject.influence = this.influence;
  80787. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80788. if (this.hasNormals) {
  80789. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80790. }
  80791. if (this.hasTangents) {
  80792. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80793. }
  80794. // Animations
  80795. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80796. return serializationObject;
  80797. };
  80798. // Statics
  80799. MorphTarget.Parse = function (serializationObject) {
  80800. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80801. result.setPositions(serializationObject.positions);
  80802. if (serializationObject.normals) {
  80803. result.setNormals(serializationObject.normals);
  80804. }
  80805. if (serializationObject.tangents) {
  80806. result.setTangents(serializationObject.tangents);
  80807. }
  80808. // Animations
  80809. if (serializationObject.animations) {
  80810. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80811. var parsedAnimation = serializationObject.animations[animationIndex];
  80812. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80813. }
  80814. }
  80815. return result;
  80816. };
  80817. MorphTarget.FromMesh = function (mesh, name, influence) {
  80818. if (!name) {
  80819. name = mesh.name;
  80820. }
  80821. var result = new MorphTarget(name, influence);
  80822. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80823. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80824. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80825. }
  80826. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80827. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80828. }
  80829. return result;
  80830. };
  80831. return MorphTarget;
  80832. }());
  80833. BABYLON.MorphTarget = MorphTarget;
  80834. })(BABYLON || (BABYLON = {}));
  80835. //# sourceMappingURL=babylon.morphTarget.js.map
  80836. "use strict";
  80837. var BABYLON;
  80838. (function (BABYLON) {
  80839. var MorphTargetManager = /** @class */ (function () {
  80840. function MorphTargetManager(scene) {
  80841. if (scene === void 0) { scene = null; }
  80842. this._targets = new Array();
  80843. this._targetObservable = new Array();
  80844. this._activeTargets = new BABYLON.SmartArray(16);
  80845. this._supportsNormals = false;
  80846. this._supportsTangents = false;
  80847. this._vertexCount = 0;
  80848. this._uniqueId = 0;
  80849. this._tempInfluences = new Array();
  80850. if (!scene) {
  80851. scene = BABYLON.Engine.LastCreatedScene;
  80852. }
  80853. this._scene = scene;
  80854. if (this._scene) {
  80855. this._scene.morphTargetManagers.push(this);
  80856. this._uniqueId = this._scene.getUniqueId();
  80857. }
  80858. }
  80859. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80860. get: function () {
  80861. return this._uniqueId;
  80862. },
  80863. enumerable: true,
  80864. configurable: true
  80865. });
  80866. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80867. get: function () {
  80868. return this._vertexCount;
  80869. },
  80870. enumerable: true,
  80871. configurable: true
  80872. });
  80873. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80874. get: function () {
  80875. return this._supportsNormals;
  80876. },
  80877. enumerable: true,
  80878. configurable: true
  80879. });
  80880. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80881. get: function () {
  80882. return this._supportsTangents;
  80883. },
  80884. enumerable: true,
  80885. configurable: true
  80886. });
  80887. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80888. get: function () {
  80889. return this._targets.length;
  80890. },
  80891. enumerable: true,
  80892. configurable: true
  80893. });
  80894. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80895. get: function () {
  80896. return this._activeTargets.length;
  80897. },
  80898. enumerable: true,
  80899. configurable: true
  80900. });
  80901. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80902. get: function () {
  80903. return this._influences;
  80904. },
  80905. enumerable: true,
  80906. configurable: true
  80907. });
  80908. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80909. return this._activeTargets.data[index];
  80910. };
  80911. MorphTargetManager.prototype.getTarget = function (index) {
  80912. return this._targets[index];
  80913. };
  80914. MorphTargetManager.prototype.addTarget = function (target) {
  80915. var _this = this;
  80916. this._targets.push(target);
  80917. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80918. _this._syncActiveTargets(needUpdate);
  80919. }));
  80920. this._syncActiveTargets(true);
  80921. };
  80922. MorphTargetManager.prototype.removeTarget = function (target) {
  80923. var index = this._targets.indexOf(target);
  80924. if (index >= 0) {
  80925. this._targets.splice(index, 1);
  80926. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80927. this._syncActiveTargets(true);
  80928. }
  80929. };
  80930. /**
  80931. * Serializes the current manager into a Serialization object.
  80932. * Returns the serialized object.
  80933. */
  80934. MorphTargetManager.prototype.serialize = function () {
  80935. var serializationObject = {};
  80936. serializationObject.id = this.uniqueId;
  80937. serializationObject.targets = [];
  80938. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80939. var target = _a[_i];
  80940. serializationObject.targets.push(target.serialize());
  80941. }
  80942. return serializationObject;
  80943. };
  80944. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80945. var influenceCount = 0;
  80946. this._activeTargets.reset();
  80947. this._supportsNormals = true;
  80948. this._supportsTangents = true;
  80949. this._vertexCount = 0;
  80950. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80951. var target = _a[_i];
  80952. this._activeTargets.push(target);
  80953. this._tempInfluences[influenceCount++] = target.influence;
  80954. var positions = target.getPositions();
  80955. if (positions) {
  80956. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80957. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80958. var vertexCount = positions.length / 3;
  80959. if (this._vertexCount === 0) {
  80960. this._vertexCount = vertexCount;
  80961. }
  80962. else if (this._vertexCount !== vertexCount) {
  80963. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80964. return;
  80965. }
  80966. }
  80967. }
  80968. if (!this._influences || this._influences.length !== influenceCount) {
  80969. this._influences = new Float32Array(influenceCount);
  80970. }
  80971. for (var index = 0; index < influenceCount; index++) {
  80972. this._influences[index] = this._tempInfluences[index];
  80973. }
  80974. if (needUpdate && this._scene) {
  80975. // Flag meshes as dirty to resync with the active targets
  80976. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80977. var mesh = _c[_b];
  80978. if (mesh.morphTargetManager === this) {
  80979. mesh._syncGeometryWithMorphTargetManager();
  80980. }
  80981. }
  80982. }
  80983. };
  80984. // Statics
  80985. MorphTargetManager.Parse = function (serializationObject, scene) {
  80986. var result = new MorphTargetManager(scene);
  80987. result._uniqueId = serializationObject.id;
  80988. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80989. var targetData = _a[_i];
  80990. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80991. }
  80992. return result;
  80993. };
  80994. return MorphTargetManager;
  80995. }());
  80996. BABYLON.MorphTargetManager = MorphTargetManager;
  80997. })(BABYLON || (BABYLON = {}));
  80998. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80999. "use strict";
  81000. var BABYLON;
  81001. (function (BABYLON) {
  81002. var Octree = /** @class */ (function () {
  81003. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81004. if (maxDepth === void 0) { maxDepth = 2; }
  81005. this.maxDepth = maxDepth;
  81006. this.dynamicContent = new Array();
  81007. this._maxBlockCapacity = maxBlockCapacity || 64;
  81008. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81009. this._creationFunc = creationFunc;
  81010. }
  81011. // Methods
  81012. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81013. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81014. };
  81015. Octree.prototype.addMesh = function (entry) {
  81016. for (var index = 0; index < this.blocks.length; index++) {
  81017. var block = this.blocks[index];
  81018. block.addEntry(entry);
  81019. }
  81020. };
  81021. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81022. this._selectionContent.reset();
  81023. for (var index = 0; index < this.blocks.length; index++) {
  81024. var block = this.blocks[index];
  81025. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81026. }
  81027. if (allowDuplicate) {
  81028. this._selectionContent.concat(this.dynamicContent);
  81029. }
  81030. else {
  81031. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81032. }
  81033. return this._selectionContent;
  81034. };
  81035. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81036. this._selectionContent.reset();
  81037. for (var index = 0; index < this.blocks.length; index++) {
  81038. var block = this.blocks[index];
  81039. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81040. }
  81041. if (allowDuplicate) {
  81042. this._selectionContent.concat(this.dynamicContent);
  81043. }
  81044. else {
  81045. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81046. }
  81047. return this._selectionContent;
  81048. };
  81049. Octree.prototype.intersectsRay = function (ray) {
  81050. this._selectionContent.reset();
  81051. for (var index = 0; index < this.blocks.length; index++) {
  81052. var block = this.blocks[index];
  81053. block.intersectsRay(ray, this._selectionContent);
  81054. }
  81055. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81056. return this._selectionContent;
  81057. };
  81058. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81059. target.blocks = new Array();
  81060. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81061. // Segmenting space
  81062. for (var x = 0; x < 2; x++) {
  81063. for (var y = 0; y < 2; y++) {
  81064. for (var z = 0; z < 2; z++) {
  81065. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81066. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81067. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81068. block.addEntries(entries);
  81069. target.blocks.push(block);
  81070. }
  81071. }
  81072. }
  81073. };
  81074. Octree.CreationFuncForMeshes = function (entry, block) {
  81075. var boundingInfo = entry.getBoundingInfo();
  81076. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81077. block.entries.push(entry);
  81078. }
  81079. };
  81080. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81081. var boundingInfo = entry.getBoundingInfo();
  81082. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81083. block.entries.push(entry);
  81084. }
  81085. };
  81086. return Octree;
  81087. }());
  81088. BABYLON.Octree = Octree;
  81089. })(BABYLON || (BABYLON = {}));
  81090. //# sourceMappingURL=babylon.octree.js.map
  81091. "use strict";
  81092. var BABYLON;
  81093. (function (BABYLON) {
  81094. var OctreeBlock = /** @class */ (function () {
  81095. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81096. this.entries = new Array();
  81097. this._boundingVectors = new Array();
  81098. this._capacity = capacity;
  81099. this._depth = depth;
  81100. this._maxDepth = maxDepth;
  81101. this._creationFunc = creationFunc;
  81102. this._minPoint = minPoint;
  81103. this._maxPoint = maxPoint;
  81104. this._boundingVectors.push(minPoint.clone());
  81105. this._boundingVectors.push(maxPoint.clone());
  81106. this._boundingVectors.push(minPoint.clone());
  81107. this._boundingVectors[2].x = maxPoint.x;
  81108. this._boundingVectors.push(minPoint.clone());
  81109. this._boundingVectors[3].y = maxPoint.y;
  81110. this._boundingVectors.push(minPoint.clone());
  81111. this._boundingVectors[4].z = maxPoint.z;
  81112. this._boundingVectors.push(maxPoint.clone());
  81113. this._boundingVectors[5].z = minPoint.z;
  81114. this._boundingVectors.push(maxPoint.clone());
  81115. this._boundingVectors[6].x = minPoint.x;
  81116. this._boundingVectors.push(maxPoint.clone());
  81117. this._boundingVectors[7].y = minPoint.y;
  81118. }
  81119. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81120. // Property
  81121. get: function () {
  81122. return this._capacity;
  81123. },
  81124. enumerable: true,
  81125. configurable: true
  81126. });
  81127. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81128. get: function () {
  81129. return this._minPoint;
  81130. },
  81131. enumerable: true,
  81132. configurable: true
  81133. });
  81134. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81135. get: function () {
  81136. return this._maxPoint;
  81137. },
  81138. enumerable: true,
  81139. configurable: true
  81140. });
  81141. // Methods
  81142. OctreeBlock.prototype.addEntry = function (entry) {
  81143. if (this.blocks) {
  81144. for (var index = 0; index < this.blocks.length; index++) {
  81145. var block = this.blocks[index];
  81146. block.addEntry(entry);
  81147. }
  81148. return;
  81149. }
  81150. this._creationFunc(entry, this);
  81151. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81152. this.createInnerBlocks();
  81153. }
  81154. };
  81155. OctreeBlock.prototype.addEntries = function (entries) {
  81156. for (var index = 0; index < entries.length; index++) {
  81157. var mesh = entries[index];
  81158. this.addEntry(mesh);
  81159. }
  81160. };
  81161. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81162. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81163. if (this.blocks) {
  81164. for (var index = 0; index < this.blocks.length; index++) {
  81165. var block = this.blocks[index];
  81166. block.select(frustumPlanes, selection, allowDuplicate);
  81167. }
  81168. return;
  81169. }
  81170. if (allowDuplicate) {
  81171. selection.concat(this.entries);
  81172. }
  81173. else {
  81174. selection.concatWithNoDuplicate(this.entries);
  81175. }
  81176. }
  81177. };
  81178. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81179. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81180. if (this.blocks) {
  81181. for (var index = 0; index < this.blocks.length; index++) {
  81182. var block = this.blocks[index];
  81183. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81184. }
  81185. return;
  81186. }
  81187. if (allowDuplicate) {
  81188. selection.concat(this.entries);
  81189. }
  81190. else {
  81191. selection.concatWithNoDuplicate(this.entries);
  81192. }
  81193. }
  81194. };
  81195. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81196. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81197. if (this.blocks) {
  81198. for (var index = 0; index < this.blocks.length; index++) {
  81199. var block = this.blocks[index];
  81200. block.intersectsRay(ray, selection);
  81201. }
  81202. return;
  81203. }
  81204. selection.concatWithNoDuplicate(this.entries);
  81205. }
  81206. };
  81207. OctreeBlock.prototype.createInnerBlocks = function () {
  81208. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81209. };
  81210. return OctreeBlock;
  81211. }());
  81212. BABYLON.OctreeBlock = OctreeBlock;
  81213. })(BABYLON || (BABYLON = {}));
  81214. //# sourceMappingURL=babylon.octreeBlock.js.map
  81215. "use strict";
  81216. var BABYLON;
  81217. (function (BABYLON) {
  81218. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81219. __extends(VRDistortionCorrectionPostProcess, _super);
  81220. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81221. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81222. 'LensCenter',
  81223. 'Scale',
  81224. 'ScaleIn',
  81225. 'HmdWarpParam'
  81226. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81227. _this._isRightEye = isRightEye;
  81228. _this._distortionFactors = vrMetrics.distortionK;
  81229. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81230. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81231. _this.adaptScaleToCurrentViewport = true;
  81232. _this.onSizeChangedObservable.add(function () {
  81233. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81234. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81235. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81236. });
  81237. _this.onApplyObservable.add(function (effect) {
  81238. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81239. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81240. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81241. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81242. });
  81243. return _this;
  81244. }
  81245. return VRDistortionCorrectionPostProcess;
  81246. }(BABYLON.PostProcess));
  81247. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81248. })(BABYLON || (BABYLON = {}));
  81249. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81250. "use strict";
  81251. var BABYLON;
  81252. (function (BABYLON) {
  81253. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81254. __extends(AnaglyphPostProcess, _super);
  81255. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81256. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81257. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81258. _this.onApplyObservable.add(function (effect) {
  81259. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81260. });
  81261. return _this;
  81262. }
  81263. return AnaglyphPostProcess;
  81264. }(BABYLON.PostProcess));
  81265. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81266. })(BABYLON || (BABYLON = {}));
  81267. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81268. "use strict";
  81269. var BABYLON;
  81270. (function (BABYLON) {
  81271. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81272. __extends(StereoscopicInterlacePostProcess, _super);
  81273. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81274. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81275. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81276. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81277. _this.onSizeChangedObservable.add(function () {
  81278. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81279. });
  81280. _this.onApplyObservable.add(function (effect) {
  81281. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81282. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81283. });
  81284. return _this;
  81285. }
  81286. return StereoscopicInterlacePostProcess;
  81287. }(BABYLON.PostProcess));
  81288. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81289. })(BABYLON || (BABYLON = {}));
  81290. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81291. "use strict";
  81292. var BABYLON;
  81293. (function (BABYLON) {
  81294. /**
  81295. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81296. * Screen rotation is taken into account.
  81297. */
  81298. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81299. function FreeCameraDeviceOrientationInput() {
  81300. var _this = this;
  81301. this._screenOrientationAngle = 0;
  81302. this._screenQuaternion = new BABYLON.Quaternion();
  81303. this._alpha = 0;
  81304. this._beta = 0;
  81305. this._gamma = 0;
  81306. this._orientationChanged = function () {
  81307. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81308. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81309. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81310. };
  81311. this._deviceOrientation = function (evt) {
  81312. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81313. _this._beta = evt.beta !== null ? evt.beta : 0;
  81314. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81315. };
  81316. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81317. this._orientationChanged();
  81318. }
  81319. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81320. get: function () {
  81321. return this._camera;
  81322. },
  81323. set: function (camera) {
  81324. this._camera = camera;
  81325. if (this._camera != null && !this._camera.rotationQuaternion) {
  81326. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81327. }
  81328. },
  81329. enumerable: true,
  81330. configurable: true
  81331. });
  81332. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81333. window.addEventListener("orientationchange", this._orientationChanged);
  81334. window.addEventListener("deviceorientation", this._deviceOrientation);
  81335. //In certain cases, the attach control is called AFTER orientation was changed,
  81336. //So this is needed.
  81337. this._orientationChanged();
  81338. };
  81339. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81340. window.removeEventListener("orientationchange", this._orientationChanged);
  81341. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81342. };
  81343. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81344. //if no device orientation provided, don't update the rotation.
  81345. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81346. if (!this._alpha)
  81347. return;
  81348. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81349. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81350. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81351. //Mirror on XY Plane
  81352. this._camera.rotationQuaternion.z *= -1;
  81353. this._camera.rotationQuaternion.w *= -1;
  81354. };
  81355. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81356. return "FreeCameraDeviceOrientationInput";
  81357. };
  81358. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81359. return "deviceOrientation";
  81360. };
  81361. return FreeCameraDeviceOrientationInput;
  81362. }());
  81363. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81364. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81365. })(BABYLON || (BABYLON = {}));
  81366. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81367. "use strict";
  81368. var BABYLON;
  81369. (function (BABYLON) {
  81370. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81371. function ArcRotateCameraVRDeviceOrientationInput() {
  81372. this.alphaCorrection = 1;
  81373. this.betaCorrection = 1;
  81374. this.gammaCorrection = 1;
  81375. this._alpha = 0;
  81376. this._gamma = 0;
  81377. this._dirty = false;
  81378. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81379. }
  81380. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81381. this.camera.attachControl(element, noPreventDefault);
  81382. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81383. };
  81384. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81385. if (evt.alpha !== null) {
  81386. this._alpha = +evt.alpha | 0;
  81387. }
  81388. if (evt.gamma !== null) {
  81389. this._gamma = +evt.gamma | 0;
  81390. }
  81391. this._dirty = true;
  81392. };
  81393. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81394. if (this._dirty) {
  81395. this._dirty = false;
  81396. if (this._gamma < 0) {
  81397. this._gamma = 180 + this._gamma;
  81398. }
  81399. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81400. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81401. }
  81402. };
  81403. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81404. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81405. };
  81406. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81407. return "ArcRotateCameraVRDeviceOrientationInput";
  81408. };
  81409. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81410. return "VRDeviceOrientation";
  81411. };
  81412. return ArcRotateCameraVRDeviceOrientationInput;
  81413. }());
  81414. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81415. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81416. })(BABYLON || (BABYLON = {}));
  81417. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81418. "use strict";
  81419. var BABYLON;
  81420. (function (BABYLON) {
  81421. var VRCameraMetrics = /** @class */ (function () {
  81422. function VRCameraMetrics() {
  81423. this.compensateDistortion = true;
  81424. }
  81425. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81426. get: function () {
  81427. return this.hResolution / (2 * this.vResolution);
  81428. },
  81429. enumerable: true,
  81430. configurable: true
  81431. });
  81432. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81433. get: function () {
  81434. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81435. },
  81436. enumerable: true,
  81437. configurable: true
  81438. });
  81439. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81440. get: function () {
  81441. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81442. var h = (4 * meters) / this.hScreenSize;
  81443. return BABYLON.Matrix.Translation(h, 0, 0);
  81444. },
  81445. enumerable: true,
  81446. configurable: true
  81447. });
  81448. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81449. get: function () {
  81450. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81451. var h = (4 * meters) / this.hScreenSize;
  81452. return BABYLON.Matrix.Translation(-h, 0, 0);
  81453. },
  81454. enumerable: true,
  81455. configurable: true
  81456. });
  81457. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81458. get: function () {
  81459. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81460. },
  81461. enumerable: true,
  81462. configurable: true
  81463. });
  81464. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81465. get: function () {
  81466. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81467. },
  81468. enumerable: true,
  81469. configurable: true
  81470. });
  81471. VRCameraMetrics.GetDefault = function () {
  81472. var result = new VRCameraMetrics();
  81473. result.hResolution = 1280;
  81474. result.vResolution = 800;
  81475. result.hScreenSize = 0.149759993;
  81476. result.vScreenSize = 0.0935999975;
  81477. result.vScreenCenter = 0.0467999987;
  81478. result.eyeToScreenDistance = 0.0410000011;
  81479. result.lensSeparationDistance = 0.0635000020;
  81480. result.interpupillaryDistance = 0.0640000030;
  81481. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81482. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81483. result.postProcessScaleFactor = 1.714605507808412;
  81484. result.lensCenterOffset = 0.151976421;
  81485. return result;
  81486. };
  81487. return VRCameraMetrics;
  81488. }());
  81489. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81490. })(BABYLON || (BABYLON = {}));
  81491. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81492. "use strict";
  81493. var BABYLON;
  81494. (function (BABYLON) {
  81495. /**
  81496. * This represents a WebVR camera.
  81497. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81498. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81499. */
  81500. var WebVRFreeCamera = /** @class */ (function (_super) {
  81501. __extends(WebVRFreeCamera, _super);
  81502. /**
  81503. * Instantiates a WebVRFreeCamera.
  81504. * @param name The name of the WebVRFreeCamera
  81505. * @param position The starting anchor position for the camera
  81506. * @param scene The scene the camera belongs to
  81507. * @param webVROptions a set of customizable options for the webVRCamera
  81508. */
  81509. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81510. if (webVROptions === void 0) { webVROptions = {}; }
  81511. var _this = _super.call(this, name, position, scene) || this;
  81512. _this.webVROptions = webVROptions;
  81513. /**
  81514. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81515. */
  81516. _this._vrDevice = null;
  81517. /**
  81518. * The rawPose of the vrDevice.
  81519. */
  81520. _this.rawPose = null;
  81521. _this._specsVersion = "1.1";
  81522. _this._attached = false;
  81523. _this._descendants = [];
  81524. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81525. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81526. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81527. _this._standingMatrix = null;
  81528. /**
  81529. * Represents device position in babylon space.
  81530. */
  81531. _this.devicePosition = BABYLON.Vector3.Zero();
  81532. /**
  81533. * Represents device rotation in babylon space.
  81534. */
  81535. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81536. /**
  81537. * The scale of the device to be used when translating from device space to babylon space.
  81538. */
  81539. _this.deviceScaleFactor = 1;
  81540. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81541. _this._worldToDevice = BABYLON.Matrix.Identity();
  81542. /**
  81543. * References to the webVR controllers for the vrDevice.
  81544. */
  81545. _this.controllers = [];
  81546. /**
  81547. * Emits an event when a controller is attached.
  81548. */
  81549. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81550. /**
  81551. * Emits an event when a controller's mesh has been loaded;
  81552. */
  81553. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81554. /**
  81555. * If the rig cameras be used as parent instead of this camera.
  81556. */
  81557. _this.rigParenting = true;
  81558. _this._defaultHeight = undefined;
  81559. _this._workingVector = BABYLON.Vector3.Zero();
  81560. _this._oneVector = BABYLON.Vector3.One();
  81561. _this._workingMatrix = BABYLON.Matrix.Identity();
  81562. _this._cache.position = BABYLON.Vector3.Zero();
  81563. if (webVROptions.defaultHeight) {
  81564. _this._defaultHeight = webVROptions.defaultHeight;
  81565. _this.position.y = _this._defaultHeight;
  81566. }
  81567. _this.minZ = 0.1;
  81568. //legacy support - the compensation boolean was removed.
  81569. if (arguments.length === 5) {
  81570. _this.webVROptions = arguments[4];
  81571. }
  81572. // default webVR options
  81573. if (_this.webVROptions.trackPosition == undefined) {
  81574. _this.webVROptions.trackPosition = true;
  81575. }
  81576. if (_this.webVROptions.controllerMeshes == undefined) {
  81577. _this.webVROptions.controllerMeshes = true;
  81578. }
  81579. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81580. _this.webVROptions.defaultLightingOnControllers = true;
  81581. }
  81582. _this.rotationQuaternion = new BABYLON.Quaternion();
  81583. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81584. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81585. }
  81586. //enable VR
  81587. var engine = _this.getEngine();
  81588. _this._onVREnabled = function (success) { if (success) {
  81589. _this.initControllers();
  81590. } };
  81591. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81592. engine.initWebVR().add(function (event) {
  81593. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81594. return;
  81595. }
  81596. _this._vrDevice = event.vrDisplay;
  81597. //reset the rig parameters.
  81598. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81599. if (_this._attached) {
  81600. _this.getEngine().enableVR();
  81601. }
  81602. });
  81603. if (typeof (VRFrameData) !== "undefined")
  81604. _this._frameData = new VRFrameData();
  81605. /**
  81606. * The idea behind the following lines:
  81607. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81608. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81609. * the second will not show it correctly.
  81610. *
  81611. * To solve this - each object that has the camera as parent will be added to a protected array.
  81612. * When the rig camera renders, it will take this array and set all of those to be its children.
  81613. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81614. * Amazing!
  81615. */
  81616. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81617. if (camera.parent === _this && _this.rigParenting) {
  81618. _this._descendants = _this.getDescendants(true, function (n) {
  81619. // don't take the cameras or the controllers!
  81620. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81621. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81622. return !isController && !isRigCamera;
  81623. });
  81624. _this._descendants.forEach(function (node) {
  81625. node.parent = camera;
  81626. });
  81627. }
  81628. });
  81629. scene.onAfterCameraRenderObservable.add(function (camera) {
  81630. if (camera.parent === _this && _this.rigParenting) {
  81631. _this._descendants.forEach(function (node) {
  81632. node.parent = _this;
  81633. });
  81634. }
  81635. });
  81636. return _this;
  81637. }
  81638. /**
  81639. * Gets the device distance from the ground in meters.
  81640. * @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.
  81641. */
  81642. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81643. if (this._standingMatrix) {
  81644. // Add standing matrix offset to get real offset from ground in room
  81645. this._standingMatrix.getTranslationToRef(this._workingVector);
  81646. return this._deviceRoomPosition.y + this._workingVector.y;
  81647. }
  81648. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81649. return this._defaultHeight || 0;
  81650. };
  81651. /**
  81652. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81653. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81654. */
  81655. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81656. var _this = this;
  81657. if (callback === void 0) { callback = function (bool) { }; }
  81658. // Use standing matrix if available
  81659. this.getEngine().initWebVRAsync().then(function (result) {
  81660. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81661. callback(false);
  81662. }
  81663. else {
  81664. _this._standingMatrix = new BABYLON.Matrix();
  81665. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81666. if (!_this.getScene().useRightHandedSystem) {
  81667. [2, 6, 8, 9, 14].forEach(function (num) {
  81668. if (_this._standingMatrix) {
  81669. _this._standingMatrix.m[num] *= -1;
  81670. }
  81671. });
  81672. }
  81673. callback(true);
  81674. }
  81675. });
  81676. };
  81677. /**
  81678. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81679. * @returns A promise with a boolean set to if the standing matrix is supported.
  81680. */
  81681. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81682. var _this = this;
  81683. return new Promise(function (res, rej) {
  81684. _this.useStandingMatrix(function (supported) {
  81685. res(supported);
  81686. });
  81687. });
  81688. };
  81689. /**
  81690. * Disposes the camera
  81691. */
  81692. WebVRFreeCamera.prototype.dispose = function () {
  81693. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81694. _super.prototype.dispose.call(this);
  81695. };
  81696. /**
  81697. * Gets a vrController by name.
  81698. * @param name The name of the controller to retreive
  81699. * @returns the controller matching the name specified or null if not found
  81700. */
  81701. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81702. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81703. var gp = _a[_i];
  81704. if (gp.hand === name) {
  81705. return gp;
  81706. }
  81707. }
  81708. return null;
  81709. };
  81710. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81711. /**
  81712. * The controller corrisponding to the users left hand.
  81713. */
  81714. get: function () {
  81715. if (!this._leftController) {
  81716. this._leftController = this.getControllerByName("left");
  81717. }
  81718. return this._leftController;
  81719. },
  81720. enumerable: true,
  81721. configurable: true
  81722. });
  81723. ;
  81724. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81725. /**
  81726. * The controller corrisponding to the users right hand.
  81727. */
  81728. get: function () {
  81729. if (!this._rightController) {
  81730. this._rightController = this.getControllerByName("right");
  81731. }
  81732. return this._rightController;
  81733. },
  81734. enumerable: true,
  81735. configurable: true
  81736. });
  81737. ;
  81738. /**
  81739. * Casts a ray forward from the vrCamera's gaze.
  81740. * @param length Length of the ray (default: 100)
  81741. * @returns the ray corrisponding to the gaze
  81742. */
  81743. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81744. if (length === void 0) { length = 100; }
  81745. if (this.leftCamera) {
  81746. // Use left eye to avoid computation to compute center on every call
  81747. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81748. }
  81749. else {
  81750. return _super.prototype.getForwardRay.call(this, length);
  81751. }
  81752. };
  81753. /**
  81754. * Updates the camera based on device's frame data
  81755. */
  81756. WebVRFreeCamera.prototype._checkInputs = function () {
  81757. if (this._vrDevice && this._vrDevice.isPresenting) {
  81758. this._vrDevice.getFrameData(this._frameData);
  81759. this.updateFromDevice(this._frameData.pose);
  81760. }
  81761. _super.prototype._checkInputs.call(this);
  81762. };
  81763. /**
  81764. * Updates the poseControlled values based on the input device pose.
  81765. * @param poseData Pose coming from the device
  81766. */
  81767. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81768. if (poseData && poseData.orientation) {
  81769. this.rawPose = poseData;
  81770. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81771. if (this.getScene().useRightHandedSystem) {
  81772. this._deviceRoomRotationQuaternion.z *= -1;
  81773. this._deviceRoomRotationQuaternion.w *= -1;
  81774. }
  81775. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81776. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81777. if (this.getScene().useRightHandedSystem) {
  81778. this._deviceRoomPosition.z *= -1;
  81779. }
  81780. }
  81781. }
  81782. };
  81783. /**
  81784. * WebVR's attach control will start broadcasting frames to the device.
  81785. * Note that in certain browsers (chrome for example) this function must be called
  81786. * within a user-interaction callback. Example:
  81787. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81788. *
  81789. * @param element html element to attach the vrDevice to
  81790. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81791. */
  81792. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81793. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81794. this._attached = true;
  81795. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81796. if (this._vrDevice) {
  81797. this.getEngine().enableVR();
  81798. }
  81799. };
  81800. /**
  81801. * Detaches the camera from the html element and disables VR
  81802. *
  81803. * @param element html element to detach from
  81804. */
  81805. WebVRFreeCamera.prototype.detachControl = function (element) {
  81806. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81807. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81808. _super.prototype.detachControl.call(this, element);
  81809. this._attached = false;
  81810. this.getEngine().disableVR();
  81811. };
  81812. /**
  81813. * @returns the name of this class
  81814. */
  81815. WebVRFreeCamera.prototype.getClassName = function () {
  81816. return "WebVRFreeCamera";
  81817. };
  81818. /**
  81819. * Calls resetPose on the vrDisplay
  81820. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81821. */
  81822. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81823. //uses the vrDisplay's "resetPose()".
  81824. //pitch and roll won't be affected.
  81825. this._vrDevice.resetPose();
  81826. };
  81827. /**
  81828. * Updates the rig cameras (left and right eye)
  81829. */
  81830. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81831. var camLeft = this._rigCameras[0];
  81832. var camRight = this._rigCameras[1];
  81833. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81834. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81835. camLeft.position.copyFrom(this._deviceRoomPosition);
  81836. camRight.position.copyFrom(this._deviceRoomPosition);
  81837. };
  81838. /**
  81839. * Updates the cached values of the camera
  81840. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81841. */
  81842. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81843. var _this = this;
  81844. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81845. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81846. if (!this.updateCacheCalled) {
  81847. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81848. this.updateCacheCalled = true;
  81849. this.update();
  81850. }
  81851. // Set working vector to the device position in room space rotated by the new rotation
  81852. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81853. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81854. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81855. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81856. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81857. // Add translation from anchor position
  81858. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81859. this._workingVector.addInPlace(this.position);
  81860. this._workingVector.subtractInPlace(this._cache.position);
  81861. this._deviceToWorld.setTranslation(this._workingVector);
  81862. // Set an inverted matrix to be used when updating the camera
  81863. this._deviceToWorld.invertToRef(this._worldToDevice);
  81864. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81865. this.controllers.forEach(function (controller) {
  81866. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81867. controller.update();
  81868. });
  81869. }
  81870. if (!ignoreParentClass) {
  81871. _super.prototype._updateCache.call(this);
  81872. }
  81873. this.updateCacheCalled = false;
  81874. };
  81875. /**
  81876. * Updates the current device position and rotation in the babylon world
  81877. */
  81878. WebVRFreeCamera.prototype.update = function () {
  81879. // Get current device position in babylon world
  81880. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81881. // Get current device rotation in babylon world
  81882. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81883. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81884. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81885. _super.prototype.update.call(this);
  81886. };
  81887. /**
  81888. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81889. * @returns an identity matrix
  81890. */
  81891. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81892. return BABYLON.Matrix.Identity();
  81893. };
  81894. /**
  81895. * This function is called by the two RIG cameras.
  81896. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81897. */
  81898. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81899. var _this = this;
  81900. // Update the parent camera prior to using a child camera to avoid desynchronization
  81901. var parentCamera = this._cameraRigParams["parentCamera"];
  81902. parentCamera._updateCache();
  81903. //WebVR 1.1
  81904. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81905. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81906. if (!this.getScene().useRightHandedSystem) {
  81907. [2, 6, 8, 9, 14].forEach(function (num) {
  81908. _this._webvrViewMatrix.m[num] *= -1;
  81909. });
  81910. }
  81911. // update the camera rotation matrix
  81912. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81913. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81914. // Computing target and final matrix
  81915. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81916. // should the view matrix be updated with scale and position offset?
  81917. if (parentCamera.deviceScaleFactor !== 1) {
  81918. this._webvrViewMatrix.invert();
  81919. // scale the position, if set
  81920. if (parentCamera.deviceScaleFactor) {
  81921. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81922. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81923. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81924. }
  81925. this._webvrViewMatrix.invert();
  81926. }
  81927. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81928. return this._webvrViewMatrix;
  81929. };
  81930. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81931. var _this = this;
  81932. var parentCamera = this.parent;
  81933. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81934. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81935. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81936. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81937. //babylon compatible matrix
  81938. if (!this.getScene().useRightHandedSystem) {
  81939. [8, 9, 10, 11].forEach(function (num) {
  81940. _this._projectionMatrix.m[num] *= -1;
  81941. });
  81942. }
  81943. return this._projectionMatrix;
  81944. };
  81945. /**
  81946. * Initializes the controllers and their meshes
  81947. */
  81948. WebVRFreeCamera.prototype.initControllers = function () {
  81949. var _this = this;
  81950. this.controllers = [];
  81951. var manager = this.getScene().gamepadManager;
  81952. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81953. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81954. var webVrController = gamepad;
  81955. if (webVrController.defaultModel) {
  81956. webVrController.defaultModel.setEnabled(false);
  81957. }
  81958. if (webVrController.hand === "right") {
  81959. _this._rightController = null;
  81960. }
  81961. if (webVrController.hand === "left") {
  81962. _this._leftController = null;
  81963. }
  81964. var controllerIndex = _this.controllers.indexOf(webVrController);
  81965. if (controllerIndex !== -1) {
  81966. _this.controllers.splice(controllerIndex, 1);
  81967. }
  81968. }
  81969. });
  81970. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81971. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81972. var webVrController_1 = gamepad;
  81973. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81974. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81975. if (_this.webVROptions.controllerMeshes) {
  81976. if (webVrController_1.defaultModel) {
  81977. webVrController_1.defaultModel.setEnabled(true);
  81978. }
  81979. else {
  81980. // Load the meshes
  81981. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81982. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81983. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81984. if (_this.webVROptions.defaultLightingOnControllers) {
  81985. if (!_this._lightOnControllers) {
  81986. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81987. }
  81988. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81989. var children = mesh.getChildren();
  81990. if (children.length !== 0) {
  81991. children.forEach(function (mesh) {
  81992. light.includedOnlyMeshes.push(mesh);
  81993. activateLightOnSubMeshes_1(mesh, light);
  81994. });
  81995. }
  81996. };
  81997. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81998. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81999. }
  82000. });
  82001. }
  82002. }
  82003. webVrController_1.attachToPoseControlledCamera(_this);
  82004. // since this is async - sanity check. Is the controller already stored?
  82005. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82006. //add to the controllers array
  82007. _this.controllers.push(webVrController_1);
  82008. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82009. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82010. // So we're overriding setting left & right manually to be sure
  82011. var firstViveWandDetected = false;
  82012. for (var i = 0; i < _this.controllers.length; i++) {
  82013. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82014. if (!firstViveWandDetected) {
  82015. firstViveWandDetected = true;
  82016. _this.controllers[i].hand = "left";
  82017. }
  82018. else {
  82019. _this.controllers[i].hand = "right";
  82020. }
  82021. }
  82022. }
  82023. //did we find enough controllers? Great! let the developer know.
  82024. if (_this.controllers.length >= 2) {
  82025. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82026. }
  82027. }
  82028. }
  82029. });
  82030. };
  82031. return WebVRFreeCamera;
  82032. }(BABYLON.FreeCamera));
  82033. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82034. })(BABYLON || (BABYLON = {}));
  82035. //# sourceMappingURL=babylon.webVRCamera.js.map
  82036. "use strict";
  82037. var BABYLON;
  82038. (function (BABYLON) {
  82039. // We're mainly based on the logic defined into the FreeCamera code
  82040. /**
  82041. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82042. * being tilted forward or back and left or right.
  82043. */
  82044. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82045. __extends(DeviceOrientationCamera, _super);
  82046. /**
  82047. * Creates a new device orientation camera
  82048. * @param name The name of the camera
  82049. * @param position The start position camera
  82050. * @param scene The scene the camera belongs to
  82051. */
  82052. function DeviceOrientationCamera(name, position, scene) {
  82053. var _this = _super.call(this, name, position, scene) || this;
  82054. _this._quaternionCache = new BABYLON.Quaternion();
  82055. _this.inputs.addDeviceOrientation();
  82056. return _this;
  82057. }
  82058. /**
  82059. * Gets the current instance class name ("DeviceOrientationCamera").
  82060. * This helps avoiding instanceof at run time.
  82061. * @returns the class name
  82062. */
  82063. DeviceOrientationCamera.prototype.getClassName = function () {
  82064. return "DeviceOrientationCamera";
  82065. };
  82066. /**
  82067. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82068. */
  82069. DeviceOrientationCamera.prototype._checkInputs = function () {
  82070. _super.prototype._checkInputs.call(this);
  82071. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82072. if (this._initialQuaternion) {
  82073. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82074. }
  82075. };
  82076. /**
  82077. * Reset the camera to its default orientation on the specified axis only.
  82078. * @param axis The axis to reset
  82079. */
  82080. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82081. var _this = this;
  82082. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82083. //can only work if this camera has a rotation quaternion already.
  82084. if (!this.rotationQuaternion)
  82085. return;
  82086. if (!this._initialQuaternion) {
  82087. this._initialQuaternion = new BABYLON.Quaternion();
  82088. }
  82089. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82090. ['x', 'y', 'z'].forEach(function (axisName) {
  82091. if (!axis[axisName]) {
  82092. _this._initialQuaternion[axisName] = 0;
  82093. }
  82094. else {
  82095. _this._initialQuaternion[axisName] *= -1;
  82096. }
  82097. });
  82098. this._initialQuaternion.normalize();
  82099. //force rotation update
  82100. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82101. };
  82102. return DeviceOrientationCamera;
  82103. }(BABYLON.FreeCamera));
  82104. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82105. })(BABYLON || (BABYLON = {}));
  82106. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82107. "use strict";
  82108. var BABYLON;
  82109. (function (BABYLON) {
  82110. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82111. __extends(VRDeviceOrientationFreeCamera, _super);
  82112. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82113. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82114. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82115. var _this = _super.call(this, name, position, scene) || this;
  82116. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82117. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82118. return _this;
  82119. }
  82120. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82121. return "VRDeviceOrientationFreeCamera";
  82122. };
  82123. return VRDeviceOrientationFreeCamera;
  82124. }(BABYLON.DeviceOrientationCamera));
  82125. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82126. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82127. __extends(VRDeviceOrientationGamepadCamera, _super);
  82128. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82129. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82130. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82131. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82132. _this.inputs.addGamepad();
  82133. return _this;
  82134. }
  82135. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82136. return "VRDeviceOrientationGamepadCamera";
  82137. };
  82138. return VRDeviceOrientationGamepadCamera;
  82139. }(VRDeviceOrientationFreeCamera));
  82140. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82141. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82142. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82143. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82144. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82145. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82146. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82147. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82148. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82149. _this.inputs.addVRDeviceOrientation();
  82150. return _this;
  82151. }
  82152. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82153. return "VRDeviceOrientationArcRotateCamera";
  82154. };
  82155. return VRDeviceOrientationArcRotateCamera;
  82156. }(BABYLON.ArcRotateCamera));
  82157. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82158. })(BABYLON || (BABYLON = {}));
  82159. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82160. "use strict";
  82161. var BABYLON;
  82162. (function (BABYLON) {
  82163. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82164. __extends(AnaglyphFreeCamera, _super);
  82165. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82166. var _this = _super.call(this, name, position, scene) || this;
  82167. _this.interaxialDistance = interaxialDistance;
  82168. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82169. return _this;
  82170. }
  82171. AnaglyphFreeCamera.prototype.getClassName = function () {
  82172. return "AnaglyphFreeCamera";
  82173. };
  82174. return AnaglyphFreeCamera;
  82175. }(BABYLON.FreeCamera));
  82176. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82177. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82178. __extends(AnaglyphArcRotateCamera, _super);
  82179. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82180. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82181. _this.interaxialDistance = interaxialDistance;
  82182. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82183. return _this;
  82184. }
  82185. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82186. return "AnaglyphArcRotateCamera";
  82187. };
  82188. return AnaglyphArcRotateCamera;
  82189. }(BABYLON.ArcRotateCamera));
  82190. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82191. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82192. __extends(AnaglyphGamepadCamera, _super);
  82193. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82194. var _this = _super.call(this, name, position, scene) || this;
  82195. _this.interaxialDistance = interaxialDistance;
  82196. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82197. return _this;
  82198. }
  82199. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82200. return "AnaglyphGamepadCamera";
  82201. };
  82202. return AnaglyphGamepadCamera;
  82203. }(BABYLON.GamepadCamera));
  82204. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82205. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82206. __extends(AnaglyphUniversalCamera, _super);
  82207. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82208. var _this = _super.call(this, name, position, scene) || this;
  82209. _this.interaxialDistance = interaxialDistance;
  82210. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82211. return _this;
  82212. }
  82213. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82214. return "AnaglyphUniversalCamera";
  82215. };
  82216. return AnaglyphUniversalCamera;
  82217. }(BABYLON.UniversalCamera));
  82218. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82219. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82220. __extends(StereoscopicFreeCamera, _super);
  82221. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82222. var _this = _super.call(this, name, position, scene) || this;
  82223. _this.interaxialDistance = interaxialDistance;
  82224. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82225. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82226. return _this;
  82227. }
  82228. StereoscopicFreeCamera.prototype.getClassName = function () {
  82229. return "StereoscopicFreeCamera";
  82230. };
  82231. return StereoscopicFreeCamera;
  82232. }(BABYLON.FreeCamera));
  82233. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82234. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82235. __extends(StereoscopicArcRotateCamera, _super);
  82236. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82237. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82238. _this.interaxialDistance = interaxialDistance;
  82239. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82240. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82241. return _this;
  82242. }
  82243. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82244. return "StereoscopicArcRotateCamera";
  82245. };
  82246. return StereoscopicArcRotateCamera;
  82247. }(BABYLON.ArcRotateCamera));
  82248. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82249. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82250. __extends(StereoscopicGamepadCamera, _super);
  82251. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82252. var _this = _super.call(this, name, position, scene) || this;
  82253. _this.interaxialDistance = interaxialDistance;
  82254. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82255. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82256. return _this;
  82257. }
  82258. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82259. return "StereoscopicGamepadCamera";
  82260. };
  82261. return StereoscopicGamepadCamera;
  82262. }(BABYLON.GamepadCamera));
  82263. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82264. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82265. __extends(StereoscopicUniversalCamera, _super);
  82266. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82267. var _this = _super.call(this, name, position, scene) || this;
  82268. _this.interaxialDistance = interaxialDistance;
  82269. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82270. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82271. return _this;
  82272. }
  82273. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82274. return "StereoscopicUniversalCamera";
  82275. };
  82276. return StereoscopicUniversalCamera;
  82277. }(BABYLON.UniversalCamera));
  82278. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82279. })(BABYLON || (BABYLON = {}));
  82280. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82281. "use strict";
  82282. var BABYLON;
  82283. (function (BABYLON) {
  82284. var VRExperienceHelperGazer = /** @class */ (function () {
  82285. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82286. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82287. this.scene = scene;
  82288. this._pointerDownOnMeshAsked = false;
  82289. this._isActionableMesh = false;
  82290. this._teleportationRequestInitiated = false;
  82291. this._teleportationBackRequestInitiated = false;
  82292. this._dpadPressed = true;
  82293. this._activePointer = false;
  82294. this._id = VRExperienceHelperGazer._idCounter++;
  82295. // Gaze tracker
  82296. if (!gazeTrackerToClone) {
  82297. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82298. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82299. this._gazeTracker.isPickable = false;
  82300. this._gazeTracker.isVisible = false;
  82301. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82302. targetMat.specularColor = BABYLON.Color3.Black();
  82303. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82304. targetMat.backFaceCulling = false;
  82305. this._gazeTracker.material = targetMat;
  82306. }
  82307. else {
  82308. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82309. }
  82310. }
  82311. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82312. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82313. };
  82314. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82315. this._pointerDownOnMeshAsked = true;
  82316. if (this._currentMeshSelected && this._currentHit) {
  82317. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82318. }
  82319. };
  82320. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82321. if (this._currentMeshSelected && this._currentHit) {
  82322. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82323. }
  82324. this._pointerDownOnMeshAsked = false;
  82325. };
  82326. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82327. this._activePointer = true;
  82328. };
  82329. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82330. this._activePointer = false;
  82331. };
  82332. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82333. };
  82334. VRExperienceHelperGazer.prototype.dispose = function () {
  82335. this._interactionsEnabled = false;
  82336. this._teleportationEnabled = false;
  82337. };
  82338. VRExperienceHelperGazer._idCounter = 0;
  82339. return VRExperienceHelperGazer;
  82340. }());
  82341. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82342. __extends(VRExperienceHelperControllerGazer, _super);
  82343. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82344. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82345. _this.webVRController = webVRController;
  82346. // Laser pointer
  82347. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82348. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82349. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82350. laserPointerMaterial.alpha = 0.6;
  82351. _this._laserPointer.material = laserPointerMaterial;
  82352. _this._laserPointer.rotation.x = Math.PI / 2;
  82353. _this._laserPointer.position.z = -0.5;
  82354. _this._laserPointer.isVisible = false;
  82355. if (!webVRController.mesh) {
  82356. // Create an empty mesh that is used prior to loading the high quality model
  82357. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82358. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82359. preloadPointerPose.rotation.x = -0.7;
  82360. preloadMesh.addChild(preloadPointerPose);
  82361. webVRController.attachToMesh(preloadMesh);
  82362. }
  82363. _this._setLaserPointerParent(webVRController.mesh);
  82364. return _this;
  82365. }
  82366. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82367. return this.webVRController.getForwardRay(length);
  82368. };
  82369. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82370. _super.prototype._activatePointer.call(this);
  82371. this._laserPointer.isVisible = true;
  82372. };
  82373. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82374. _super.prototype._deactivatePointer.call(this);
  82375. this._laserPointer.isVisible = false;
  82376. };
  82377. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82378. this._laserPointer.material.emissiveColor = color;
  82379. };
  82380. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82381. var makeNotPick = function (root) {
  82382. root.name += " laserPointer";
  82383. root.getChildMeshes().forEach(function (c) {
  82384. makeNotPick(c);
  82385. });
  82386. };
  82387. makeNotPick(mesh);
  82388. var childMeshes = mesh.getChildMeshes();
  82389. this.webVRController._pointingPoseNode = null;
  82390. for (var i = 0; i < childMeshes.length; i++) {
  82391. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82392. mesh = childMeshes[i];
  82393. this.webVRController._pointingPoseNode = mesh;
  82394. break;
  82395. }
  82396. }
  82397. this._laserPointer.parent = mesh;
  82398. };
  82399. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82400. this._laserPointer.scaling.y = distance;
  82401. this._laserPointer.position.z = -distance / 2;
  82402. };
  82403. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82404. _super.prototype.dispose.call(this);
  82405. this._laserPointer.dispose();
  82406. };
  82407. return VRExperienceHelperControllerGazer;
  82408. }(VRExperienceHelperGazer));
  82409. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82410. __extends(VRExperienceHelperCameraGazer, _super);
  82411. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82412. var _this = _super.call(this, scene) || this;
  82413. _this.getCamera = getCamera;
  82414. return _this;
  82415. }
  82416. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82417. var camera = this.getCamera();
  82418. if (camera) {
  82419. return camera.getForwardRay(length);
  82420. }
  82421. else {
  82422. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82423. }
  82424. };
  82425. return VRExperienceHelperCameraGazer;
  82426. }(VRExperienceHelperGazer));
  82427. /**
  82428. * Helps to quickly add VR support to an existing scene.
  82429. * See http://doc.babylonjs.com/how_to/webvr_helper
  82430. */
  82431. var VRExperienceHelper = /** @class */ (function () {
  82432. /**
  82433. * Instantiates a VRExperienceHelper.
  82434. * Helps to quickly add VR support to an existing scene.
  82435. * @param scene The scene the VRExperienceHelper belongs to.
  82436. * @param webVROptions Options to modify the vr experience helper's behavior.
  82437. */
  82438. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82439. if (webVROptions === void 0) { webVROptions = {}; }
  82440. var _this = this;
  82441. this.webVROptions = webVROptions;
  82442. // Can the system support WebVR, even if a headset isn't plugged in?
  82443. this._webVRsupported = false;
  82444. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82445. this._webVRready = false;
  82446. // Are we waiting for the requestPresent callback to complete?
  82447. this._webVRrequesting = false;
  82448. // Are we presenting to the headset right now?
  82449. this._webVRpresenting = false;
  82450. // Are we presenting in the fullscreen fallback?
  82451. this._fullscreenVRpresenting = false;
  82452. /**
  82453. * Observable raised when entering VR.
  82454. */
  82455. this.onEnteringVRObservable = new BABYLON.Observable();
  82456. /**
  82457. * Observable raised when exiting VR.
  82458. */
  82459. this.onExitingVRObservable = new BABYLON.Observable();
  82460. /**
  82461. * Observable raised when controller mesh is loaded.
  82462. */
  82463. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82464. this._useCustomVRButton = false;
  82465. this._teleportationRequested = false;
  82466. this._teleportActive = false;
  82467. this._floorMeshesCollection = [];
  82468. this._rotationAllowed = true;
  82469. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82470. this._rotationRightAsked = false;
  82471. this._rotationLeftAsked = false;
  82472. this._isDefaultTeleportationTarget = true;
  82473. this._teleportationFillColor = "#444444";
  82474. this._teleportationBorderColor = "#FFFFFF";
  82475. this._rotationAngle = 0;
  82476. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82477. this._padSensibilityUp = 0.65;
  82478. this._padSensibilityDown = 0.35;
  82479. this.leftController = null;
  82480. this.rightController = null;
  82481. /**
  82482. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82483. */
  82484. this.onNewMeshSelected = new BABYLON.Observable();
  82485. /**
  82486. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82487. */
  82488. this.onNewMeshPicked = new BABYLON.Observable();
  82489. /**
  82490. * Observable raised before camera teleportation
  82491. */
  82492. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82493. /**
  82494. * Observable raised after camera teleportation
  82495. */
  82496. this.onAfterCameraTeleport = new BABYLON.Observable();
  82497. /**
  82498. * Observable raised when current selected mesh gets unselected
  82499. */
  82500. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82501. /**
  82502. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82503. */
  82504. this.teleportationEnabled = true;
  82505. this._teleportationInitialized = false;
  82506. this._interactionsEnabled = false;
  82507. this._interactionsRequested = false;
  82508. this._displayGaze = true;
  82509. this._displayLaserPointer = true;
  82510. this._onResize = function () {
  82511. _this.moveButtonToBottomRight();
  82512. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82513. _this.exitVR();
  82514. }
  82515. };
  82516. this._onFullscreenChange = function () {
  82517. if (document.fullscreen !== undefined) {
  82518. _this._fullscreenVRpresenting = document.fullscreen;
  82519. }
  82520. else if (document.mozFullScreen !== undefined) {
  82521. _this._fullscreenVRpresenting = document.mozFullScreen;
  82522. }
  82523. else if (document.webkitIsFullScreen !== undefined) {
  82524. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82525. }
  82526. else if (document.msIsFullScreen !== undefined) {
  82527. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82528. }
  82529. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82530. _this.exitVR();
  82531. if (!_this._useCustomVRButton) {
  82532. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82533. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82534. }
  82535. }
  82536. };
  82537. this.beforeRender = function () {
  82538. if (_this.leftController && _this.leftController._activePointer) {
  82539. _this._castRayAndSelectObject(_this.leftController);
  82540. }
  82541. if (_this.rightController && _this.rightController._activePointer) {
  82542. _this._castRayAndSelectObject(_this.rightController);
  82543. }
  82544. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82545. _this._castRayAndSelectObject(_this._cameraGazer);
  82546. }
  82547. else {
  82548. _this._cameraGazer._gazeTracker.isVisible = false;
  82549. }
  82550. };
  82551. this._onNewGamepadConnected = function (gamepad) {
  82552. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82553. if (gamepad.leftStick) {
  82554. gamepad.onleftstickchanged(function (stickValues) {
  82555. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82556. // Listening to classic/xbox gamepad only if no VR controller is active
  82557. if ((!_this.leftController && !_this.rightController) ||
  82558. ((_this.leftController && !_this.leftController._activePointer) &&
  82559. (_this.rightController && !_this.rightController._activePointer))) {
  82560. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82561. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82562. }
  82563. }
  82564. });
  82565. }
  82566. if (gamepad.rightStick) {
  82567. gamepad.onrightstickchanged(function (stickValues) {
  82568. if (_this._teleportationInitialized) {
  82569. _this._checkRotate(stickValues, _this._cameraGazer);
  82570. }
  82571. });
  82572. }
  82573. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82574. gamepad.onbuttondown(function (buttonPressed) {
  82575. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82576. _this._cameraGazer._selectionPointerDown();
  82577. }
  82578. });
  82579. gamepad.onbuttonup(function (buttonPressed) {
  82580. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82581. _this._cameraGazer._selectionPointerUp();
  82582. }
  82583. });
  82584. }
  82585. }
  82586. else {
  82587. var webVRController = gamepad;
  82588. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82589. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82590. _this.rightController = controller;
  82591. }
  82592. else {
  82593. _this.leftController = controller;
  82594. }
  82595. _this._tryEnableInteractionOnController(controller);
  82596. }
  82597. };
  82598. // 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
  82599. this._tryEnableInteractionOnController = function (controller) {
  82600. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82601. _this._enableInteractionOnController(controller);
  82602. }
  82603. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82604. _this._enableTeleportationOnController(controller);
  82605. }
  82606. };
  82607. this._onNewGamepadDisconnected = function (gamepad) {
  82608. if (gamepad instanceof BABYLON.WebVRController) {
  82609. if (gamepad.hand === "left" && _this.leftController != null) {
  82610. _this.leftController.dispose();
  82611. _this.leftController = null;
  82612. }
  82613. if (gamepad.hand === "right" && _this.rightController != null) {
  82614. _this.rightController.dispose();
  82615. _this.rightController = null;
  82616. }
  82617. }
  82618. };
  82619. this._workingVector = BABYLON.Vector3.Zero();
  82620. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82621. this._workingMatrix = BABYLON.Matrix.Identity();
  82622. this._scene = scene;
  82623. this._canvas = scene.getEngine().getRenderingCanvas();
  82624. // Parse options
  82625. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82626. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82627. }
  82628. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82629. webVROptions.createDeviceOrientationCamera = true;
  82630. }
  82631. if (webVROptions.defaultHeight === undefined) {
  82632. webVROptions.defaultHeight = 1.7;
  82633. }
  82634. if (webVROptions.useCustomVRButton) {
  82635. this._useCustomVRButton = true;
  82636. if (webVROptions.customVRButton) {
  82637. this._btnVR = webVROptions.customVRButton;
  82638. }
  82639. }
  82640. if (webVROptions.rayLength) {
  82641. this._rayLength = webVROptions.rayLength;
  82642. }
  82643. this._defaultHeight = webVROptions.defaultHeight;
  82644. if (webVROptions.positionScale) {
  82645. this._rayLength *= webVROptions.positionScale;
  82646. this._defaultHeight *= webVROptions.positionScale;
  82647. }
  82648. // Set position
  82649. if (this._scene.activeCamera) {
  82650. this._position = this._scene.activeCamera.position.clone();
  82651. }
  82652. else {
  82653. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82654. }
  82655. // Set non-vr camera
  82656. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82657. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82658. // Copy data from existing camera
  82659. if (this._scene.activeCamera) {
  82660. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82661. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82662. // Set rotation from previous camera
  82663. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82664. var targetCamera = this._scene.activeCamera;
  82665. if (targetCamera.rotationQuaternion) {
  82666. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82667. }
  82668. else {
  82669. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82670. }
  82671. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82672. }
  82673. }
  82674. this._scene.activeCamera = this._deviceOrientationCamera;
  82675. if (this._canvas) {
  82676. this._scene.activeCamera.attachControl(this._canvas);
  82677. }
  82678. }
  82679. else {
  82680. this._existingCamera = this._scene.activeCamera;
  82681. }
  82682. // Create VR cameras
  82683. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82684. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82685. }
  82686. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82687. this._webVRCamera.useStandingMatrix();
  82688. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82689. // Create default button
  82690. if (!this._useCustomVRButton) {
  82691. this._btnVR = document.createElement("BUTTON");
  82692. this._btnVR.className = "babylonVRicon";
  82693. this._btnVR.id = "babylonVRiconbtn";
  82694. this._btnVR.title = "Click to switch to VR";
  82695. 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) }";
  82696. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82697. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82698. // css += ".babylonVRicon.vrdisplaysupported { }";
  82699. // css += ".babylonVRicon.vrdisplayready { }";
  82700. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82701. var style = document.createElement('style');
  82702. style.appendChild(document.createTextNode(css));
  82703. document.getElementsByTagName('head')[0].appendChild(style);
  82704. this.moveButtonToBottomRight();
  82705. }
  82706. // VR button click event
  82707. if (this._btnVR) {
  82708. this._btnVR.addEventListener("click", function () {
  82709. if (!_this.isInVRMode) {
  82710. _this.enterVR();
  82711. }
  82712. else {
  82713. _this.exitVR();
  82714. }
  82715. });
  82716. }
  82717. // Window events
  82718. window.addEventListener("resize", this._onResize);
  82719. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82720. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82721. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82722. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82723. // Display vr button when headset is connected
  82724. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82725. this.displayVRButton();
  82726. }
  82727. else {
  82728. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82729. if (e.vrDisplay) {
  82730. _this.displayVRButton();
  82731. }
  82732. });
  82733. }
  82734. // Exiting VR mode using 'ESC' key on desktop
  82735. this._onKeyDown = function (event) {
  82736. if (event.keyCode === 27 && _this.isInVRMode) {
  82737. _this.exitVR();
  82738. }
  82739. };
  82740. document.addEventListener("keydown", this._onKeyDown);
  82741. // Exiting VR mode double tapping the touch screen
  82742. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82743. if (_this.isInVRMode) {
  82744. _this.exitVR();
  82745. if (_this._fullscreenVRpresenting) {
  82746. _this._scene.getEngine().switchFullscreen(true);
  82747. }
  82748. }
  82749. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82750. // Listen for WebVR display changes
  82751. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82752. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82753. this._onVRRequestPresentStart = function () {
  82754. _this._webVRrequesting = true;
  82755. _this.updateButtonVisibility();
  82756. };
  82757. this._onVRRequestPresentComplete = function (success) {
  82758. _this._webVRrequesting = false;
  82759. _this.updateButtonVisibility();
  82760. };
  82761. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82762. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82763. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82764. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82765. scene.onDisposeObservable.add(function () {
  82766. _this.dispose();
  82767. });
  82768. // Gamepad connection events
  82769. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82770. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82771. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82772. this.updateButtonVisibility();
  82773. //create easing functions
  82774. this._circleEase = new BABYLON.CircleEase();
  82775. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82776. }
  82777. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82778. /** Return this.onEnteringVRObservable
  82779. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82780. */
  82781. get: function () {
  82782. return this.onEnteringVRObservable;
  82783. },
  82784. enumerable: true,
  82785. configurable: true
  82786. });
  82787. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82788. /** Return this.onExitingVRObservable
  82789. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82790. */
  82791. get: function () {
  82792. return this.onExitingVRObservable;
  82793. },
  82794. enumerable: true,
  82795. configurable: true
  82796. });
  82797. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82798. /** Return this.onControllerMeshLoadedObservable
  82799. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82800. */
  82801. get: function () {
  82802. return this.onControllerMeshLoadedObservable;
  82803. },
  82804. enumerable: true,
  82805. configurable: true
  82806. });
  82807. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82808. /**
  82809. * The mesh used to display where the user is going to teleport.
  82810. */
  82811. get: function () {
  82812. return this._teleportationTarget;
  82813. },
  82814. /**
  82815. * Sets the mesh to be used to display where the user is going to teleport.
  82816. */
  82817. set: function (value) {
  82818. if (value) {
  82819. value.name = "teleportationTarget";
  82820. this._isDefaultTeleportationTarget = false;
  82821. this._teleportationTarget = value;
  82822. }
  82823. },
  82824. enumerable: true,
  82825. configurable: true
  82826. });
  82827. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82828. /**
  82829. * The mesh used to display where the user is selecting,
  82830. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82831. * See http://doc.babylonjs.com/resources/baking_transformations
  82832. */
  82833. get: function () {
  82834. return this._cameraGazer._gazeTracker;
  82835. },
  82836. set: function (value) {
  82837. if (value) {
  82838. this._cameraGazer._gazeTracker = value;
  82839. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82840. this._cameraGazer._gazeTracker.isPickable = false;
  82841. this._cameraGazer._gazeTracker.isVisible = false;
  82842. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82843. if (this.leftController) {
  82844. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82845. }
  82846. if (this.rightController) {
  82847. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82848. }
  82849. }
  82850. },
  82851. enumerable: true,
  82852. configurable: true
  82853. });
  82854. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82855. /**
  82856. * If the ray of the gaze should be displayed.
  82857. */
  82858. get: function () {
  82859. return this._displayGaze;
  82860. },
  82861. /**
  82862. * Sets if the ray of the gaze should be displayed.
  82863. */
  82864. set: function (value) {
  82865. this._displayGaze = value;
  82866. if (!value) {
  82867. this._cameraGazer._gazeTracker.isVisible = false;
  82868. if (this.leftController) {
  82869. this.leftController._gazeTracker.isVisible = false;
  82870. }
  82871. if (this.rightController) {
  82872. this.rightController._gazeTracker.isVisible = false;
  82873. }
  82874. }
  82875. },
  82876. enumerable: true,
  82877. configurable: true
  82878. });
  82879. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82880. /**
  82881. * If the ray of the LaserPointer should be displayed.
  82882. */
  82883. get: function () {
  82884. return this._displayLaserPointer;
  82885. },
  82886. /**
  82887. * Sets if the ray of the LaserPointer should be displayed.
  82888. */
  82889. set: function (value) {
  82890. this._displayLaserPointer = value;
  82891. if (!value) {
  82892. if (this.rightController) {
  82893. this.rightController._deactivatePointer();
  82894. this.rightController._gazeTracker.isVisible = false;
  82895. }
  82896. if (this.leftController) {
  82897. this.leftController._deactivatePointer();
  82898. this.leftController._gazeTracker.isVisible = false;
  82899. }
  82900. }
  82901. else {
  82902. if (this.rightController) {
  82903. this.rightController._activatePointer();
  82904. }
  82905. else if (this.leftController) {
  82906. this.leftController._activatePointer();
  82907. }
  82908. }
  82909. },
  82910. enumerable: true,
  82911. configurable: true
  82912. });
  82913. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82914. /**
  82915. * The deviceOrientationCamera used as the camera when not in VR.
  82916. */
  82917. get: function () {
  82918. return this._deviceOrientationCamera;
  82919. },
  82920. enumerable: true,
  82921. configurable: true
  82922. });
  82923. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82924. /**
  82925. * Based on the current WebVR support, returns the current VR camera used.
  82926. */
  82927. get: function () {
  82928. if (this._webVRready) {
  82929. return this._webVRCamera;
  82930. }
  82931. else {
  82932. return this._scene.activeCamera;
  82933. }
  82934. },
  82935. enumerable: true,
  82936. configurable: true
  82937. });
  82938. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82939. /**
  82940. * The webVRCamera which is used when in VR.
  82941. */
  82942. get: function () {
  82943. return this._webVRCamera;
  82944. },
  82945. enumerable: true,
  82946. configurable: true
  82947. });
  82948. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82949. /**
  82950. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82951. */
  82952. get: function () {
  82953. return this._vrDeviceOrientationCamera;
  82954. },
  82955. enumerable: true,
  82956. configurable: true
  82957. });
  82958. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82959. get: function () {
  82960. var result = this._cameraGazer._teleportationRequestInitiated
  82961. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82962. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82963. return result;
  82964. },
  82965. enumerable: true,
  82966. configurable: true
  82967. });
  82968. // Raised when one of the controller has loaded successfully its associated default mesh
  82969. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82970. if (this.leftController && this.leftController.webVRController == webVRController) {
  82971. if (webVRController.mesh) {
  82972. this.leftController._setLaserPointerParent(webVRController.mesh);
  82973. }
  82974. }
  82975. if (this.rightController && this.rightController.webVRController == webVRController) {
  82976. if (webVRController.mesh) {
  82977. this.rightController._setLaserPointerParent(webVRController.mesh);
  82978. }
  82979. }
  82980. try {
  82981. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82982. }
  82983. catch (err) {
  82984. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82985. }
  82986. };
  82987. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82988. /**
  82989. * Gets a value indicating if we are currently in VR mode.
  82990. */
  82991. get: function () {
  82992. return this._webVRpresenting || this._fullscreenVRpresenting;
  82993. },
  82994. enumerable: true,
  82995. configurable: true
  82996. });
  82997. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82998. var vrDisplay = this._scene.getEngine().getVRDevice();
  82999. if (vrDisplay) {
  83000. var wasPresenting = this._webVRpresenting;
  83001. // A VR display is connected
  83002. this._webVRpresenting = vrDisplay.isPresenting;
  83003. if (wasPresenting && !this._webVRpresenting)
  83004. this.exitVR();
  83005. }
  83006. else {
  83007. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83008. }
  83009. this.updateButtonVisibility();
  83010. };
  83011. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83012. this._webVRsupported = eventArgs.vrSupported;
  83013. this._webVRready = !!eventArgs.vrDisplay;
  83014. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83015. this.updateButtonVisibility();
  83016. };
  83017. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83018. if (this._canvas && !this._useCustomVRButton) {
  83019. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83020. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83021. }
  83022. };
  83023. VRExperienceHelper.prototype.displayVRButton = function () {
  83024. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83025. document.body.appendChild(this._btnVR);
  83026. this._btnVRDisplayed = true;
  83027. }
  83028. };
  83029. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83030. if (!this._btnVR || this._useCustomVRButton) {
  83031. return;
  83032. }
  83033. this._btnVR.className = "babylonVRicon";
  83034. if (this.isInVRMode) {
  83035. this._btnVR.className += " vrdisplaypresenting";
  83036. }
  83037. else {
  83038. if (this._webVRready)
  83039. this._btnVR.className += " vrdisplayready";
  83040. if (this._webVRsupported)
  83041. this._btnVR.className += " vrdisplaysupported";
  83042. if (this._webVRrequesting)
  83043. this._btnVR.className += " vrdisplayrequesting";
  83044. }
  83045. };
  83046. /**
  83047. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83048. * Otherwise, will use the fullscreen API.
  83049. */
  83050. VRExperienceHelper.prototype.enterVR = function () {
  83051. if (this.onEnteringVRObservable) {
  83052. try {
  83053. this.onEnteringVRObservable.notifyObservers(this);
  83054. }
  83055. catch (err) {
  83056. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83057. }
  83058. }
  83059. if (this._scene.activeCamera) {
  83060. this._position = this._scene.activeCamera.position.clone();
  83061. // make sure that we return to the last active camera
  83062. this._existingCamera = this._scene.activeCamera;
  83063. }
  83064. if (this._webVRrequesting)
  83065. return;
  83066. // If WebVR is supported and a headset is connected
  83067. if (this._webVRready) {
  83068. if (!this._webVRpresenting) {
  83069. this._webVRCamera.position = this._position;
  83070. this._scene.activeCamera = this._webVRCamera;
  83071. }
  83072. }
  83073. else if (this._vrDeviceOrientationCamera) {
  83074. this._vrDeviceOrientationCamera.position = this._position;
  83075. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83076. this._scene.getEngine().switchFullscreen(true);
  83077. this.updateButtonVisibility();
  83078. }
  83079. if (this._scene.activeCamera && this._canvas) {
  83080. this._scene.activeCamera.attachControl(this._canvas);
  83081. }
  83082. if (this._interactionsEnabled) {
  83083. this._scene.registerBeforeRender(this.beforeRender);
  83084. }
  83085. };
  83086. /**
  83087. * Attempt to exit VR, or fullscreen.
  83088. */
  83089. VRExperienceHelper.prototype.exitVR = function () {
  83090. if (this.onExitingVRObservable) {
  83091. try {
  83092. this.onExitingVRObservable.notifyObservers(this);
  83093. }
  83094. catch (err) {
  83095. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83096. }
  83097. }
  83098. if (this._webVRpresenting) {
  83099. this._scene.getEngine().disableVR();
  83100. }
  83101. if (this._scene.activeCamera) {
  83102. this._position = this._scene.activeCamera.position.clone();
  83103. }
  83104. if (this._deviceOrientationCamera) {
  83105. this._deviceOrientationCamera.position = this._position;
  83106. this._scene.activeCamera = this._deviceOrientationCamera;
  83107. if (this._canvas) {
  83108. this._scene.activeCamera.attachControl(this._canvas);
  83109. }
  83110. }
  83111. else if (this._existingCamera) {
  83112. this._existingCamera.position = this._position;
  83113. this._scene.activeCamera = this._existingCamera;
  83114. }
  83115. this.updateButtonVisibility();
  83116. if (this._interactionsEnabled) {
  83117. this._scene.unregisterBeforeRender(this.beforeRender);
  83118. }
  83119. };
  83120. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83121. /**
  83122. * The position of the vr experience helper.
  83123. */
  83124. get: function () {
  83125. return this._position;
  83126. },
  83127. /**
  83128. * Sets the position of the vr experience helper.
  83129. */
  83130. set: function (value) {
  83131. this._position = value;
  83132. if (this._scene.activeCamera) {
  83133. this._scene.activeCamera.position = value;
  83134. }
  83135. },
  83136. enumerable: true,
  83137. configurable: true
  83138. });
  83139. /**
  83140. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83141. */
  83142. VRExperienceHelper.prototype.enableInteractions = function () {
  83143. var _this = this;
  83144. if (!this._interactionsEnabled) {
  83145. this._interactionsRequested = true;
  83146. if (this.leftController) {
  83147. this._enableInteractionOnController(this.leftController);
  83148. }
  83149. if (this.rightController) {
  83150. this._enableInteractionOnController(this.rightController);
  83151. }
  83152. this.raySelectionPredicate = function (mesh) {
  83153. return mesh.isVisible;
  83154. };
  83155. this.meshSelectionPredicate = function (mesh) {
  83156. return true;
  83157. };
  83158. this._raySelectionPredicate = function (mesh) {
  83159. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83160. && mesh.name.indexOf("teleportationTarget") === -1
  83161. && mesh.name.indexOf("torusTeleportation") === -1
  83162. && mesh.name.indexOf("laserPointer") === -1)) {
  83163. return _this.raySelectionPredicate(mesh);
  83164. }
  83165. return false;
  83166. };
  83167. this._interactionsEnabled = true;
  83168. }
  83169. };
  83170. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83171. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83172. if (this._floorMeshesCollection[i].id === mesh.id) {
  83173. return true;
  83174. }
  83175. }
  83176. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83177. return true;
  83178. }
  83179. return false;
  83180. };
  83181. /**
  83182. * Adds a floor mesh to be used for teleportation.
  83183. * @param floorMesh the mesh to be used for teleportation.
  83184. */
  83185. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83186. if (!this._floorMeshesCollection) {
  83187. return;
  83188. }
  83189. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83190. return;
  83191. }
  83192. this._floorMeshesCollection.push(floorMesh);
  83193. };
  83194. /**
  83195. * Removes a floor mesh from being used for teleportation.
  83196. * @param floorMesh the mesh to be removed.
  83197. */
  83198. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83199. if (!this._floorMeshesCollection) {
  83200. return;
  83201. }
  83202. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83203. if (meshIndex !== -1) {
  83204. this._floorMeshesCollection.splice(meshIndex, 1);
  83205. }
  83206. };
  83207. /**
  83208. * Enables interactions and teleportation using the VR controllers and gaze.
  83209. * @param vrTeleportationOptions options to modify teleportation behavior.
  83210. */
  83211. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83212. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83213. if (!this._teleportationInitialized) {
  83214. this._teleportationRequested = true;
  83215. this.enableInteractions();
  83216. if (vrTeleportationOptions.floorMeshName) {
  83217. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83218. }
  83219. if (vrTeleportationOptions.floorMeshes) {
  83220. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83221. }
  83222. if (this.leftController != null) {
  83223. this._enableTeleportationOnController(this.leftController);
  83224. }
  83225. if (this.rightController != null) {
  83226. this._enableTeleportationOnController(this.rightController);
  83227. }
  83228. // Creates an image processing post process for the vignette not relying
  83229. // on the main scene configuration for image processing to reduce setup and spaces
  83230. // (gamma/linear) conflicts.
  83231. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83232. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83233. imageProcessingConfiguration.vignetteEnabled = true;
  83234. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83235. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83236. this._teleportationInitialized = true;
  83237. if (this._isDefaultTeleportationTarget) {
  83238. this._createTeleportationCircles();
  83239. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83240. }
  83241. }
  83242. };
  83243. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83244. var _this = this;
  83245. var controllerMesh = controller.webVRController.mesh;
  83246. if (controllerMesh) {
  83247. controller._interactionsEnabled = true;
  83248. controller._activatePointer();
  83249. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83250. // Enabling / disabling laserPointer
  83251. if (_this._displayLaserPointer && stateObject.value === 1) {
  83252. if (controller._activePointer) {
  83253. controller._deactivatePointer();
  83254. }
  83255. else {
  83256. controller._activatePointer();
  83257. }
  83258. if (_this.displayGaze) {
  83259. controller._gazeTracker.isVisible = controller._activePointer;
  83260. }
  83261. }
  83262. });
  83263. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83264. if (!controller._pointerDownOnMeshAsked) {
  83265. if (stateObject.value > _this._padSensibilityUp) {
  83266. controller._selectionPointerDown();
  83267. }
  83268. }
  83269. else if (stateObject.value < _this._padSensibilityDown) {
  83270. controller._selectionPointerUp();
  83271. }
  83272. });
  83273. }
  83274. };
  83275. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83276. // Dont teleport if another gaze already requested teleportation
  83277. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83278. return;
  83279. }
  83280. if (!gazer._teleportationRequestInitiated) {
  83281. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83282. gazer._activatePointer();
  83283. gazer._teleportationRequestInitiated = true;
  83284. }
  83285. }
  83286. else {
  83287. // Listening to the proper controller values changes to confirm teleportation
  83288. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83289. if (this._teleportActive) {
  83290. this._teleportCamera(this._haloCenter);
  83291. }
  83292. gazer._teleportationRequestInitiated = false;
  83293. }
  83294. }
  83295. };
  83296. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83297. // Only rotate when user is not currently selecting a teleportation location
  83298. if (gazer._teleportationRequestInitiated) {
  83299. return;
  83300. }
  83301. if (!this._rotationLeftAsked) {
  83302. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83303. this._rotationLeftAsked = true;
  83304. if (this._rotationAllowed) {
  83305. this._rotateCamera(false);
  83306. }
  83307. }
  83308. }
  83309. else {
  83310. if (stateObject.x > -this._padSensibilityDown) {
  83311. this._rotationLeftAsked = false;
  83312. }
  83313. }
  83314. if (!this._rotationRightAsked) {
  83315. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83316. this._rotationRightAsked = true;
  83317. if (this._rotationAllowed) {
  83318. this._rotateCamera(true);
  83319. }
  83320. }
  83321. }
  83322. else {
  83323. if (stateObject.x < this._padSensibilityDown) {
  83324. this._rotationRightAsked = false;
  83325. }
  83326. }
  83327. };
  83328. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83329. // Only teleport backwards when user is not currently selecting a teleportation location
  83330. if (gazer._teleportationRequestInitiated) {
  83331. return;
  83332. }
  83333. // Teleport backwards
  83334. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83335. if (!gazer._teleportationBackRequestInitiated) {
  83336. if (!this.currentVRCamera) {
  83337. return;
  83338. }
  83339. // Get rotation and position of the current camera
  83340. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83341. var position = this.currentVRCamera.position;
  83342. // If the camera has device position, use that instead
  83343. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83344. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83345. position = this.currentVRCamera.devicePosition;
  83346. }
  83347. // Get matrix with only the y rotation of the device rotation
  83348. rotation.toEulerAnglesToRef(this._workingVector);
  83349. this._workingVector.z = 0;
  83350. this._workingVector.x = 0;
  83351. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83352. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83353. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83354. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83355. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83356. var ray = new BABYLON.Ray(position, this._workingVector);
  83357. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83358. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83359. this._teleportCamera(hit.pickedPoint);
  83360. }
  83361. gazer._teleportationBackRequestInitiated = true;
  83362. }
  83363. }
  83364. else {
  83365. gazer._teleportationBackRequestInitiated = false;
  83366. }
  83367. };
  83368. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83369. var _this = this;
  83370. var controllerMesh = controller.webVRController.mesh;
  83371. if (controllerMesh) {
  83372. if (!controller._interactionsEnabled) {
  83373. this._enableInteractionOnController(controller);
  83374. }
  83375. controller._interactionsEnabled = true;
  83376. controller._teleportationEnabled = true;
  83377. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83378. controller._dpadPressed = false;
  83379. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83380. controller._dpadPressed = stateObject.pressed;
  83381. if (!controller._dpadPressed) {
  83382. _this._rotationLeftAsked = false;
  83383. _this._rotationRightAsked = false;
  83384. controller._teleportationBackRequestInitiated = false;
  83385. }
  83386. });
  83387. }
  83388. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83389. if (_this.teleportationEnabled) {
  83390. _this._checkTeleportBackwards(stateObject, controller);
  83391. _this._checkTeleportWithRay(stateObject, controller);
  83392. }
  83393. _this._checkRotate(stateObject, controller);
  83394. });
  83395. }
  83396. };
  83397. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83398. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83399. this._teleportationTarget.isPickable = false;
  83400. var length = 512;
  83401. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83402. dynamicTexture.hasAlpha = true;
  83403. var context = dynamicTexture.getContext();
  83404. var centerX = length / 2;
  83405. var centerY = length / 2;
  83406. var radius = 200;
  83407. context.beginPath();
  83408. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83409. context.fillStyle = this._teleportationFillColor;
  83410. context.fill();
  83411. context.lineWidth = 10;
  83412. context.strokeStyle = this._teleportationBorderColor;
  83413. context.stroke();
  83414. context.closePath();
  83415. dynamicTexture.update();
  83416. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83417. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83418. this._teleportationTarget.material = teleportationCircleMaterial;
  83419. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83420. torus.isPickable = false;
  83421. torus.parent = this._teleportationTarget;
  83422. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83423. var keys = [];
  83424. keys.push({
  83425. frame: 0,
  83426. value: 0
  83427. });
  83428. keys.push({
  83429. frame: 30,
  83430. value: 0.4
  83431. });
  83432. keys.push({
  83433. frame: 60,
  83434. value: 0
  83435. });
  83436. animationInnerCircle.setKeys(keys);
  83437. var easingFunction = new BABYLON.SineEase();
  83438. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83439. animationInnerCircle.setEasingFunction(easingFunction);
  83440. torus.animations = [];
  83441. torus.animations.push(animationInnerCircle);
  83442. this._scene.beginAnimation(torus, 0, 60, true);
  83443. this._hideTeleportationTarget();
  83444. };
  83445. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83446. this._teleportActive = true;
  83447. if (this._teleportationInitialized) {
  83448. this._teleportationTarget.isVisible = true;
  83449. if (this._isDefaultTeleportationTarget) {
  83450. this._teleportationTarget.getChildren()[0].isVisible = true;
  83451. }
  83452. }
  83453. };
  83454. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83455. this._teleportActive = false;
  83456. if (this._teleportationInitialized) {
  83457. this._teleportationTarget.isVisible = false;
  83458. if (this._isDefaultTeleportationTarget) {
  83459. this._teleportationTarget.getChildren()[0].isVisible = false;
  83460. }
  83461. }
  83462. };
  83463. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83464. var _this = this;
  83465. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83466. return;
  83467. }
  83468. if (right) {
  83469. this._rotationAngle++;
  83470. }
  83471. else {
  83472. this._rotationAngle--;
  83473. }
  83474. this.currentVRCamera.animations = [];
  83475. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83476. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83477. var animationRotationKeys = [];
  83478. animationRotationKeys.push({
  83479. frame: 0,
  83480. value: this.currentVRCamera.rotationQuaternion
  83481. });
  83482. animationRotationKeys.push({
  83483. frame: 6,
  83484. value: target
  83485. });
  83486. animationRotation.setKeys(animationRotationKeys);
  83487. animationRotation.setEasingFunction(this._circleEase);
  83488. this.currentVRCamera.animations.push(animationRotation);
  83489. this._postProcessMove.animations = [];
  83490. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83491. var vignetteWeightKeys = [];
  83492. vignetteWeightKeys.push({
  83493. frame: 0,
  83494. value: 0
  83495. });
  83496. vignetteWeightKeys.push({
  83497. frame: 3,
  83498. value: 4
  83499. });
  83500. vignetteWeightKeys.push({
  83501. frame: 6,
  83502. value: 0
  83503. });
  83504. animationPP.setKeys(vignetteWeightKeys);
  83505. animationPP.setEasingFunction(this._circleEase);
  83506. this._postProcessMove.animations.push(animationPP);
  83507. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83508. var vignetteStretchKeys = [];
  83509. vignetteStretchKeys.push({
  83510. frame: 0,
  83511. value: 0
  83512. });
  83513. vignetteStretchKeys.push({
  83514. frame: 3,
  83515. value: 10
  83516. });
  83517. vignetteStretchKeys.push({
  83518. frame: 6,
  83519. value: 0
  83520. });
  83521. animationPP2.setKeys(vignetteStretchKeys);
  83522. animationPP2.setEasingFunction(this._circleEase);
  83523. this._postProcessMove.animations.push(animationPP2);
  83524. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83525. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83526. this._postProcessMove.samples = 4;
  83527. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83528. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83529. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83530. });
  83531. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83532. };
  83533. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83534. if (hit.pickedPoint) {
  83535. if (gazer._teleportationRequestInitiated) {
  83536. this._displayTeleportationTarget();
  83537. this._haloCenter.copyFrom(hit.pickedPoint);
  83538. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83539. }
  83540. var pickNormal = hit.getNormal(true, false);
  83541. if (pickNormal) {
  83542. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83543. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83544. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83545. }
  83546. this._teleportationTarget.position.y += 0.1;
  83547. }
  83548. };
  83549. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83550. var _this = this;
  83551. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83552. return;
  83553. }
  83554. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83555. // offset of the headset from the anchor.
  83556. if (this.webVRCamera.leftCamera) {
  83557. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83558. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83559. location.subtractToRef(this._workingVector, this._workingVector);
  83560. }
  83561. else {
  83562. this._workingVector.copyFrom(location);
  83563. }
  83564. // Add height to account for user's height offset
  83565. if (this.isInVRMode) {
  83566. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83567. }
  83568. else {
  83569. this._workingVector.y += this._defaultHeight;
  83570. }
  83571. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83572. // Create animation from the camera's position to the new location
  83573. this.currentVRCamera.animations = [];
  83574. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83575. var animationCameraTeleportationKeys = [{
  83576. frame: 0,
  83577. value: this.currentVRCamera.position
  83578. },
  83579. {
  83580. frame: 11,
  83581. value: this._workingVector
  83582. }
  83583. ];
  83584. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83585. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83586. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83587. this._postProcessMove.animations = [];
  83588. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83589. var vignetteWeightKeys = [];
  83590. vignetteWeightKeys.push({
  83591. frame: 0,
  83592. value: 0
  83593. });
  83594. vignetteWeightKeys.push({
  83595. frame: 5,
  83596. value: 8
  83597. });
  83598. vignetteWeightKeys.push({
  83599. frame: 11,
  83600. value: 0
  83601. });
  83602. animationPP.setKeys(vignetteWeightKeys);
  83603. this._postProcessMove.animations.push(animationPP);
  83604. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83605. var vignetteStretchKeys = [];
  83606. vignetteStretchKeys.push({
  83607. frame: 0,
  83608. value: 0
  83609. });
  83610. vignetteStretchKeys.push({
  83611. frame: 5,
  83612. value: 10
  83613. });
  83614. vignetteStretchKeys.push({
  83615. frame: 11,
  83616. value: 0
  83617. });
  83618. animationPP2.setKeys(vignetteStretchKeys);
  83619. this._postProcessMove.animations.push(animationPP2);
  83620. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83621. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83622. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83623. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83624. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83625. });
  83626. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83627. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83628. });
  83629. this._hideTeleportationTarget();
  83630. };
  83631. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83632. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83633. return;
  83634. }
  83635. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83636. // Moving the gazeTracker on the mesh face targetted
  83637. if (hit && hit.pickedPoint) {
  83638. if (this._displayGaze) {
  83639. var multiplier = 1;
  83640. gazer._gazeTracker.isVisible = true;
  83641. if (gazer._isActionableMesh) {
  83642. multiplier = 3;
  83643. }
  83644. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83645. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83646. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83647. var pickNormal = hit.getNormal();
  83648. // To avoid z-fighting
  83649. var deltaFighting = 0.002;
  83650. if (pickNormal) {
  83651. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83652. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83653. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83654. }
  83655. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83656. if (gazer._gazeTracker.position.x < 0) {
  83657. gazer._gazeTracker.position.x += deltaFighting;
  83658. }
  83659. else {
  83660. gazer._gazeTracker.position.x -= deltaFighting;
  83661. }
  83662. if (gazer._gazeTracker.position.y < 0) {
  83663. gazer._gazeTracker.position.y += deltaFighting;
  83664. }
  83665. else {
  83666. gazer._gazeTracker.position.y -= deltaFighting;
  83667. }
  83668. if (gazer._gazeTracker.position.z < 0) {
  83669. gazer._gazeTracker.position.z += deltaFighting;
  83670. }
  83671. else {
  83672. gazer._gazeTracker.position.z -= deltaFighting;
  83673. }
  83674. }
  83675. // Changing the size of the laser pointer based on the distance from the targetted point
  83676. gazer._updatePointerDistance(hit.distance);
  83677. }
  83678. else {
  83679. gazer._gazeTracker.isVisible = false;
  83680. }
  83681. if (hit && hit.pickedMesh) {
  83682. gazer._currentHit = hit;
  83683. if (gazer._pointerDownOnMeshAsked) {
  83684. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83685. }
  83686. // The object selected is the floor, we're in a teleportation scenario
  83687. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83688. // Moving the teleportation area to this targetted point
  83689. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83690. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83691. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83692. }
  83693. gazer._currentMeshSelected = null;
  83694. if (gazer._teleportationRequestInitiated) {
  83695. this._moveTeleportationSelectorTo(hit, gazer);
  83696. }
  83697. return;
  83698. }
  83699. // If not, we're in a selection scenario
  83700. //this._teleportationAllowed = false;
  83701. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83702. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83703. this.onNewMeshPicked.notifyObservers(hit);
  83704. gazer._currentMeshSelected = hit.pickedMesh;
  83705. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83706. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83707. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83708. gazer._isActionableMesh = true;
  83709. }
  83710. else {
  83711. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83712. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83713. gazer._isActionableMesh = false;
  83714. }
  83715. try {
  83716. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83717. }
  83718. catch (err) {
  83719. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83720. }
  83721. }
  83722. else {
  83723. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83724. gazer._currentMeshSelected = null;
  83725. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83726. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83727. }
  83728. }
  83729. }
  83730. else {
  83731. gazer._currentHit = null;
  83732. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83733. gazer._currentMeshSelected = null;
  83734. //this._teleportationAllowed = false;
  83735. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83736. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83737. }
  83738. };
  83739. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83740. if (mesh) {
  83741. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83742. }
  83743. };
  83744. /**
  83745. * Sets the color of the laser ray from the vr controllers.
  83746. * @param color new color for the ray.
  83747. */
  83748. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83749. if (this.leftController) {
  83750. this.leftController._setLaserPointerColor(color);
  83751. }
  83752. if (this.rightController) {
  83753. this.rightController._setLaserPointerColor(color);
  83754. }
  83755. };
  83756. /**
  83757. * Sets the color of the ray from the vr headsets gaze.
  83758. * @param color new color for the ray.
  83759. */
  83760. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83761. if (!this._cameraGazer._gazeTracker.material) {
  83762. return;
  83763. }
  83764. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83765. if (this.leftController) {
  83766. this.leftController._gazeTracker.material.emissiveColor = color;
  83767. }
  83768. if (this.rightController) {
  83769. this.rightController._gazeTracker.material.emissiveColor = color;
  83770. }
  83771. };
  83772. /**
  83773. * Exits VR and disposes of the vr experience helper
  83774. */
  83775. VRExperienceHelper.prototype.dispose = function () {
  83776. if (this.isInVRMode) {
  83777. this.exitVR();
  83778. }
  83779. if (this._postProcessMove) {
  83780. this._postProcessMove.dispose();
  83781. }
  83782. if (this._webVRCamera) {
  83783. this._webVRCamera.dispose();
  83784. }
  83785. if (this._vrDeviceOrientationCamera) {
  83786. this._vrDeviceOrientationCamera.dispose();
  83787. }
  83788. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83789. document.body.removeChild(this._btnVR);
  83790. }
  83791. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83792. this._deviceOrientationCamera.dispose();
  83793. }
  83794. if (this._cameraGazer) {
  83795. this._cameraGazer.dispose();
  83796. }
  83797. if (this.leftController) {
  83798. this.leftController.dispose();
  83799. }
  83800. if (this.rightController) {
  83801. this.rightController.dispose();
  83802. }
  83803. if (this._teleportationTarget) {
  83804. this._teleportationTarget.dispose();
  83805. }
  83806. this._floorMeshesCollection = [];
  83807. document.removeEventListener("keydown", this._onKeyDown);
  83808. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83809. window.removeEventListener("resize", this._onResize);
  83810. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83811. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83812. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83813. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83814. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83815. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83816. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83817. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83818. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83819. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83820. this._scene.unregisterBeforeRender(this.beforeRender);
  83821. };
  83822. /**
  83823. * Gets the name of the VRExperienceHelper class
  83824. * @returns "VRExperienceHelper"
  83825. */
  83826. VRExperienceHelper.prototype.getClassName = function () {
  83827. return "VRExperienceHelper";
  83828. };
  83829. return VRExperienceHelper;
  83830. }());
  83831. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83832. })(BABYLON || (BABYLON = {}));
  83833. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83834. "use strict";
  83835. // Mainly based on these 2 articles :
  83836. // 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
  83837. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83838. var BABYLON;
  83839. (function (BABYLON) {
  83840. var JoystickAxis;
  83841. (function (JoystickAxis) {
  83842. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83843. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83844. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83845. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83846. var VirtualJoystick = /** @class */ (function () {
  83847. function VirtualJoystick(leftJoystick) {
  83848. var _this = this;
  83849. if (leftJoystick) {
  83850. this._leftJoystick = true;
  83851. }
  83852. else {
  83853. this._leftJoystick = false;
  83854. }
  83855. VirtualJoystick._globalJoystickIndex++;
  83856. // By default left & right arrow keys are moving the X
  83857. // and up & down keys are moving the Y
  83858. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83859. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83860. this.reverseLeftRight = false;
  83861. this.reverseUpDown = false;
  83862. // collections of pointers
  83863. this._touches = new BABYLON.StringDictionary();
  83864. this.deltaPosition = BABYLON.Vector3.Zero();
  83865. this._joystickSensibility = 25;
  83866. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83867. this._onResize = function (evt) {
  83868. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83869. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83870. if (VirtualJoystick.vjCanvas) {
  83871. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83872. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83873. }
  83874. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83875. };
  83876. // injecting a canvas element on top of the canvas 3D game
  83877. if (!VirtualJoystick.vjCanvas) {
  83878. window.addEventListener("resize", this._onResize, false);
  83879. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83880. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83881. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83882. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83883. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83884. VirtualJoystick.vjCanvas.style.width = "100%";
  83885. VirtualJoystick.vjCanvas.style.height = "100%";
  83886. VirtualJoystick.vjCanvas.style.position = "absolute";
  83887. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83888. VirtualJoystick.vjCanvas.style.top = "0px";
  83889. VirtualJoystick.vjCanvas.style.left = "0px";
  83890. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83891. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83892. // Support for jQuery PEP polyfill
  83893. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83894. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83895. if (!context) {
  83896. throw new Error("Unable to create canvas for virtual joystick");
  83897. }
  83898. VirtualJoystick.vjCanvasContext = context;
  83899. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83900. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83901. document.body.appendChild(VirtualJoystick.vjCanvas);
  83902. }
  83903. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83904. this.pressed = false;
  83905. // default joystick color
  83906. this._joystickColor = "cyan";
  83907. this._joystickPointerID = -1;
  83908. // current joystick position
  83909. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83910. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83911. // origin joystick position
  83912. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83913. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83914. this._onPointerDownHandlerRef = function (evt) {
  83915. _this._onPointerDown(evt);
  83916. };
  83917. this._onPointerMoveHandlerRef = function (evt) {
  83918. _this._onPointerMove(evt);
  83919. };
  83920. this._onPointerUpHandlerRef = function (evt) {
  83921. _this._onPointerUp(evt);
  83922. };
  83923. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83924. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83925. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83926. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83927. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83928. evt.preventDefault(); // Disables system menu
  83929. }, false);
  83930. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83931. }
  83932. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83933. this._joystickSensibility = newJoystickSensibility;
  83934. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83935. };
  83936. VirtualJoystick.prototype._onPointerDown = function (e) {
  83937. var positionOnScreenCondition;
  83938. e.preventDefault();
  83939. if (this._leftJoystick === true) {
  83940. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83941. }
  83942. else {
  83943. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83944. }
  83945. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83946. // First contact will be dedicated to the virtual joystick
  83947. this._joystickPointerID = e.pointerId;
  83948. this._joystickPointerStartPos.x = e.clientX;
  83949. this._joystickPointerStartPos.y = e.clientY;
  83950. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83951. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83952. this._deltaJoystickVector.x = 0;
  83953. this._deltaJoystickVector.y = 0;
  83954. this.pressed = true;
  83955. this._touches.add(e.pointerId.toString(), e);
  83956. }
  83957. else {
  83958. // You can only trigger the action buttons with a joystick declared
  83959. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83960. this._action();
  83961. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83962. }
  83963. }
  83964. };
  83965. VirtualJoystick.prototype._onPointerMove = function (e) {
  83966. // If the current pointer is the one associated to the joystick (first touch contact)
  83967. if (this._joystickPointerID == e.pointerId) {
  83968. this._joystickPointerPos.x = e.clientX;
  83969. this._joystickPointerPos.y = e.clientY;
  83970. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83971. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83972. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83973. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83974. switch (this._axisTargetedByLeftAndRight) {
  83975. case JoystickAxis.X:
  83976. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83977. break;
  83978. case JoystickAxis.Y:
  83979. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83980. break;
  83981. case JoystickAxis.Z:
  83982. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83983. break;
  83984. }
  83985. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83986. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83987. switch (this._axisTargetedByUpAndDown) {
  83988. case JoystickAxis.X:
  83989. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83990. break;
  83991. case JoystickAxis.Y:
  83992. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83993. break;
  83994. case JoystickAxis.Z:
  83995. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83996. break;
  83997. }
  83998. }
  83999. else {
  84000. var data = this._touches.get(e.pointerId.toString());
  84001. if (data) {
  84002. data.x = e.clientX;
  84003. data.y = e.clientY;
  84004. }
  84005. }
  84006. };
  84007. VirtualJoystick.prototype._onPointerUp = function (e) {
  84008. if (this._joystickPointerID == e.pointerId) {
  84009. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84010. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84011. this._joystickPointerID = -1;
  84012. this.pressed = false;
  84013. }
  84014. else {
  84015. var touch = this._touches.get(e.pointerId.toString());
  84016. if (touch) {
  84017. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84018. }
  84019. }
  84020. this._deltaJoystickVector.x = 0;
  84021. this._deltaJoystickVector.y = 0;
  84022. this._touches.remove(e.pointerId.toString());
  84023. };
  84024. /**
  84025. * Change the color of the virtual joystick
  84026. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84027. */
  84028. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84029. this._joystickColor = newColor;
  84030. };
  84031. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84032. this._action = action;
  84033. };
  84034. // Define which axis you'd like to control for left & right
  84035. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84036. switch (axis) {
  84037. case JoystickAxis.X:
  84038. case JoystickAxis.Y:
  84039. case JoystickAxis.Z:
  84040. this._axisTargetedByLeftAndRight = axis;
  84041. break;
  84042. default:
  84043. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84044. break;
  84045. }
  84046. };
  84047. // Define which axis you'd like to control for up & down
  84048. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84049. switch (axis) {
  84050. case JoystickAxis.X:
  84051. case JoystickAxis.Y:
  84052. case JoystickAxis.Z:
  84053. this._axisTargetedByUpAndDown = axis;
  84054. break;
  84055. default:
  84056. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84057. break;
  84058. }
  84059. };
  84060. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84061. var _this = this;
  84062. if (this.pressed) {
  84063. this._touches.forEach(function (key, touch) {
  84064. if (touch.pointerId === _this._joystickPointerID) {
  84065. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84066. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84067. VirtualJoystick.vjCanvasContext.beginPath();
  84068. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84069. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84070. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84071. VirtualJoystick.vjCanvasContext.stroke();
  84072. VirtualJoystick.vjCanvasContext.closePath();
  84073. VirtualJoystick.vjCanvasContext.beginPath();
  84074. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84075. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84076. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84077. VirtualJoystick.vjCanvasContext.stroke();
  84078. VirtualJoystick.vjCanvasContext.closePath();
  84079. VirtualJoystick.vjCanvasContext.beginPath();
  84080. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84081. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84082. VirtualJoystick.vjCanvasContext.stroke();
  84083. VirtualJoystick.vjCanvasContext.closePath();
  84084. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84085. }
  84086. else {
  84087. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84088. VirtualJoystick.vjCanvasContext.beginPath();
  84089. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84090. VirtualJoystick.vjCanvasContext.beginPath();
  84091. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84092. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84093. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84094. VirtualJoystick.vjCanvasContext.stroke();
  84095. VirtualJoystick.vjCanvasContext.closePath();
  84096. touch.prevX = touch.x;
  84097. touch.prevY = touch.y;
  84098. }
  84099. ;
  84100. });
  84101. }
  84102. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84103. };
  84104. VirtualJoystick.prototype.releaseCanvas = function () {
  84105. if (VirtualJoystick.vjCanvas) {
  84106. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84107. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84108. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84109. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84110. window.removeEventListener("resize", this._onResize);
  84111. document.body.removeChild(VirtualJoystick.vjCanvas);
  84112. VirtualJoystick.vjCanvas = null;
  84113. }
  84114. };
  84115. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84116. VirtualJoystick._globalJoystickIndex = 0;
  84117. return VirtualJoystick;
  84118. }());
  84119. BABYLON.VirtualJoystick = VirtualJoystick;
  84120. })(BABYLON || (BABYLON = {}));
  84121. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84122. "use strict";
  84123. var BABYLON;
  84124. (function (BABYLON) {
  84125. // We're mainly based on the logic defined into the FreeCamera code
  84126. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84127. __extends(VirtualJoysticksCamera, _super);
  84128. function VirtualJoysticksCamera(name, position, scene) {
  84129. var _this = _super.call(this, name, position, scene) || this;
  84130. _this.inputs.addVirtualJoystick();
  84131. return _this;
  84132. }
  84133. VirtualJoysticksCamera.prototype.getClassName = function () {
  84134. return "VirtualJoysticksCamera";
  84135. };
  84136. return VirtualJoysticksCamera;
  84137. }(BABYLON.FreeCamera));
  84138. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84139. })(BABYLON || (BABYLON = {}));
  84140. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84141. "use strict";
  84142. var BABYLON;
  84143. (function (BABYLON) {
  84144. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84145. function FreeCameraVirtualJoystickInput() {
  84146. }
  84147. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84148. return this._leftjoystick;
  84149. };
  84150. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84151. return this._rightjoystick;
  84152. };
  84153. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84154. if (this._leftjoystick) {
  84155. var camera = this.camera;
  84156. var speed = camera._computeLocalCameraSpeed() * 50;
  84157. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84158. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84159. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84160. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84161. if (!this._leftjoystick.pressed) {
  84162. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84163. }
  84164. if (!this._rightjoystick.pressed) {
  84165. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84166. }
  84167. }
  84168. };
  84169. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84170. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84171. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84172. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84173. this._leftjoystick.setJoystickSensibility(0.15);
  84174. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84175. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84176. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84177. this._rightjoystick.reverseUpDown = true;
  84178. this._rightjoystick.setJoystickSensibility(0.05);
  84179. this._rightjoystick.setJoystickColor("yellow");
  84180. };
  84181. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84182. this._leftjoystick.releaseCanvas();
  84183. this._rightjoystick.releaseCanvas();
  84184. };
  84185. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84186. return "FreeCameraVirtualJoystickInput";
  84187. };
  84188. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84189. return "virtualJoystick";
  84190. };
  84191. return FreeCameraVirtualJoystickInput;
  84192. }());
  84193. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84194. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84195. })(BABYLON || (BABYLON = {}));
  84196. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84197. "use strict";
  84198. var BABYLON;
  84199. (function (BABYLON) {
  84200. var SimplificationSettings = /** @class */ (function () {
  84201. function SimplificationSettings(quality, distance, optimizeMesh) {
  84202. this.quality = quality;
  84203. this.distance = distance;
  84204. this.optimizeMesh = optimizeMesh;
  84205. }
  84206. return SimplificationSettings;
  84207. }());
  84208. BABYLON.SimplificationSettings = SimplificationSettings;
  84209. var SimplificationQueue = /** @class */ (function () {
  84210. function SimplificationQueue() {
  84211. this.running = false;
  84212. this._simplificationArray = [];
  84213. }
  84214. SimplificationQueue.prototype.addTask = function (task) {
  84215. this._simplificationArray.push(task);
  84216. };
  84217. SimplificationQueue.prototype.executeNext = function () {
  84218. var task = this._simplificationArray.pop();
  84219. if (task) {
  84220. this.running = true;
  84221. this.runSimplification(task);
  84222. }
  84223. else {
  84224. this.running = false;
  84225. }
  84226. };
  84227. SimplificationQueue.prototype.runSimplification = function (task) {
  84228. var _this = this;
  84229. if (task.parallelProcessing) {
  84230. //parallel simplifier
  84231. task.settings.forEach(function (setting) {
  84232. var simplifier = _this.getSimplifier(task);
  84233. simplifier.simplify(setting, function (newMesh) {
  84234. task.mesh.addLODLevel(setting.distance, newMesh);
  84235. newMesh.isVisible = true;
  84236. //check if it is the last
  84237. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84238. //all done, run the success callback.
  84239. task.successCallback();
  84240. }
  84241. _this.executeNext();
  84242. });
  84243. });
  84244. }
  84245. else {
  84246. //single simplifier.
  84247. var simplifier = this.getSimplifier(task);
  84248. var runDecimation = function (setting, callback) {
  84249. simplifier.simplify(setting, function (newMesh) {
  84250. task.mesh.addLODLevel(setting.distance, newMesh);
  84251. newMesh.isVisible = true;
  84252. //run the next quality level
  84253. callback();
  84254. });
  84255. };
  84256. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84257. runDecimation(task.settings[loop.index], function () {
  84258. loop.executeNext();
  84259. });
  84260. }, function () {
  84261. //execution ended, run the success callback.
  84262. if (task.successCallback) {
  84263. task.successCallback();
  84264. }
  84265. _this.executeNext();
  84266. });
  84267. }
  84268. };
  84269. SimplificationQueue.prototype.getSimplifier = function (task) {
  84270. switch (task.simplificationType) {
  84271. case SimplificationType.QUADRATIC:
  84272. default:
  84273. return new QuadraticErrorSimplification(task.mesh);
  84274. }
  84275. };
  84276. return SimplificationQueue;
  84277. }());
  84278. BABYLON.SimplificationQueue = SimplificationQueue;
  84279. /**
  84280. * The implemented types of simplification.
  84281. * At the moment only Quadratic Error Decimation is implemented.
  84282. */
  84283. var SimplificationType;
  84284. (function (SimplificationType) {
  84285. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84286. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84287. var DecimationTriangle = /** @class */ (function () {
  84288. function DecimationTriangle(vertices) {
  84289. this.vertices = vertices;
  84290. this.error = new Array(4);
  84291. this.deleted = false;
  84292. this.isDirty = false;
  84293. this.deletePending = false;
  84294. this.borderFactor = 0;
  84295. }
  84296. return DecimationTriangle;
  84297. }());
  84298. BABYLON.DecimationTriangle = DecimationTriangle;
  84299. var DecimationVertex = /** @class */ (function () {
  84300. function DecimationVertex(position, id) {
  84301. this.position = position;
  84302. this.id = id;
  84303. this.isBorder = true;
  84304. this.q = new QuadraticMatrix();
  84305. this.triangleCount = 0;
  84306. this.triangleStart = 0;
  84307. this.originalOffsets = [];
  84308. }
  84309. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84310. this.position.copyFrom(newPosition);
  84311. };
  84312. return DecimationVertex;
  84313. }());
  84314. BABYLON.DecimationVertex = DecimationVertex;
  84315. var QuadraticMatrix = /** @class */ (function () {
  84316. function QuadraticMatrix(data) {
  84317. this.data = new Array(10);
  84318. for (var i = 0; i < 10; ++i) {
  84319. if (data && data[i]) {
  84320. this.data[i] = data[i];
  84321. }
  84322. else {
  84323. this.data[i] = 0;
  84324. }
  84325. }
  84326. }
  84327. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84328. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84329. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84330. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84331. return det;
  84332. };
  84333. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84334. for (var i = 0; i < 10; ++i) {
  84335. this.data[i] += matrix.data[i];
  84336. }
  84337. };
  84338. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84339. for (var i = 0; i < 10; ++i) {
  84340. this.data[i] += data[i];
  84341. }
  84342. };
  84343. QuadraticMatrix.prototype.add = function (matrix) {
  84344. var m = new QuadraticMatrix();
  84345. for (var i = 0; i < 10; ++i) {
  84346. m.data[i] = this.data[i] + matrix.data[i];
  84347. }
  84348. return m;
  84349. };
  84350. QuadraticMatrix.FromData = function (a, b, c, d) {
  84351. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84352. };
  84353. //returning an array to avoid garbage collection
  84354. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84355. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84356. };
  84357. return QuadraticMatrix;
  84358. }());
  84359. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84360. var Reference = /** @class */ (function () {
  84361. function Reference(vertexId, triangleId) {
  84362. this.vertexId = vertexId;
  84363. this.triangleId = triangleId;
  84364. }
  84365. return Reference;
  84366. }());
  84367. BABYLON.Reference = Reference;
  84368. /**
  84369. * An implementation of the Quadratic Error simplification algorithm.
  84370. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84371. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84372. * @author RaananW
  84373. */
  84374. var QuadraticErrorSimplification = /** @class */ (function () {
  84375. function QuadraticErrorSimplification(_mesh) {
  84376. this._mesh = _mesh;
  84377. this.syncIterations = 5000;
  84378. this.aggressiveness = 7;
  84379. this.decimationIterations = 100;
  84380. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84381. }
  84382. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84383. var _this = this;
  84384. this.initDecimatedMesh();
  84385. //iterating through the submeshes array, one after the other.
  84386. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84387. _this.initWithMesh(loop.index, function () {
  84388. _this.runDecimation(settings, loop.index, function () {
  84389. loop.executeNext();
  84390. });
  84391. }, settings.optimizeMesh);
  84392. }, function () {
  84393. setTimeout(function () {
  84394. successCallback(_this._reconstructedMesh);
  84395. }, 0);
  84396. });
  84397. };
  84398. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84399. var _this = this;
  84400. var targetCount = ~~(this.triangles.length * settings.quality);
  84401. var deletedTriangles = 0;
  84402. var triangleCount = this.triangles.length;
  84403. var iterationFunction = function (iteration, callback) {
  84404. setTimeout(function () {
  84405. if (iteration % 5 === 0) {
  84406. _this.updateMesh(iteration === 0);
  84407. }
  84408. for (var i = 0; i < _this.triangles.length; ++i) {
  84409. _this.triangles[i].isDirty = false;
  84410. }
  84411. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84412. var trianglesIterator = function (i) {
  84413. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84414. var t = _this.triangles[tIdx];
  84415. if (!t)
  84416. return;
  84417. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84418. return;
  84419. }
  84420. for (var j = 0; j < 3; ++j) {
  84421. if (t.error[j] < threshold) {
  84422. var deleted0 = [];
  84423. var deleted1 = [];
  84424. var v0 = t.vertices[j];
  84425. var v1 = t.vertices[(j + 1) % 3];
  84426. if (v0.isBorder || v1.isBorder)
  84427. continue;
  84428. var p = BABYLON.Vector3.Zero();
  84429. var n = BABYLON.Vector3.Zero();
  84430. var uv = BABYLON.Vector2.Zero();
  84431. var color = new BABYLON.Color4(0, 0, 0, 1);
  84432. _this.calculateError(v0, v1, p, n, uv, color);
  84433. var delTr = new Array();
  84434. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84435. continue;
  84436. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84437. continue;
  84438. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84439. continue;
  84440. var uniqueArray = new Array();
  84441. delTr.forEach(function (deletedT) {
  84442. if (uniqueArray.indexOf(deletedT) === -1) {
  84443. deletedT.deletePending = true;
  84444. uniqueArray.push(deletedT);
  84445. }
  84446. });
  84447. if (uniqueArray.length % 2 !== 0) {
  84448. continue;
  84449. }
  84450. v0.q = v1.q.add(v0.q);
  84451. v0.updatePosition(p);
  84452. var tStart = _this.references.length;
  84453. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84454. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84455. var tCount = _this.references.length - tStart;
  84456. if (tCount <= v0.triangleCount) {
  84457. if (tCount) {
  84458. for (var c = 0; c < tCount; c++) {
  84459. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84460. }
  84461. }
  84462. }
  84463. else {
  84464. v0.triangleStart = tStart;
  84465. }
  84466. v0.triangleCount = tCount;
  84467. break;
  84468. }
  84469. }
  84470. };
  84471. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84472. }, 0);
  84473. };
  84474. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84475. if (triangleCount - deletedTriangles <= targetCount)
  84476. loop.breakLoop();
  84477. else {
  84478. iterationFunction(loop.index, function () {
  84479. loop.executeNext();
  84480. });
  84481. }
  84482. }, function () {
  84483. setTimeout(function () {
  84484. //reconstruct this part of the mesh
  84485. _this.reconstructMesh(submeshIndex);
  84486. successCallback();
  84487. }, 0);
  84488. });
  84489. };
  84490. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84491. var _this = this;
  84492. this.vertices = [];
  84493. this.triangles = [];
  84494. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84495. var indices = this._mesh.getIndices();
  84496. var submesh = this._mesh.subMeshes[submeshIndex];
  84497. var findInVertices = function (positionToSearch) {
  84498. if (optimizeMesh) {
  84499. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84500. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84501. return _this.vertices[ii];
  84502. }
  84503. }
  84504. }
  84505. return null;
  84506. };
  84507. var vertexReferences = [];
  84508. var vertexInit = function (i) {
  84509. if (!positionData) {
  84510. return;
  84511. }
  84512. var offset = i + submesh.verticesStart;
  84513. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84514. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84515. vertex.originalOffsets.push(offset);
  84516. if (vertex.id === _this.vertices.length) {
  84517. _this.vertices.push(vertex);
  84518. }
  84519. vertexReferences.push(vertex.id);
  84520. };
  84521. //var totalVertices = mesh.getTotalVertices();
  84522. var totalVertices = submesh.verticesCount;
  84523. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84524. var indicesInit = function (i) {
  84525. if (!indices) {
  84526. return;
  84527. }
  84528. var offset = (submesh.indexStart / 3) + i;
  84529. var pos = (offset * 3);
  84530. var i0 = indices[pos + 0];
  84531. var i1 = indices[pos + 1];
  84532. var i2 = indices[pos + 2];
  84533. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84534. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84535. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84536. var triangle = new DecimationTriangle([v0, v1, v2]);
  84537. triangle.originalOffset = pos;
  84538. _this.triangles.push(triangle);
  84539. };
  84540. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84541. _this.init(callback);
  84542. });
  84543. });
  84544. };
  84545. QuadraticErrorSimplification.prototype.init = function (callback) {
  84546. var _this = this;
  84547. var triangleInit1 = function (i) {
  84548. var t = _this.triangles[i];
  84549. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84550. for (var j = 0; j < 3; j++) {
  84551. 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))));
  84552. }
  84553. };
  84554. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84555. var triangleInit2 = function (i) {
  84556. var t = _this.triangles[i];
  84557. for (var j = 0; j < 3; ++j) {
  84558. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84559. }
  84560. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84561. };
  84562. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84563. callback();
  84564. });
  84565. });
  84566. };
  84567. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84568. var newTriangles = [];
  84569. var i;
  84570. for (i = 0; i < this.vertices.length; ++i) {
  84571. this.vertices[i].triangleCount = 0;
  84572. }
  84573. var t;
  84574. var j;
  84575. for (i = 0; i < this.triangles.length; ++i) {
  84576. if (!this.triangles[i].deleted) {
  84577. t = this.triangles[i];
  84578. for (j = 0; j < 3; ++j) {
  84579. t.vertices[j].triangleCount = 1;
  84580. }
  84581. newTriangles.push(t);
  84582. }
  84583. }
  84584. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84585. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84586. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84587. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84588. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84589. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84590. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84591. var vertexCount = 0;
  84592. for (i = 0; i < this.vertices.length; ++i) {
  84593. var vertex = this.vertices[i];
  84594. vertex.id = vertexCount;
  84595. if (vertex.triangleCount) {
  84596. vertex.originalOffsets.forEach(function (originalOffset) {
  84597. if (!normalData) {
  84598. return;
  84599. }
  84600. newPositionData.push(vertex.position.x);
  84601. newPositionData.push(vertex.position.y);
  84602. newPositionData.push(vertex.position.z);
  84603. newNormalData.push(normalData[originalOffset * 3]);
  84604. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84605. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84606. if (uvs && uvs.length) {
  84607. newUVsData.push(uvs[(originalOffset * 2)]);
  84608. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84609. }
  84610. else if (colorsData && colorsData.length) {
  84611. newColorsData.push(colorsData[(originalOffset * 4)]);
  84612. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84613. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84614. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84615. }
  84616. ++vertexCount;
  84617. });
  84618. }
  84619. }
  84620. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84621. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84622. var submeshesArray = this._reconstructedMesh.subMeshes;
  84623. this._reconstructedMesh.subMeshes = [];
  84624. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84625. var originalIndices = this._mesh.getIndices();
  84626. for (i = 0; i < newTriangles.length; ++i) {
  84627. t = newTriangles[i]; //now get the new referencing point for each vertex
  84628. [0, 1, 2].forEach(function (idx) {
  84629. var id = originalIndices[t.originalOffset + idx];
  84630. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84631. if (offset < 0)
  84632. offset = 0;
  84633. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84634. });
  84635. }
  84636. //overwriting the old vertex buffers and indices.
  84637. this._reconstructedMesh.setIndices(newIndicesArray);
  84638. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84639. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84640. if (newUVsData.length > 0)
  84641. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84642. if (newColorsData.length > 0)
  84643. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84644. //create submesh
  84645. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84646. if (submeshIndex > 0) {
  84647. this._reconstructedMesh.subMeshes = [];
  84648. submeshesArray.forEach(function (submesh) {
  84649. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84650. });
  84651. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84652. }
  84653. };
  84654. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84655. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84656. this._reconstructedMesh.material = this._mesh.material;
  84657. this._reconstructedMesh.parent = this._mesh.parent;
  84658. this._reconstructedMesh.isVisible = false;
  84659. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84660. };
  84661. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84662. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84663. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84664. if (t.deleted)
  84665. continue;
  84666. var s = this.references[vertex1.triangleStart + i].vertexId;
  84667. var v1 = t.vertices[(s + 1) % 3];
  84668. var v2 = t.vertices[(s + 2) % 3];
  84669. if ((v1 === vertex2 || v2 === vertex2)) {
  84670. deletedArray[i] = true;
  84671. delTr.push(t);
  84672. continue;
  84673. }
  84674. var d1 = v1.position.subtract(point);
  84675. d1 = d1.normalize();
  84676. var d2 = v2.position.subtract(point);
  84677. d2 = d2.normalize();
  84678. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84679. return true;
  84680. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84681. deletedArray[i] = false;
  84682. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84683. return true;
  84684. }
  84685. return false;
  84686. };
  84687. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84688. var newDeleted = deletedTriangles;
  84689. for (var i = 0; i < vertex.triangleCount; ++i) {
  84690. var ref = this.references[vertex.triangleStart + i];
  84691. var t = this.triangles[ref.triangleId];
  84692. if (t.deleted)
  84693. continue;
  84694. if (deletedArray[i] && t.deletePending) {
  84695. t.deleted = true;
  84696. newDeleted++;
  84697. continue;
  84698. }
  84699. t.vertices[ref.vertexId] = origVertex;
  84700. t.isDirty = true;
  84701. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84702. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84703. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84704. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84705. this.references.push(ref);
  84706. }
  84707. return newDeleted;
  84708. };
  84709. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84710. for (var i = 0; i < this.vertices.length; ++i) {
  84711. var vCount = [];
  84712. var vId = [];
  84713. var v = this.vertices[i];
  84714. var j;
  84715. for (j = 0; j < v.triangleCount; ++j) {
  84716. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84717. for (var ii = 0; ii < 3; ii++) {
  84718. var ofs = 0;
  84719. var vv = triangle.vertices[ii];
  84720. while (ofs < vCount.length) {
  84721. if (vId[ofs] === vv.id)
  84722. break;
  84723. ++ofs;
  84724. }
  84725. if (ofs === vCount.length) {
  84726. vCount.push(1);
  84727. vId.push(vv.id);
  84728. }
  84729. else {
  84730. vCount[ofs]++;
  84731. }
  84732. }
  84733. }
  84734. for (j = 0; j < vCount.length; ++j) {
  84735. if (vCount[j] === 1) {
  84736. this.vertices[vId[j]].isBorder = true;
  84737. }
  84738. else {
  84739. this.vertices[vId[j]].isBorder = false;
  84740. }
  84741. }
  84742. }
  84743. };
  84744. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84745. if (identifyBorders === void 0) { identifyBorders = false; }
  84746. var i;
  84747. if (!identifyBorders) {
  84748. var newTrianglesVector = [];
  84749. for (i = 0; i < this.triangles.length; ++i) {
  84750. if (!this.triangles[i].deleted) {
  84751. newTrianglesVector.push(this.triangles[i]);
  84752. }
  84753. }
  84754. this.triangles = newTrianglesVector;
  84755. }
  84756. for (i = 0; i < this.vertices.length; ++i) {
  84757. this.vertices[i].triangleCount = 0;
  84758. this.vertices[i].triangleStart = 0;
  84759. }
  84760. var t;
  84761. var j;
  84762. var v;
  84763. for (i = 0; i < this.triangles.length; ++i) {
  84764. t = this.triangles[i];
  84765. for (j = 0; j < 3; ++j) {
  84766. v = t.vertices[j];
  84767. v.triangleCount++;
  84768. }
  84769. }
  84770. var tStart = 0;
  84771. for (i = 0; i < this.vertices.length; ++i) {
  84772. this.vertices[i].triangleStart = tStart;
  84773. tStart += this.vertices[i].triangleCount;
  84774. this.vertices[i].triangleCount = 0;
  84775. }
  84776. var newReferences = new Array(this.triangles.length * 3);
  84777. for (i = 0; i < this.triangles.length; ++i) {
  84778. t = this.triangles[i];
  84779. for (j = 0; j < 3; ++j) {
  84780. v = t.vertices[j];
  84781. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84782. v.triangleCount++;
  84783. }
  84784. }
  84785. this.references = newReferences;
  84786. if (identifyBorders) {
  84787. this.identifyBorder();
  84788. }
  84789. };
  84790. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84791. var x = point.x;
  84792. var y = point.y;
  84793. var z = point.z;
  84794. 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
  84795. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84796. };
  84797. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84798. var q = vertex1.q.add(vertex2.q);
  84799. var border = vertex1.isBorder && vertex2.isBorder;
  84800. var error = 0;
  84801. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84802. if (qDet !== 0 && !border) {
  84803. if (!pointResult) {
  84804. pointResult = BABYLON.Vector3.Zero();
  84805. }
  84806. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84807. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84808. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84809. error = this.vertexError(q, pointResult);
  84810. }
  84811. else {
  84812. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84813. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84814. var error1 = this.vertexError(q, vertex1.position);
  84815. var error2 = this.vertexError(q, vertex2.position);
  84816. var error3 = this.vertexError(q, p3);
  84817. error = Math.min(error1, error2, error3);
  84818. if (error === error1) {
  84819. if (pointResult) {
  84820. pointResult.copyFrom(vertex1.position);
  84821. }
  84822. }
  84823. else if (error === error2) {
  84824. if (pointResult) {
  84825. pointResult.copyFrom(vertex2.position);
  84826. }
  84827. }
  84828. else {
  84829. if (pointResult) {
  84830. pointResult.copyFrom(p3);
  84831. }
  84832. }
  84833. }
  84834. return error;
  84835. };
  84836. return QuadraticErrorSimplification;
  84837. }());
  84838. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84839. })(BABYLON || (BABYLON = {}));
  84840. //# sourceMappingURL=babylon.meshSimplification.js.map
  84841. "use strict";
  84842. var BABYLON;
  84843. (function (BABYLON) {
  84844. var MeshLODLevel = /** @class */ (function () {
  84845. function MeshLODLevel(distance, mesh) {
  84846. this.distance = distance;
  84847. this.mesh = mesh;
  84848. }
  84849. return MeshLODLevel;
  84850. }());
  84851. BABYLON.MeshLODLevel = MeshLODLevel;
  84852. })(BABYLON || (BABYLON = {}));
  84853. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84854. "use strict";
  84855. var BABYLON;
  84856. (function (BABYLON) {
  84857. /**
  84858. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84859. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84860. */
  84861. var SceneOptimization = /** @class */ (function () {
  84862. /**
  84863. * Creates the SceneOptimization object
  84864. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84865. * @param desc defines the description associated with the optimization
  84866. */
  84867. function SceneOptimization(
  84868. /**
  84869. * Defines the priority of this optimization (0 by default which means first in the list)
  84870. */
  84871. priority) {
  84872. if (priority === void 0) { priority = 0; }
  84873. this.priority = priority;
  84874. }
  84875. /**
  84876. * Gets a string describing the action executed by the current optimization
  84877. * @returns description string
  84878. */
  84879. SceneOptimization.prototype.getDescription = function () {
  84880. return "";
  84881. };
  84882. /**
  84883. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84884. * @param scene defines the current scene where to apply this optimization
  84885. * @param optimizer defines the current optimizer
  84886. * @returns true if everything that can be done was applied
  84887. */
  84888. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84889. return true;
  84890. };
  84891. ;
  84892. return SceneOptimization;
  84893. }());
  84894. BABYLON.SceneOptimization = SceneOptimization;
  84895. /**
  84896. * Defines an optimization used to reduce the size of render target textures
  84897. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84898. */
  84899. var TextureOptimization = /** @class */ (function (_super) {
  84900. __extends(TextureOptimization, _super);
  84901. /**
  84902. * Creates the TextureOptimization object
  84903. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84904. * @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
  84905. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84906. */
  84907. function TextureOptimization(
  84908. /**
  84909. * Defines the priority of this optimization (0 by default which means first in the list)
  84910. */
  84911. priority,
  84912. /**
  84913. * 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
  84914. */
  84915. maximumSize,
  84916. /**
  84917. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84918. */
  84919. step) {
  84920. if (priority === void 0) { priority = 0; }
  84921. if (maximumSize === void 0) { maximumSize = 1024; }
  84922. if (step === void 0) { step = 0.5; }
  84923. var _this = _super.call(this, priority) || this;
  84924. _this.priority = priority;
  84925. _this.maximumSize = maximumSize;
  84926. _this.step = step;
  84927. return _this;
  84928. }
  84929. /**
  84930. * Gets a string describing the action executed by the current optimization
  84931. * @returns description string
  84932. */
  84933. TextureOptimization.prototype.getDescription = function () {
  84934. return "Reducing render target texture size to " + this.maximumSize;
  84935. };
  84936. /**
  84937. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84938. * @param scene defines the current scene where to apply this optimization
  84939. * @param optimizer defines the current optimizer
  84940. * @returns true if everything that can be done was applied
  84941. */
  84942. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84943. var allDone = true;
  84944. for (var index = 0; index < scene.textures.length; index++) {
  84945. var texture = scene.textures[index];
  84946. if (!texture.canRescale || texture.getContext) {
  84947. continue;
  84948. }
  84949. var currentSize = texture.getSize();
  84950. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84951. if (maxDimension > this.maximumSize) {
  84952. texture.scale(this.step);
  84953. allDone = false;
  84954. }
  84955. }
  84956. return allDone;
  84957. };
  84958. return TextureOptimization;
  84959. }(SceneOptimization));
  84960. BABYLON.TextureOptimization = TextureOptimization;
  84961. /**
  84962. * Defines an optimization used to increase or decrease the rendering resolution
  84963. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84964. */
  84965. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84966. __extends(HardwareScalingOptimization, _super);
  84967. /**
  84968. * Creates the HardwareScalingOptimization object
  84969. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84970. * @param maximumScale defines the maximum scale to use (2 by default)
  84971. * @param step defines the step to use between two passes (0.5 by default)
  84972. */
  84973. function HardwareScalingOptimization(
  84974. /**
  84975. * Defines the priority of this optimization (0 by default which means first in the list)
  84976. */
  84977. priority,
  84978. /**
  84979. * Defines the maximum scale to use (2 by default)
  84980. */
  84981. maximumScale,
  84982. /**
  84983. * Defines the step to use between two passes (0.5 by default)
  84984. */
  84985. step) {
  84986. if (priority === void 0) { priority = 0; }
  84987. if (maximumScale === void 0) { maximumScale = 2; }
  84988. if (step === void 0) { step = 0.25; }
  84989. var _this = _super.call(this, priority) || this;
  84990. _this.priority = priority;
  84991. _this.maximumScale = maximumScale;
  84992. _this.step = step;
  84993. _this._currentScale = -1;
  84994. _this._directionOffset = 1;
  84995. return _this;
  84996. }
  84997. /**
  84998. * Gets a string describing the action executed by the current optimization
  84999. * @return description string
  85000. */
  85001. HardwareScalingOptimization.prototype.getDescription = function () {
  85002. return "Setting hardware scaling level to " + this._currentScale;
  85003. };
  85004. /**
  85005. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85006. * @param scene defines the current scene where to apply this optimization
  85007. * @param optimizer defines the current optimizer
  85008. * @returns true if everything that can be done was applied
  85009. */
  85010. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85011. if (this._currentScale === -1) {
  85012. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85013. if (this._currentScale > this.maximumScale) {
  85014. this._directionOffset = -1;
  85015. }
  85016. }
  85017. this._currentScale += this._directionOffset * this.step;
  85018. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85019. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85020. };
  85021. ;
  85022. return HardwareScalingOptimization;
  85023. }(SceneOptimization));
  85024. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85025. /**
  85026. * Defines an optimization used to remove shadows
  85027. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85028. */
  85029. var ShadowsOptimization = /** @class */ (function (_super) {
  85030. __extends(ShadowsOptimization, _super);
  85031. function ShadowsOptimization() {
  85032. return _super !== null && _super.apply(this, arguments) || this;
  85033. }
  85034. /**
  85035. * Gets a string describing the action executed by the current optimization
  85036. * @return description string
  85037. */
  85038. ShadowsOptimization.prototype.getDescription = function () {
  85039. return "Turning shadows on/off";
  85040. };
  85041. /**
  85042. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85043. * @param scene defines the current scene where to apply this optimization
  85044. * @param optimizer defines the current optimizer
  85045. * @returns true if everything that can be done was applied
  85046. */
  85047. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85048. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85049. return true;
  85050. };
  85051. ;
  85052. return ShadowsOptimization;
  85053. }(SceneOptimization));
  85054. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85055. /**
  85056. * Defines an optimization used to turn post-processes off
  85057. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85058. */
  85059. var PostProcessesOptimization = /** @class */ (function (_super) {
  85060. __extends(PostProcessesOptimization, _super);
  85061. function PostProcessesOptimization() {
  85062. return _super !== null && _super.apply(this, arguments) || this;
  85063. }
  85064. /**
  85065. * Gets a string describing the action executed by the current optimization
  85066. * @return description string
  85067. */
  85068. PostProcessesOptimization.prototype.getDescription = function () {
  85069. return "Turning post-processes on/off";
  85070. };
  85071. /**
  85072. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85073. * @param scene defines the current scene where to apply this optimization
  85074. * @param optimizer defines the current optimizer
  85075. * @returns true if everything that can be done was applied
  85076. */
  85077. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85078. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85079. return true;
  85080. };
  85081. ;
  85082. return PostProcessesOptimization;
  85083. }(SceneOptimization));
  85084. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85085. /**
  85086. * Defines an optimization used to turn lens flares off
  85087. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85088. */
  85089. var LensFlaresOptimization = /** @class */ (function (_super) {
  85090. __extends(LensFlaresOptimization, _super);
  85091. function LensFlaresOptimization() {
  85092. return _super !== null && _super.apply(this, arguments) || this;
  85093. }
  85094. /**
  85095. * Gets a string describing the action executed by the current optimization
  85096. * @return description string
  85097. */
  85098. LensFlaresOptimization.prototype.getDescription = function () {
  85099. return "Turning lens flares on/off";
  85100. };
  85101. /**
  85102. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85103. * @param scene defines the current scene where to apply this optimization
  85104. * @param optimizer defines the current optimizer
  85105. * @returns true if everything that can be done was applied
  85106. */
  85107. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85108. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85109. return true;
  85110. };
  85111. ;
  85112. return LensFlaresOptimization;
  85113. }(SceneOptimization));
  85114. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85115. /**
  85116. * Defines an optimization based on user defined callback.
  85117. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85118. */
  85119. var CustomOptimization = /** @class */ (function (_super) {
  85120. __extends(CustomOptimization, _super);
  85121. function CustomOptimization() {
  85122. return _super !== null && _super.apply(this, arguments) || this;
  85123. }
  85124. /**
  85125. * Gets a string describing the action executed by the current optimization
  85126. * @returns description string
  85127. */
  85128. CustomOptimization.prototype.getDescription = function () {
  85129. if (this.onGetDescription) {
  85130. return this.onGetDescription();
  85131. }
  85132. return "Running user defined callback";
  85133. };
  85134. /**
  85135. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85136. * @param scene defines the current scene where to apply this optimization
  85137. * @param optimizer defines the current optimizer
  85138. * @returns true if everything that can be done was applied
  85139. */
  85140. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85141. if (this.onApply) {
  85142. return this.onApply(scene, optimizer);
  85143. }
  85144. return true;
  85145. };
  85146. ;
  85147. return CustomOptimization;
  85148. }(SceneOptimization));
  85149. BABYLON.CustomOptimization = CustomOptimization;
  85150. /**
  85151. * Defines an optimization used to turn particles off
  85152. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85153. */
  85154. var ParticlesOptimization = /** @class */ (function (_super) {
  85155. __extends(ParticlesOptimization, _super);
  85156. function ParticlesOptimization() {
  85157. return _super !== null && _super.apply(this, arguments) || this;
  85158. }
  85159. /**
  85160. * Gets a string describing the action executed by the current optimization
  85161. * @return description string
  85162. */
  85163. ParticlesOptimization.prototype.getDescription = function () {
  85164. return "Turning particles on/off";
  85165. };
  85166. /**
  85167. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85168. * @param scene defines the current scene where to apply this optimization
  85169. * @param optimizer defines the current optimizer
  85170. * @returns true if everything that can be done was applied
  85171. */
  85172. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85173. scene.particlesEnabled = optimizer.isInImprovementMode;
  85174. return true;
  85175. };
  85176. ;
  85177. return ParticlesOptimization;
  85178. }(SceneOptimization));
  85179. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85180. /**
  85181. * Defines an optimization used to turn render targets off
  85182. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85183. */
  85184. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85185. __extends(RenderTargetsOptimization, _super);
  85186. function RenderTargetsOptimization() {
  85187. return _super !== null && _super.apply(this, arguments) || this;
  85188. }
  85189. /**
  85190. * Gets a string describing the action executed by the current optimization
  85191. * @return description string
  85192. */
  85193. RenderTargetsOptimization.prototype.getDescription = function () {
  85194. return "Turning render targets off";
  85195. };
  85196. /**
  85197. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85198. * @param scene defines the current scene where to apply this optimization
  85199. * @param optimizer defines the current optimizer
  85200. * @returns true if everything that can be done was applied
  85201. */
  85202. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85203. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85204. return true;
  85205. };
  85206. ;
  85207. return RenderTargetsOptimization;
  85208. }(SceneOptimization));
  85209. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85210. /**
  85211. * Defines an optimization used to merge meshes with compatible materials
  85212. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85213. */
  85214. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85215. __extends(MergeMeshesOptimization, _super);
  85216. function MergeMeshesOptimization() {
  85217. var _this = _super !== null && _super.apply(this, arguments) || this;
  85218. _this._canBeMerged = function (abstractMesh) {
  85219. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85220. return false;
  85221. }
  85222. var mesh = abstractMesh;
  85223. if (!mesh.isVisible || !mesh.isEnabled()) {
  85224. return false;
  85225. }
  85226. if (mesh.instances.length > 0) {
  85227. return false;
  85228. }
  85229. if (mesh.skeleton || mesh.hasLODLevels) {
  85230. return false;
  85231. }
  85232. if (mesh.parent) {
  85233. return false;
  85234. }
  85235. return true;
  85236. };
  85237. return _this;
  85238. }
  85239. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85240. /**
  85241. * Gets or sets a boolean which defines if optimization octree has to be updated
  85242. */
  85243. get: function () {
  85244. return MergeMeshesOptimization._UpdateSelectionTree;
  85245. },
  85246. /**
  85247. * Gets or sets a boolean which defines if optimization octree has to be updated
  85248. */
  85249. set: function (value) {
  85250. MergeMeshesOptimization._UpdateSelectionTree = value;
  85251. },
  85252. enumerable: true,
  85253. configurable: true
  85254. });
  85255. /**
  85256. * Gets a string describing the action executed by the current optimization
  85257. * @return description string
  85258. */
  85259. MergeMeshesOptimization.prototype.getDescription = function () {
  85260. return "Merging similar meshes together";
  85261. };
  85262. /**
  85263. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85264. * @param scene defines the current scene where to apply this optimization
  85265. * @param optimizer defines the current optimizer
  85266. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85267. * @returns true if everything that can be done was applied
  85268. */
  85269. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85270. var globalPool = scene.meshes.slice(0);
  85271. var globalLength = globalPool.length;
  85272. for (var index = 0; index < globalLength; index++) {
  85273. var currentPool = new Array();
  85274. var current = globalPool[index];
  85275. // Checks
  85276. if (!this._canBeMerged(current)) {
  85277. continue;
  85278. }
  85279. currentPool.push(current);
  85280. // Find compatible meshes
  85281. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85282. var otherMesh = globalPool[subIndex];
  85283. if (!this._canBeMerged(otherMesh)) {
  85284. continue;
  85285. }
  85286. if (otherMesh.material !== current.material) {
  85287. continue;
  85288. }
  85289. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85290. continue;
  85291. }
  85292. currentPool.push(otherMesh);
  85293. globalLength--;
  85294. globalPool.splice(subIndex, 1);
  85295. subIndex--;
  85296. }
  85297. if (currentPool.length < 2) {
  85298. continue;
  85299. }
  85300. // Merge meshes
  85301. BABYLON.Mesh.MergeMeshes(currentPool);
  85302. }
  85303. if (updateSelectionTree != undefined) {
  85304. if (updateSelectionTree) {
  85305. scene.createOrUpdateSelectionOctree();
  85306. }
  85307. }
  85308. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85309. scene.createOrUpdateSelectionOctree();
  85310. }
  85311. return true;
  85312. };
  85313. ;
  85314. MergeMeshesOptimization._UpdateSelectionTree = false;
  85315. return MergeMeshesOptimization;
  85316. }(SceneOptimization));
  85317. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85318. /**
  85319. * Defines a list of options used by SceneOptimizer
  85320. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85321. */
  85322. var SceneOptimizerOptions = /** @class */ (function () {
  85323. /**
  85324. * Creates a new list of options used by SceneOptimizer
  85325. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85326. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85327. */
  85328. function SceneOptimizerOptions(
  85329. /**
  85330. * Defines the target frame rate to reach (60 by default)
  85331. */
  85332. targetFrameRate,
  85333. /**
  85334. * Defines the interval between two checkes (2000ms by default)
  85335. */
  85336. trackerDuration) {
  85337. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85338. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85339. this.targetFrameRate = targetFrameRate;
  85340. this.trackerDuration = trackerDuration;
  85341. /**
  85342. * Gets the list of optimizations to apply
  85343. */
  85344. this.optimizations = new Array();
  85345. }
  85346. /**
  85347. * Add a new optimization
  85348. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85349. * @returns the current SceneOptimizerOptions
  85350. */
  85351. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85352. this.optimizations.push(optimization);
  85353. return this;
  85354. };
  85355. /**
  85356. * Add a new custom optimization
  85357. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85358. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85359. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85360. * @returns the current SceneOptimizerOptions
  85361. */
  85362. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85363. if (priority === void 0) { priority = 0; }
  85364. var optimization = new CustomOptimization(priority);
  85365. optimization.onApply = onApply;
  85366. optimization.onGetDescription = onGetDescription;
  85367. this.optimizations.push(optimization);
  85368. return this;
  85369. };
  85370. /**
  85371. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85372. * @param targetFrameRate defines the target frame rate (60 by default)
  85373. * @returns a SceneOptimizerOptions object
  85374. */
  85375. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85376. var result = new SceneOptimizerOptions(targetFrameRate);
  85377. var priority = 0;
  85378. result.addOptimization(new MergeMeshesOptimization(priority));
  85379. result.addOptimization(new ShadowsOptimization(priority));
  85380. result.addOptimization(new LensFlaresOptimization(priority));
  85381. // Next priority
  85382. priority++;
  85383. result.addOptimization(new PostProcessesOptimization(priority));
  85384. result.addOptimization(new ParticlesOptimization(priority));
  85385. // Next priority
  85386. priority++;
  85387. result.addOptimization(new TextureOptimization(priority, 1024));
  85388. return result;
  85389. };
  85390. /**
  85391. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85392. * @param targetFrameRate defines the target frame rate (60 by default)
  85393. * @returns a SceneOptimizerOptions object
  85394. */
  85395. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85396. var result = new SceneOptimizerOptions(targetFrameRate);
  85397. var priority = 0;
  85398. result.addOptimization(new MergeMeshesOptimization(priority));
  85399. result.addOptimization(new ShadowsOptimization(priority));
  85400. result.addOptimization(new LensFlaresOptimization(priority));
  85401. // Next priority
  85402. priority++;
  85403. result.addOptimization(new PostProcessesOptimization(priority));
  85404. result.addOptimization(new ParticlesOptimization(priority));
  85405. // Next priority
  85406. priority++;
  85407. result.addOptimization(new TextureOptimization(priority, 512));
  85408. // Next priority
  85409. priority++;
  85410. result.addOptimization(new RenderTargetsOptimization(priority));
  85411. // Next priority
  85412. priority++;
  85413. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85414. return result;
  85415. };
  85416. /**
  85417. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85418. * @param targetFrameRate defines the target frame rate (60 by default)
  85419. * @returns a SceneOptimizerOptions object
  85420. */
  85421. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85422. var result = new SceneOptimizerOptions(targetFrameRate);
  85423. var priority = 0;
  85424. result.addOptimization(new MergeMeshesOptimization(priority));
  85425. result.addOptimization(new ShadowsOptimization(priority));
  85426. result.addOptimization(new LensFlaresOptimization(priority));
  85427. // Next priority
  85428. priority++;
  85429. result.addOptimization(new PostProcessesOptimization(priority));
  85430. result.addOptimization(new ParticlesOptimization(priority));
  85431. // Next priority
  85432. priority++;
  85433. result.addOptimization(new TextureOptimization(priority, 256));
  85434. // Next priority
  85435. priority++;
  85436. result.addOptimization(new RenderTargetsOptimization(priority));
  85437. // Next priority
  85438. priority++;
  85439. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85440. return result;
  85441. };
  85442. return SceneOptimizerOptions;
  85443. }());
  85444. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85445. /**
  85446. * Class used to run optimizations in order to reach a target frame rate
  85447. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85448. */
  85449. var SceneOptimizer = /** @class */ (function () {
  85450. /**
  85451. * Creates a new SceneOptimizer
  85452. * @param scene defines the scene to work on
  85453. * @param options defines the options to use with the SceneOptimizer
  85454. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85455. * @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)
  85456. */
  85457. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85458. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85459. if (improvementMode === void 0) { improvementMode = false; }
  85460. var _this = this;
  85461. this._isRunning = false;
  85462. this._currentPriorityLevel = 0;
  85463. this._targetFrameRate = 60;
  85464. this._trackerDuration = 2000;
  85465. this._currentFrameRate = 0;
  85466. this._improvementMode = false;
  85467. /**
  85468. * Defines an observable called when the optimizer reaches the target frame rate
  85469. */
  85470. this.onSuccessObservable = new BABYLON.Observable();
  85471. /**
  85472. * Defines an observable called when the optimizer enables an optimization
  85473. */
  85474. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85475. /**
  85476. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85477. */
  85478. this.onFailureObservable = new BABYLON.Observable();
  85479. if (!options) {
  85480. this._options = new SceneOptimizerOptions();
  85481. }
  85482. else {
  85483. this._options = options;
  85484. }
  85485. if (this._options.targetFrameRate) {
  85486. this._targetFrameRate = this._options.targetFrameRate;
  85487. }
  85488. if (this._options.trackerDuration) {
  85489. this._trackerDuration = this._options.trackerDuration;
  85490. }
  85491. if (autoGeneratePriorities) {
  85492. var priority = 0;
  85493. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85494. var optim = _a[_i];
  85495. optim.priority = priority++;
  85496. }
  85497. }
  85498. this._improvementMode = improvementMode;
  85499. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85500. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85501. _this._sceneDisposeObserver = null;
  85502. _this.dispose();
  85503. });
  85504. }
  85505. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85506. /**
  85507. * Gets a boolean indicating if the optimizer is in improvement mode
  85508. */
  85509. get: function () {
  85510. return this._improvementMode;
  85511. },
  85512. enumerable: true,
  85513. configurable: true
  85514. });
  85515. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85516. /**
  85517. * Gets the current priority level (0 at start)
  85518. */
  85519. get: function () {
  85520. return this._currentPriorityLevel;
  85521. },
  85522. enumerable: true,
  85523. configurable: true
  85524. });
  85525. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85526. /**
  85527. * Gets the current frame rate checked by the SceneOptimizer
  85528. */
  85529. get: function () {
  85530. return this._currentFrameRate;
  85531. },
  85532. enumerable: true,
  85533. configurable: true
  85534. });
  85535. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85536. /**
  85537. * Gets or sets the current target frame rate (60 by default)
  85538. */
  85539. get: function () {
  85540. return this._targetFrameRate;
  85541. },
  85542. /**
  85543. * Gets or sets the current target frame rate (60 by default)
  85544. */
  85545. set: function (value) {
  85546. this._targetFrameRate = value;
  85547. },
  85548. enumerable: true,
  85549. configurable: true
  85550. });
  85551. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85552. /**
  85553. * Gets or sets the current interval between two checks (every 2000ms by default)
  85554. */
  85555. get: function () {
  85556. return this._trackerDuration;
  85557. },
  85558. /**
  85559. * Gets or sets the current interval between two checks (every 2000ms by default)
  85560. */
  85561. set: function (value) {
  85562. this._trackerDuration = value;
  85563. },
  85564. enumerable: true,
  85565. configurable: true
  85566. });
  85567. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85568. /**
  85569. * Gets the list of active optimizations
  85570. */
  85571. get: function () {
  85572. return this._options.optimizations;
  85573. },
  85574. enumerable: true,
  85575. configurable: true
  85576. });
  85577. /**
  85578. * Stops the current optimizer
  85579. */
  85580. SceneOptimizer.prototype.stop = function () {
  85581. this._isRunning = false;
  85582. };
  85583. /**
  85584. * Reset the optimizer to initial step (current priority level = 0)
  85585. */
  85586. SceneOptimizer.prototype.reset = function () {
  85587. this._currentPriorityLevel = 0;
  85588. };
  85589. /**
  85590. * Start the optimizer. By default it will try to reach a specific framerate
  85591. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85592. */
  85593. SceneOptimizer.prototype.start = function () {
  85594. var _this = this;
  85595. if (this._isRunning) {
  85596. return;
  85597. }
  85598. this._isRunning = true;
  85599. // Let's wait for the scene to be ready before running our check
  85600. this._scene.executeWhenReady(function () {
  85601. setTimeout(function () {
  85602. _this._checkCurrentState();
  85603. }, _this._trackerDuration);
  85604. });
  85605. };
  85606. SceneOptimizer.prototype._checkCurrentState = function () {
  85607. var _this = this;
  85608. if (!this._isRunning) {
  85609. return;
  85610. }
  85611. var scene = this._scene;
  85612. var options = this._options;
  85613. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85614. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85615. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85616. this._isRunning = false;
  85617. this.onSuccessObservable.notifyObservers(this);
  85618. return;
  85619. }
  85620. // Apply current level of optimizations
  85621. var allDone = true;
  85622. var noOptimizationApplied = true;
  85623. for (var index = 0; index < options.optimizations.length; index++) {
  85624. var optimization = options.optimizations[index];
  85625. if (optimization.priority === this._currentPriorityLevel) {
  85626. noOptimizationApplied = false;
  85627. allDone = allDone && optimization.apply(scene, this);
  85628. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85629. }
  85630. }
  85631. // If no optimization was applied, this is a failure :(
  85632. if (noOptimizationApplied) {
  85633. this._isRunning = false;
  85634. this.onFailureObservable.notifyObservers(this);
  85635. return;
  85636. }
  85637. // If all optimizations were done, move to next level
  85638. if (allDone) {
  85639. this._currentPriorityLevel++;
  85640. }
  85641. // Let's the system running for a specific amount of time before checking FPS
  85642. scene.executeWhenReady(function () {
  85643. setTimeout(function () {
  85644. _this._checkCurrentState();
  85645. }, _this._trackerDuration);
  85646. });
  85647. };
  85648. /**
  85649. * Release all resources
  85650. */
  85651. SceneOptimizer.prototype.dispose = function () {
  85652. this.stop();
  85653. this.onSuccessObservable.clear();
  85654. this.onFailureObservable.clear();
  85655. this.onNewOptimizationAppliedObservable.clear();
  85656. if (this._sceneDisposeObserver) {
  85657. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85658. }
  85659. };
  85660. /**
  85661. * Helper function to create a SceneOptimizer with one single line of code
  85662. * @param scene defines the scene to work on
  85663. * @param options defines the options to use with the SceneOptimizer
  85664. * @param onSuccess defines a callback to call on success
  85665. * @param onFailure defines a callback to call on failure
  85666. * @returns the new SceneOptimizer object
  85667. */
  85668. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85669. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85670. if (onSuccess) {
  85671. optimizer.onSuccessObservable.add(function () {
  85672. onSuccess();
  85673. });
  85674. }
  85675. if (onFailure) {
  85676. optimizer.onFailureObservable.add(function () {
  85677. onFailure();
  85678. });
  85679. }
  85680. optimizer.start();
  85681. return optimizer;
  85682. };
  85683. return SceneOptimizer;
  85684. }());
  85685. BABYLON.SceneOptimizer = SceneOptimizer;
  85686. })(BABYLON || (BABYLON = {}));
  85687. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85688. "use strict";
  85689. var BABYLON;
  85690. (function (BABYLON) {
  85691. var OutlineRenderer = /** @class */ (function () {
  85692. function OutlineRenderer(scene) {
  85693. this.zOffset = 1;
  85694. this._scene = scene;
  85695. }
  85696. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85697. var _this = this;
  85698. if (useOverlay === void 0) { useOverlay = false; }
  85699. var scene = this._scene;
  85700. var engine = this._scene.getEngine();
  85701. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85702. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85703. return;
  85704. }
  85705. var mesh = subMesh.getRenderingMesh();
  85706. var material = subMesh.getMaterial();
  85707. if (!material || !scene.activeCamera) {
  85708. return;
  85709. }
  85710. engine.enableEffect(this._effect);
  85711. // Logarithmic depth
  85712. if (material.useLogarithmicDepth) {
  85713. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85714. }
  85715. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85716. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85717. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85718. // Bones
  85719. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85720. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85721. }
  85722. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85723. // Alpha test
  85724. if (material && material.needAlphaTesting()) {
  85725. var alphaTexture = material.getAlphaTestTexture();
  85726. if (alphaTexture) {
  85727. this._effect.setTexture("diffuseSampler", alphaTexture);
  85728. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85729. }
  85730. }
  85731. engine.setZOffset(-this.zOffset);
  85732. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85733. engine.setZOffset(0);
  85734. };
  85735. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85736. var defines = [];
  85737. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85738. var mesh = subMesh.getMesh();
  85739. var material = subMesh.getMaterial();
  85740. if (material) {
  85741. // Alpha test
  85742. if (material.needAlphaTesting()) {
  85743. defines.push("#define ALPHATEST");
  85744. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85745. attribs.push(BABYLON.VertexBuffer.UVKind);
  85746. defines.push("#define UV1");
  85747. }
  85748. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85749. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85750. defines.push("#define UV2");
  85751. }
  85752. }
  85753. //Logarithmic depth
  85754. if (material.useLogarithmicDepth) {
  85755. defines.push("#define LOGARITHMICDEPTH");
  85756. }
  85757. }
  85758. // Bones
  85759. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85760. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85761. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85762. if (mesh.numBoneInfluencers > 4) {
  85763. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85764. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85765. }
  85766. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85767. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85768. }
  85769. else {
  85770. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85771. }
  85772. // Instances
  85773. if (useInstances) {
  85774. defines.push("#define INSTANCES");
  85775. attribs.push("world0");
  85776. attribs.push("world1");
  85777. attribs.push("world2");
  85778. attribs.push("world3");
  85779. }
  85780. // Get correct effect
  85781. var join = defines.join("\n");
  85782. if (this._cachedDefines !== join) {
  85783. this._cachedDefines = join;
  85784. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85785. }
  85786. return this._effect.isReady();
  85787. };
  85788. return OutlineRenderer;
  85789. }());
  85790. BABYLON.OutlineRenderer = OutlineRenderer;
  85791. })(BABYLON || (BABYLON = {}));
  85792. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85793. "use strict";
  85794. var BABYLON;
  85795. (function (BABYLON) {
  85796. var FaceAdjacencies = /** @class */ (function () {
  85797. function FaceAdjacencies() {
  85798. this.edges = new Array();
  85799. this.edgesConnectedCount = 0;
  85800. }
  85801. return FaceAdjacencies;
  85802. }());
  85803. var EdgesRenderer = /** @class */ (function () {
  85804. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85805. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85806. if (epsilon === void 0) { epsilon = 0.95; }
  85807. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85808. this.edgesWidthScalerForOrthographic = 1000.0;
  85809. this.edgesWidthScalerForPerspective = 50.0;
  85810. this._linesPositions = new Array();
  85811. this._linesNormals = new Array();
  85812. this._linesIndices = new Array();
  85813. this._buffers = {};
  85814. this._checkVerticesInsteadOfIndices = false;
  85815. this._source = source;
  85816. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85817. this._epsilon = epsilon;
  85818. this._prepareRessources();
  85819. this._generateEdgesLines();
  85820. }
  85821. EdgesRenderer.prototype._prepareRessources = function () {
  85822. if (this._lineShader) {
  85823. return;
  85824. }
  85825. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85826. attributes: ["position", "normal"],
  85827. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85828. });
  85829. this._lineShader.disableDepthWrite = true;
  85830. this._lineShader.backFaceCulling = false;
  85831. };
  85832. EdgesRenderer.prototype._rebuild = function () {
  85833. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85834. if (buffer) {
  85835. buffer._rebuild();
  85836. }
  85837. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85838. if (buffer) {
  85839. buffer._rebuild();
  85840. }
  85841. var scene = this._source.getScene();
  85842. var engine = scene.getEngine();
  85843. this._ib = engine.createIndexBuffer(this._linesIndices);
  85844. };
  85845. EdgesRenderer.prototype.dispose = function () {
  85846. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85847. if (buffer) {
  85848. buffer.dispose();
  85849. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85850. }
  85851. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85852. if (buffer) {
  85853. buffer.dispose();
  85854. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85855. }
  85856. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85857. this._lineShader.dispose();
  85858. };
  85859. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85860. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85861. return 0;
  85862. }
  85863. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85864. return 1;
  85865. }
  85866. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85867. return 2;
  85868. }
  85869. return -1;
  85870. };
  85871. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85872. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85873. return 0;
  85874. }
  85875. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85876. return 1;
  85877. }
  85878. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85879. return 2;
  85880. }
  85881. return -1;
  85882. };
  85883. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85884. var needToCreateLine;
  85885. if (edge === undefined) {
  85886. needToCreateLine = true;
  85887. }
  85888. else {
  85889. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85890. needToCreateLine = dotProduct < this._epsilon;
  85891. }
  85892. if (needToCreateLine) {
  85893. var offset = this._linesPositions.length / 3;
  85894. var normal = p0.subtract(p1);
  85895. normal.normalize();
  85896. // Positions
  85897. this._linesPositions.push(p0.x);
  85898. this._linesPositions.push(p0.y);
  85899. this._linesPositions.push(p0.z);
  85900. this._linesPositions.push(p0.x);
  85901. this._linesPositions.push(p0.y);
  85902. this._linesPositions.push(p0.z);
  85903. this._linesPositions.push(p1.x);
  85904. this._linesPositions.push(p1.y);
  85905. this._linesPositions.push(p1.z);
  85906. this._linesPositions.push(p1.x);
  85907. this._linesPositions.push(p1.y);
  85908. this._linesPositions.push(p1.z);
  85909. // Normals
  85910. this._linesNormals.push(p1.x);
  85911. this._linesNormals.push(p1.y);
  85912. this._linesNormals.push(p1.z);
  85913. this._linesNormals.push(-1);
  85914. this._linesNormals.push(p1.x);
  85915. this._linesNormals.push(p1.y);
  85916. this._linesNormals.push(p1.z);
  85917. this._linesNormals.push(1);
  85918. this._linesNormals.push(p0.x);
  85919. this._linesNormals.push(p0.y);
  85920. this._linesNormals.push(p0.z);
  85921. this._linesNormals.push(-1);
  85922. this._linesNormals.push(p0.x);
  85923. this._linesNormals.push(p0.y);
  85924. this._linesNormals.push(p0.z);
  85925. this._linesNormals.push(1);
  85926. // Indices
  85927. this._linesIndices.push(offset);
  85928. this._linesIndices.push(offset + 1);
  85929. this._linesIndices.push(offset + 2);
  85930. this._linesIndices.push(offset);
  85931. this._linesIndices.push(offset + 2);
  85932. this._linesIndices.push(offset + 3);
  85933. }
  85934. };
  85935. EdgesRenderer.prototype._generateEdgesLines = function () {
  85936. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85937. var indices = this._source.getIndices();
  85938. if (!indices || !positions) {
  85939. return;
  85940. }
  85941. // First let's find adjacencies
  85942. var adjacencies = new Array();
  85943. var faceNormals = new Array();
  85944. var index;
  85945. var faceAdjacencies;
  85946. // Prepare faces
  85947. for (index = 0; index < indices.length; index += 3) {
  85948. faceAdjacencies = new FaceAdjacencies();
  85949. var p0Index = indices[index];
  85950. var p1Index = indices[index + 1];
  85951. var p2Index = indices[index + 2];
  85952. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85953. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85954. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85955. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85956. faceNormal.normalize();
  85957. faceNormals.push(faceNormal);
  85958. adjacencies.push(faceAdjacencies);
  85959. }
  85960. // Scan
  85961. for (index = 0; index < adjacencies.length; index++) {
  85962. faceAdjacencies = adjacencies[index];
  85963. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85964. var otherFaceAdjacencies = adjacencies[otherIndex];
  85965. if (faceAdjacencies.edgesConnectedCount === 3) {
  85966. break;
  85967. }
  85968. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85969. continue;
  85970. }
  85971. var otherP0 = indices[otherIndex * 3];
  85972. var otherP1 = indices[otherIndex * 3 + 1];
  85973. var otherP2 = indices[otherIndex * 3 + 2];
  85974. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85975. var otherEdgeIndex = 0;
  85976. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85977. continue;
  85978. }
  85979. switch (edgeIndex) {
  85980. case 0:
  85981. if (this._checkVerticesInsteadOfIndices) {
  85982. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85983. }
  85984. else {
  85985. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85986. }
  85987. break;
  85988. case 1:
  85989. if (this._checkVerticesInsteadOfIndices) {
  85990. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85991. }
  85992. else {
  85993. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85994. }
  85995. break;
  85996. case 2:
  85997. if (this._checkVerticesInsteadOfIndices) {
  85998. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85999. }
  86000. else {
  86001. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86002. }
  86003. break;
  86004. }
  86005. if (otherEdgeIndex === -1) {
  86006. continue;
  86007. }
  86008. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86009. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86010. faceAdjacencies.edgesConnectedCount++;
  86011. otherFaceAdjacencies.edgesConnectedCount++;
  86012. if (faceAdjacencies.edgesConnectedCount === 3) {
  86013. break;
  86014. }
  86015. }
  86016. }
  86017. }
  86018. // Create lines
  86019. for (index = 0; index < adjacencies.length; index++) {
  86020. // 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
  86021. var current = adjacencies[index];
  86022. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86023. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86024. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86025. }
  86026. // Merge into a single mesh
  86027. var engine = this._source.getScene().getEngine();
  86028. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86029. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86030. this._ib = engine.createIndexBuffer(this._linesIndices);
  86031. this._indicesCount = this._linesIndices.length;
  86032. };
  86033. EdgesRenderer.prototype.render = function () {
  86034. var scene = this._source.getScene();
  86035. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86036. return;
  86037. }
  86038. var engine = scene.getEngine();
  86039. this._lineShader._preBind();
  86040. // VBOs
  86041. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86042. scene.resetCachedMaterial();
  86043. this._lineShader.setColor4("color", this._source.edgesColor);
  86044. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86045. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86046. }
  86047. else {
  86048. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86049. }
  86050. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86051. this._lineShader.bind(this._source.getWorldMatrix());
  86052. // Draw order
  86053. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86054. this._lineShader.unbind();
  86055. engine.setDepthWrite(true);
  86056. };
  86057. return EdgesRenderer;
  86058. }());
  86059. BABYLON.EdgesRenderer = EdgesRenderer;
  86060. })(BABYLON || (BABYLON = {}));
  86061. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86062. "use strict";
  86063. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86064. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86065. s = arguments[i];
  86066. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86067. t[p] = s[p];
  86068. }
  86069. return t;
  86070. };
  86071. var BABYLON;
  86072. (function (BABYLON) {
  86073. /**
  86074. * The effect layer Helps adding post process effect blended with the main pass.
  86075. *
  86076. * This can be for instance use to generate glow or higlight effects on the scene.
  86077. *
  86078. * The effect layer class can not be used directly and is intented to inherited from to be
  86079. * customized per effects.
  86080. */
  86081. var EffectLayer = /** @class */ (function () {
  86082. /**
  86083. * Instantiates a new effect Layer and references it in the scene.
  86084. * @param name The name of the layer
  86085. * @param scene The scene to use the layer in
  86086. */
  86087. function EffectLayer(
  86088. /** The Friendly of the effect in the scene */
  86089. name, scene) {
  86090. this.name = name;
  86091. this._vertexBuffers = {};
  86092. this._maxSize = 0;
  86093. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86094. this._shouldRender = true;
  86095. this._postProcesses = [];
  86096. this._textures = [];
  86097. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86098. /**
  86099. * The clear color of the texture used to generate the glow map.
  86100. */
  86101. this.neutralColor = new BABYLON.Color4();
  86102. /**
  86103. * Specifies wether the highlight layer is enabled or not.
  86104. */
  86105. this.isEnabled = true;
  86106. /**
  86107. * An event triggered when the effect layer has been disposed.
  86108. */
  86109. this.onDisposeObservable = new BABYLON.Observable();
  86110. /**
  86111. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86112. */
  86113. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86114. /**
  86115. * An event triggered when the generated texture is being merged in the scene.
  86116. */
  86117. this.onBeforeComposeObservable = new BABYLON.Observable();
  86118. /**
  86119. * An event triggered when the generated texture has been merged in the scene.
  86120. */
  86121. this.onAfterComposeObservable = new BABYLON.Observable();
  86122. /**
  86123. * An event triggered when the efffect layer changes its size.
  86124. */
  86125. this.onSizeChangedObservable = new BABYLON.Observable();
  86126. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86127. this._engine = scene.getEngine();
  86128. this._maxSize = this._engine.getCaps().maxTextureSize;
  86129. this._scene.effectLayers.push(this);
  86130. // Generate Buffers
  86131. this._generateIndexBuffer();
  86132. this._genrateVertexBuffer();
  86133. }
  86134. Object.defineProperty(EffectLayer.prototype, "camera", {
  86135. /**
  86136. * Gets the camera attached to the layer.
  86137. */
  86138. get: function () {
  86139. return this._effectLayerOptions.camera;
  86140. },
  86141. enumerable: true,
  86142. configurable: true
  86143. });
  86144. /**
  86145. * Initializes the effect layer with the required options.
  86146. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86147. */
  86148. EffectLayer.prototype._init = function (options) {
  86149. // Adapt options
  86150. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86151. this._setMainTextureSize();
  86152. this._createMainTexture();
  86153. this._createTextureAndPostProcesses();
  86154. this._mergeEffect = this._createMergeEffect();
  86155. };
  86156. /**
  86157. * Generates the index buffer of the full screen quad blending to the main canvas.
  86158. */
  86159. EffectLayer.prototype._generateIndexBuffer = function () {
  86160. // Indices
  86161. var indices = [];
  86162. indices.push(0);
  86163. indices.push(1);
  86164. indices.push(2);
  86165. indices.push(0);
  86166. indices.push(2);
  86167. indices.push(3);
  86168. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86169. };
  86170. /**
  86171. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86172. */
  86173. EffectLayer.prototype._genrateVertexBuffer = function () {
  86174. // VBO
  86175. var vertices = [];
  86176. vertices.push(1, 1);
  86177. vertices.push(-1, 1);
  86178. vertices.push(-1, -1);
  86179. vertices.push(1, -1);
  86180. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86181. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86182. };
  86183. /**
  86184. * Sets the main texture desired size which is the closest power of two
  86185. * of the engine canvas size.
  86186. */
  86187. EffectLayer.prototype._setMainTextureSize = function () {
  86188. if (this._effectLayerOptions.mainTextureFixedSize) {
  86189. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86190. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86191. }
  86192. else {
  86193. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86194. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86195. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86196. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86197. }
  86198. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86199. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86200. };
  86201. /**
  86202. * Creates the main texture for the effect layer.
  86203. */
  86204. EffectLayer.prototype._createMainTexture = function () {
  86205. var _this = this;
  86206. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86207. width: this._mainTextureDesiredSize.width,
  86208. height: this._mainTextureDesiredSize.height
  86209. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86210. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86211. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86212. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86213. this._mainTexture.anisotropicFilteringLevel = 1;
  86214. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86215. this._mainTexture.renderParticles = false;
  86216. this._mainTexture.renderList = null;
  86217. this._mainTexture.ignoreCameraViewport = true;
  86218. // Custom render function
  86219. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86220. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86221. var index;
  86222. var engine = _this._scene.getEngine();
  86223. if (depthOnlySubMeshes.length) {
  86224. engine.setColorWrite(false);
  86225. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86226. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86227. }
  86228. engine.setColorWrite(true);
  86229. }
  86230. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86231. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86232. }
  86233. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86234. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86235. }
  86236. for (index = 0; index < transparentSubMeshes.length; index++) {
  86237. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86238. }
  86239. };
  86240. this._mainTexture.onClearObservable.add(function (engine) {
  86241. engine.clear(_this.neutralColor, true, true, true);
  86242. });
  86243. };
  86244. /**
  86245. * Checks for the readiness of the element composing the layer.
  86246. * @param subMesh the mesh to check for
  86247. * @param useInstances specify wether or not to use instances to render the mesh
  86248. * @param emissiveTexture the associated emissive texture used to generate the glow
  86249. * @return true if ready otherwise, false
  86250. */
  86251. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86252. var material = subMesh.getMaterial();
  86253. if (!material) {
  86254. return false;
  86255. }
  86256. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86257. return false;
  86258. }
  86259. var defines = [];
  86260. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86261. var mesh = subMesh.getMesh();
  86262. var uv1 = false;
  86263. var uv2 = false;
  86264. // Alpha test
  86265. if (material && material.needAlphaTesting()) {
  86266. var alphaTexture = material.getAlphaTestTexture();
  86267. if (alphaTexture) {
  86268. defines.push("#define ALPHATEST");
  86269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86270. alphaTexture.coordinatesIndex === 1) {
  86271. defines.push("#define DIFFUSEUV2");
  86272. uv2 = true;
  86273. }
  86274. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86275. defines.push("#define DIFFUSEUV1");
  86276. uv1 = true;
  86277. }
  86278. }
  86279. }
  86280. // Emissive
  86281. if (emissiveTexture) {
  86282. defines.push("#define EMISSIVE");
  86283. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86284. emissiveTexture.coordinatesIndex === 1) {
  86285. defines.push("#define EMISSIVEUV2");
  86286. uv2 = true;
  86287. }
  86288. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86289. defines.push("#define EMISSIVEUV1");
  86290. uv1 = true;
  86291. }
  86292. }
  86293. if (uv1) {
  86294. attribs.push(BABYLON.VertexBuffer.UVKind);
  86295. defines.push("#define UV1");
  86296. }
  86297. if (uv2) {
  86298. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86299. defines.push("#define UV2");
  86300. }
  86301. // Bones
  86302. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86303. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86304. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86305. if (mesh.numBoneInfluencers > 4) {
  86306. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86307. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86308. }
  86309. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86310. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86311. }
  86312. else {
  86313. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86314. }
  86315. // Morph targets
  86316. var manager = mesh.morphTargetManager;
  86317. var morphInfluencers = 0;
  86318. if (manager) {
  86319. if (manager.numInfluencers > 0) {
  86320. defines.push("#define MORPHTARGETS");
  86321. morphInfluencers = manager.numInfluencers;
  86322. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86323. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86324. }
  86325. }
  86326. // Instances
  86327. if (useInstances) {
  86328. defines.push("#define INSTANCES");
  86329. attribs.push("world0");
  86330. attribs.push("world1");
  86331. attribs.push("world2");
  86332. attribs.push("world3");
  86333. }
  86334. // Get correct effect
  86335. var join = defines.join("\n");
  86336. if (this._cachedDefines !== join) {
  86337. this._cachedDefines = join;
  86338. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86339. }
  86340. return this._effectLayerMapGenerationEffect.isReady();
  86341. };
  86342. /**
  86343. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86344. */
  86345. EffectLayer.prototype.render = function () {
  86346. var currentEffect = this._mergeEffect;
  86347. // Check
  86348. if (!currentEffect.isReady())
  86349. return;
  86350. for (var i = 0; i < this._postProcesses.length; i++) {
  86351. if (!this._postProcesses[i].isReady()) {
  86352. return;
  86353. }
  86354. }
  86355. var engine = this._scene.getEngine();
  86356. this.onBeforeComposeObservable.notifyObservers(this);
  86357. // Render
  86358. engine.enableEffect(currentEffect);
  86359. engine.setState(false);
  86360. // VBOs
  86361. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86362. // Cache
  86363. var previousAlphaMode = engine.getAlphaMode();
  86364. // Go Blend.
  86365. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86366. // Blends the map on the main canvas.
  86367. this._internalRender(currentEffect);
  86368. // Restore Alpha
  86369. engine.setAlphaMode(previousAlphaMode);
  86370. this.onAfterComposeObservable.notifyObservers(this);
  86371. // Handle size changes.
  86372. var size = this._mainTexture.getSize();
  86373. this._setMainTextureSize();
  86374. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86375. // Recreate RTT and post processes on size change.
  86376. this.onSizeChangedObservable.notifyObservers(this);
  86377. this._disposeTextureAndPostProcesses();
  86378. this._createMainTexture();
  86379. this._createTextureAndPostProcesses();
  86380. }
  86381. };
  86382. /**
  86383. * Determine if a given mesh will be used in the current effect.
  86384. * @param mesh mesh to test
  86385. * @returns true if the mesh will be used
  86386. */
  86387. EffectLayer.prototype.hasMesh = function (mesh) {
  86388. return true;
  86389. };
  86390. /**
  86391. * Returns true if the layer contains information to display, otherwise false.
  86392. * @returns true if the glow layer should be rendered
  86393. */
  86394. EffectLayer.prototype.shouldRender = function () {
  86395. return this.isEnabled && this._shouldRender;
  86396. };
  86397. /**
  86398. * Returns true if the mesh should render, otherwise false.
  86399. * @param mesh The mesh to render
  86400. * @returns true if it should render otherwise false
  86401. */
  86402. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86403. return true;
  86404. };
  86405. /**
  86406. * Returns true if the mesh should render, otherwise false.
  86407. * @param mesh The mesh to render
  86408. * @returns true if it should render otherwise false
  86409. */
  86410. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86411. return true;
  86412. };
  86413. /**
  86414. * Renders the submesh passed in parameter to the generation map.
  86415. */
  86416. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86417. var _this = this;
  86418. if (!this.shouldRender()) {
  86419. return;
  86420. }
  86421. var material = subMesh.getMaterial();
  86422. var mesh = subMesh.getRenderingMesh();
  86423. var scene = this._scene;
  86424. var engine = scene.getEngine();
  86425. if (!material) {
  86426. return;
  86427. }
  86428. // Do not block in blend mode.
  86429. if (material.needAlphaBlendingForMesh(mesh)) {
  86430. return;
  86431. }
  86432. // Culling
  86433. engine.setState(material.backFaceCulling);
  86434. // Managing instances
  86435. var batch = mesh._getInstancesRenderList(subMesh._id);
  86436. if (batch.mustReturn) {
  86437. return;
  86438. }
  86439. // Early Exit per mesh
  86440. if (!this._shouldRenderMesh(mesh)) {
  86441. return;
  86442. }
  86443. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86444. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86445. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86446. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86447. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86448. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86449. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86450. // Alpha test
  86451. if (material && material.needAlphaTesting()) {
  86452. var alphaTexture = material.getAlphaTestTexture();
  86453. if (alphaTexture) {
  86454. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86455. var textureMatrix = alphaTexture.getTextureMatrix();
  86456. if (textureMatrix) {
  86457. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86458. }
  86459. }
  86460. }
  86461. // Glow emissive only
  86462. if (this._emissiveTextureAndColor.texture) {
  86463. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86464. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86465. }
  86466. // Bones
  86467. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86468. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86469. }
  86470. // Morph targets
  86471. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  86472. // Draw
  86473. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86474. }
  86475. else {
  86476. // Need to reset refresh rate of the shadowMap
  86477. this._mainTexture.resetRefreshCounter();
  86478. }
  86479. };
  86480. /**
  86481. * Rebuild the required buffers.
  86482. * @ignore Internal use only.
  86483. */
  86484. EffectLayer.prototype._rebuild = function () {
  86485. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86486. if (vb) {
  86487. vb._rebuild();
  86488. }
  86489. this._generateIndexBuffer();
  86490. };
  86491. /**
  86492. * Dispose only the render target textures and post process.
  86493. */
  86494. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86495. this._mainTexture.dispose();
  86496. for (var i = 0; i < this._postProcesses.length; i++) {
  86497. if (this._postProcesses[i]) {
  86498. this._postProcesses[i].dispose();
  86499. }
  86500. }
  86501. this._postProcesses = [];
  86502. for (var i = 0; i < this._textures.length; i++) {
  86503. if (this._textures[i]) {
  86504. this._textures[i].dispose();
  86505. }
  86506. }
  86507. this._textures = [];
  86508. };
  86509. /**
  86510. * Dispose the highlight layer and free resources.
  86511. */
  86512. EffectLayer.prototype.dispose = function () {
  86513. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86514. if (vertexBuffer) {
  86515. vertexBuffer.dispose();
  86516. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86517. }
  86518. if (this._indexBuffer) {
  86519. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86520. this._indexBuffer = null;
  86521. }
  86522. // Clean textures and post processes
  86523. this._disposeTextureAndPostProcesses();
  86524. // Remove from scene
  86525. var index = this._scene.effectLayers.indexOf(this, 0);
  86526. if (index > -1) {
  86527. this._scene.effectLayers.splice(index, 1);
  86528. }
  86529. // Callback
  86530. this.onDisposeObservable.notifyObservers(this);
  86531. this.onDisposeObservable.clear();
  86532. this.onBeforeRenderMainTextureObservable.clear();
  86533. this.onBeforeComposeObservable.clear();
  86534. this.onAfterComposeObservable.clear();
  86535. this.onSizeChangedObservable.clear();
  86536. };
  86537. return EffectLayer;
  86538. }());
  86539. BABYLON.EffectLayer = EffectLayer;
  86540. })(BABYLON || (BABYLON = {}));
  86541. //# sourceMappingURL=babylon.effectLayer.js.map
  86542. "use strict";
  86543. var BABYLON;
  86544. (function (BABYLON) {
  86545. /**
  86546. * Special Glow Blur post process only blurring the alpha channel
  86547. * It enforces keeping the most luminous color in the color channel.
  86548. */
  86549. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86550. __extends(GlowBlurPostProcess, _super);
  86551. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86553. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86554. _this.direction = direction;
  86555. _this.kernel = kernel;
  86556. _this.onApplyObservable.add(function (effect) {
  86557. effect.setFloat2("screenSize", _this.width, _this.height);
  86558. effect.setVector2("direction", _this.direction);
  86559. effect.setFloat("blurWidth", _this.kernel);
  86560. });
  86561. return _this;
  86562. }
  86563. return GlowBlurPostProcess;
  86564. }(BABYLON.PostProcess));
  86565. /**
  86566. * The highlight layer Helps adding a glow effect around a mesh.
  86567. *
  86568. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86569. * glowy meshes to your scene.
  86570. *
  86571. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86572. */
  86573. var HighlightLayer = /** @class */ (function (_super) {
  86574. __extends(HighlightLayer, _super);
  86575. /**
  86576. * Instantiates a new highlight Layer and references it to the scene..
  86577. * @param name The name of the layer
  86578. * @param scene The scene to use the layer in
  86579. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86580. */
  86581. function HighlightLayer(name, scene, options) {
  86582. var _this = _super.call(this, name, scene) || this;
  86583. _this.name = name;
  86584. /**
  86585. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86586. */
  86587. _this.innerGlow = true;
  86588. /**
  86589. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86590. */
  86591. _this.outerGlow = true;
  86592. /**
  86593. * An event triggered when the highlight layer is being blurred.
  86594. */
  86595. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86596. /**
  86597. * An event triggered when the highlight layer has been blurred.
  86598. */
  86599. _this.onAfterBlurObservable = new BABYLON.Observable();
  86600. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86601. _this._meshes = {};
  86602. _this._excludedMeshes = {};
  86603. _this.neutralColor = HighlightLayer.NeutralColor;
  86604. // Warn on stencil
  86605. if (!_this._engine.isStencilEnable) {
  86606. 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 }");
  86607. }
  86608. // Adapt options
  86609. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86610. // Initialize the layer
  86611. _this._init({
  86612. alphaBlendingMode: _this._options.alphaBlendingMode,
  86613. camera: _this._options.camera,
  86614. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86615. mainTextureRatio: _this._options.mainTextureRatio
  86616. });
  86617. // Do not render as long as no meshes have been added
  86618. _this._shouldRender = false;
  86619. return _this;
  86620. }
  86621. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86622. /**
  86623. * Gets the horizontal size of the blur.
  86624. */
  86625. get: function () {
  86626. return this._horizontalBlurPostprocess.kernel;
  86627. },
  86628. /**
  86629. * Specifies the horizontal size of the blur.
  86630. */
  86631. set: function (value) {
  86632. this._horizontalBlurPostprocess.kernel = value;
  86633. },
  86634. enumerable: true,
  86635. configurable: true
  86636. });
  86637. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86638. /**
  86639. * Gets the vertical size of the blur.
  86640. */
  86641. get: function () {
  86642. return this._verticalBlurPostprocess.kernel;
  86643. },
  86644. /**
  86645. * Specifies the vertical size of the blur.
  86646. */
  86647. set: function (value) {
  86648. this._verticalBlurPostprocess.kernel = value;
  86649. },
  86650. enumerable: true,
  86651. configurable: true
  86652. });
  86653. /**
  86654. * Get the effect name of the layer.
  86655. * @return The effect name
  86656. */
  86657. HighlightLayer.prototype.getEffectName = function () {
  86658. return HighlightLayer.EffectName;
  86659. };
  86660. /**
  86661. * Create the merge effect. This is the shader use to blit the information back
  86662. * to the main canvas at the end of the scene rendering.
  86663. */
  86664. HighlightLayer.prototype._createMergeEffect = function () {
  86665. // Effect
  86666. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86667. };
  86668. /**
  86669. * Creates the render target textures and post processes used in the highlight layer.
  86670. */
  86671. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86672. var _this = this;
  86673. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86674. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86675. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86676. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86677. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86678. width: blurTextureWidth,
  86679. height: blurTextureHeight
  86680. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86681. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86682. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86683. this._blurTexture.anisotropicFilteringLevel = 16;
  86684. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86685. this._blurTexture.renderParticles = false;
  86686. this._blurTexture.ignoreCameraViewport = true;
  86687. this._textures = [this._blurTexture];
  86688. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86689. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86690. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86691. effect.setTexture("textureSampler", _this._mainTexture);
  86692. });
  86693. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86694. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86695. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86696. });
  86697. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86698. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86699. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86700. });
  86701. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86702. }
  86703. else {
  86704. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86705. width: blurTextureWidth,
  86706. height: blurTextureHeight
  86707. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86708. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86709. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86710. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86711. effect.setTexture("textureSampler", _this._mainTexture);
  86712. });
  86713. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86714. width: blurTextureWidth,
  86715. height: blurTextureHeight
  86716. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86717. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86718. }
  86719. this._mainTexture.onAfterUnbindObservable.add(function () {
  86720. _this.onBeforeBlurObservable.notifyObservers(_this);
  86721. var internalTexture = _this._blurTexture.getInternalTexture();
  86722. if (internalTexture) {
  86723. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86724. }
  86725. _this.onAfterBlurObservable.notifyObservers(_this);
  86726. });
  86727. // Prevent autoClear.
  86728. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86729. };
  86730. /**
  86731. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86732. */
  86733. HighlightLayer.prototype.needStencil = function () {
  86734. return true;
  86735. };
  86736. /**
  86737. * Checks for the readiness of the element composing the layer.
  86738. * @param subMesh the mesh to check for
  86739. * @param useInstances specify wether or not to use instances to render the mesh
  86740. * @param emissiveTexture the associated emissive texture used to generate the glow
  86741. * @return true if ready otherwise, false
  86742. */
  86743. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86744. var material = subMesh.getMaterial();
  86745. var mesh = subMesh.getRenderingMesh();
  86746. if (!material || !mesh || !this._meshes) {
  86747. return false;
  86748. }
  86749. var emissiveTexture = null;
  86750. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86751. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86752. emissiveTexture = material.emissiveTexture;
  86753. }
  86754. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86755. };
  86756. /**
  86757. * Implementation specific of rendering the generating effect on the main canvas.
  86758. * @param effect The effect used to render through
  86759. */
  86760. HighlightLayer.prototype._internalRender = function (effect) {
  86761. // Texture
  86762. effect.setTexture("textureSampler", this._blurTexture);
  86763. // Cache
  86764. var engine = this._engine;
  86765. var previousStencilBuffer = engine.getStencilBuffer();
  86766. var previousStencilFunction = engine.getStencilFunction();
  86767. var previousStencilMask = engine.getStencilMask();
  86768. var previousStencilOperationPass = engine.getStencilOperationPass();
  86769. var previousStencilOperationFail = engine.getStencilOperationFail();
  86770. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86771. var previousStencilReference = engine.getStencilFunctionReference();
  86772. // Stencil operations
  86773. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86774. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86775. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86776. // Draw order
  86777. engine.setStencilMask(0x00);
  86778. engine.setStencilBuffer(true);
  86779. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86780. // 2 passes inner outer
  86781. if (this.outerGlow) {
  86782. effect.setFloat("offset", 0);
  86783. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86784. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86785. }
  86786. if (this.innerGlow) {
  86787. effect.setFloat("offset", 1);
  86788. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86789. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86790. }
  86791. // Restore Cache
  86792. engine.setStencilFunction(previousStencilFunction);
  86793. engine.setStencilMask(previousStencilMask);
  86794. engine.setStencilBuffer(previousStencilBuffer);
  86795. engine.setStencilOperationPass(previousStencilOperationPass);
  86796. engine.setStencilOperationFail(previousStencilOperationFail);
  86797. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86798. engine.setStencilFunctionReference(previousStencilReference);
  86799. };
  86800. /**
  86801. * Returns true if the layer contains information to display, otherwise false.
  86802. */
  86803. HighlightLayer.prototype.shouldRender = function () {
  86804. if (_super.prototype.shouldRender.call(this)) {
  86805. return this._meshes ? true : false;
  86806. }
  86807. return false;
  86808. };
  86809. /**
  86810. * Returns true if the mesh should render, otherwise false.
  86811. * @param mesh The mesh to render
  86812. * @returns true if it should render otherwise false
  86813. */
  86814. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86815. // Excluded Mesh
  86816. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86817. return false;
  86818. }
  86819. ;
  86820. return true;
  86821. };
  86822. /**
  86823. * Sets the required values for both the emissive texture and and the main color.
  86824. */
  86825. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86826. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86827. if (highlightLayerMesh) {
  86828. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86829. }
  86830. else {
  86831. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86832. }
  86833. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86834. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86835. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86836. }
  86837. else {
  86838. this._emissiveTextureAndColor.texture = null;
  86839. }
  86840. };
  86841. /**
  86842. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86843. * @param mesh The mesh to exclude from the highlight layer
  86844. */
  86845. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86846. if (!this._excludedMeshes) {
  86847. return;
  86848. }
  86849. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86850. if (!meshExcluded) {
  86851. this._excludedMeshes[mesh.uniqueId] = {
  86852. mesh: mesh,
  86853. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86854. mesh.getEngine().setStencilBuffer(false);
  86855. }),
  86856. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86857. mesh.getEngine().setStencilBuffer(true);
  86858. }),
  86859. };
  86860. }
  86861. };
  86862. /**
  86863. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86864. * @param mesh The mesh to highlight
  86865. */
  86866. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86867. if (!this._excludedMeshes) {
  86868. return;
  86869. }
  86870. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86871. if (meshExcluded) {
  86872. if (meshExcluded.beforeRender) {
  86873. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86874. }
  86875. if (meshExcluded.afterRender) {
  86876. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86877. }
  86878. }
  86879. this._excludedMeshes[mesh.uniqueId] = null;
  86880. };
  86881. /**
  86882. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86883. * @param mesh mesh to test
  86884. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86885. */
  86886. HighlightLayer.prototype.hasMesh = function (mesh) {
  86887. if (!this._meshes) {
  86888. return false;
  86889. }
  86890. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86891. };
  86892. /**
  86893. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86894. * @param mesh The mesh to highlight
  86895. * @param color The color of the highlight
  86896. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86897. */
  86898. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86899. var _this = this;
  86900. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86901. if (!this._meshes) {
  86902. return;
  86903. }
  86904. var meshHighlight = this._meshes[mesh.uniqueId];
  86905. if (meshHighlight) {
  86906. meshHighlight.color = color;
  86907. }
  86908. else {
  86909. this._meshes[mesh.uniqueId] = {
  86910. mesh: mesh,
  86911. color: color,
  86912. // Lambda required for capture due to Observable this context
  86913. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86914. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86915. _this._defaultStencilReference(mesh);
  86916. }
  86917. else {
  86918. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86919. }
  86920. }),
  86921. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86922. glowEmissiveOnly: glowEmissiveOnly
  86923. };
  86924. }
  86925. this._shouldRender = true;
  86926. };
  86927. /**
  86928. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86929. * @param mesh The mesh to highlight
  86930. */
  86931. HighlightLayer.prototype.removeMesh = function (mesh) {
  86932. if (!this._meshes) {
  86933. return;
  86934. }
  86935. var meshHighlight = this._meshes[mesh.uniqueId];
  86936. if (meshHighlight) {
  86937. if (meshHighlight.observerHighlight) {
  86938. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86939. }
  86940. if (meshHighlight.observerDefault) {
  86941. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86942. }
  86943. delete this._meshes[mesh.uniqueId];
  86944. }
  86945. this._shouldRender = false;
  86946. for (var meshHighlightToCheck in this._meshes) {
  86947. if (this._meshes[meshHighlightToCheck]) {
  86948. this._shouldRender = true;
  86949. break;
  86950. }
  86951. }
  86952. };
  86953. /**
  86954. * Force the stencil to the normal expected value for none glowing parts
  86955. */
  86956. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86957. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86958. };
  86959. /**
  86960. * Free any resources and references associated to a mesh.
  86961. * Internal use
  86962. * @param mesh The mesh to free.
  86963. */
  86964. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86965. this.removeMesh(mesh);
  86966. this.removeExcludedMesh(mesh);
  86967. };
  86968. /**
  86969. * Dispose the highlight layer and free resources.
  86970. */
  86971. HighlightLayer.prototype.dispose = function () {
  86972. if (this._meshes) {
  86973. // Clean mesh references
  86974. for (var id in this._meshes) {
  86975. var meshHighlight = this._meshes[id];
  86976. if (meshHighlight && meshHighlight.mesh) {
  86977. if (meshHighlight.observerHighlight) {
  86978. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86979. }
  86980. if (meshHighlight.observerDefault) {
  86981. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86982. }
  86983. }
  86984. }
  86985. this._meshes = null;
  86986. }
  86987. if (this._excludedMeshes) {
  86988. for (var id in this._excludedMeshes) {
  86989. var meshHighlight = this._excludedMeshes[id];
  86990. if (meshHighlight) {
  86991. if (meshHighlight.beforeRender) {
  86992. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86993. }
  86994. if (meshHighlight.afterRender) {
  86995. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86996. }
  86997. }
  86998. }
  86999. this._excludedMeshes = null;
  87000. }
  87001. _super.prototype.dispose.call(this);
  87002. };
  87003. /**
  87004. * Effect Name of the highlight layer.
  87005. */
  87006. HighlightLayer.EffectName = "HighlightLayer";
  87007. /**
  87008. * The neutral color used during the preparation of the glow effect.
  87009. * This is black by default as the blend operation is a blend operation.
  87010. */
  87011. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87012. /**
  87013. * Stencil value used for glowing meshes.
  87014. */
  87015. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87016. /**
  87017. * Stencil value used for the other meshes in the scene.
  87018. */
  87019. HighlightLayer.NormalMeshStencilReference = 0x01;
  87020. return HighlightLayer;
  87021. }(BABYLON.EffectLayer));
  87022. BABYLON.HighlightLayer = HighlightLayer;
  87023. })(BABYLON || (BABYLON = {}));
  87024. //# sourceMappingURL=babylon.highlightLayer.js.map
  87025. "use strict";
  87026. var BABYLON;
  87027. (function (BABYLON) {
  87028. /**
  87029. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87030. *
  87031. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87032. * glowy meshes to your scene.
  87033. *
  87034. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87035. */
  87036. var GlowLayer = /** @class */ (function (_super) {
  87037. __extends(GlowLayer, _super);
  87038. /**
  87039. * Instantiates a new glow Layer and references it to the scene.
  87040. * @param name The name of the layer
  87041. * @param scene The scene to use the layer in
  87042. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87043. */
  87044. function GlowLayer(name, scene, options) {
  87045. var _this = _super.call(this, name, scene) || this;
  87046. _this.name = name;
  87047. _this._intensity = 1.0;
  87048. _this._includedOnlyMeshes = [];
  87049. _this._excludedMeshes = [];
  87050. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87051. // Adapt options
  87052. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87053. // Initialize the layer
  87054. _this._init({
  87055. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87056. camera: _this._options.camera,
  87057. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87058. mainTextureRatio: _this._options.mainTextureRatio
  87059. });
  87060. return _this;
  87061. }
  87062. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87063. /**
  87064. * Gets the kernel size of the blur.
  87065. */
  87066. get: function () {
  87067. return this._horizontalBlurPostprocess1.kernel;
  87068. },
  87069. /**
  87070. * Sets the kernel size of the blur.
  87071. */
  87072. set: function (value) {
  87073. this._horizontalBlurPostprocess1.kernel = value;
  87074. this._verticalBlurPostprocess1.kernel = value;
  87075. this._horizontalBlurPostprocess2.kernel = value;
  87076. this._verticalBlurPostprocess2.kernel = value;
  87077. },
  87078. enumerable: true,
  87079. configurable: true
  87080. });
  87081. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87082. /**
  87083. * Gets the glow intensity.
  87084. */
  87085. get: function () {
  87086. return this._intensity;
  87087. },
  87088. /**
  87089. * Sets the glow intensity.
  87090. */
  87091. set: function (value) {
  87092. this._intensity = value;
  87093. },
  87094. enumerable: true,
  87095. configurable: true
  87096. });
  87097. /**
  87098. * Get the effect name of the layer.
  87099. * @return The effect name
  87100. */
  87101. GlowLayer.prototype.getEffectName = function () {
  87102. return GlowLayer.EffectName;
  87103. };
  87104. /**
  87105. * Create the merge effect. This is the shader use to blit the information back
  87106. * to the main canvas at the end of the scene rendering.
  87107. */
  87108. GlowLayer.prototype._createMergeEffect = function () {
  87109. // Effect
  87110. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87111. };
  87112. /**
  87113. * Creates the render target textures and post processes used in the glow layer.
  87114. */
  87115. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87116. var _this = this;
  87117. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87118. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87119. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87120. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87121. var textureType = 0;
  87122. if (this._engine.getCaps().textureHalfFloatRender) {
  87123. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87124. }
  87125. else {
  87126. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87127. }
  87128. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87129. width: blurTextureWidth,
  87130. height: blurTextureHeight
  87131. }, this._scene, false, true, textureType);
  87132. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87133. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87134. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87135. this._blurTexture1.renderParticles = false;
  87136. this._blurTexture1.ignoreCameraViewport = true;
  87137. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87138. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87139. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87140. width: blurTextureWidth2,
  87141. height: blurTextureHeight2
  87142. }, this._scene, false, true, textureType);
  87143. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87144. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87145. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87146. this._blurTexture2.renderParticles = false;
  87147. this._blurTexture2.ignoreCameraViewport = true;
  87148. this._textures = [this._blurTexture1, this._blurTexture2];
  87149. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87150. width: blurTextureWidth,
  87151. height: blurTextureHeight
  87152. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87153. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87154. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87155. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87156. effect.setTexture("textureSampler", _this._mainTexture);
  87157. });
  87158. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87159. width: blurTextureWidth,
  87160. height: blurTextureHeight
  87161. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87162. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87163. width: blurTextureWidth2,
  87164. height: blurTextureHeight2
  87165. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87166. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87167. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87168. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87169. effect.setTexture("textureSampler", _this._blurTexture1);
  87170. });
  87171. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87172. width: blurTextureWidth2,
  87173. height: blurTextureHeight2
  87174. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87175. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87176. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87177. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87178. this._mainTexture.samples = this._options.mainTextureSamples;
  87179. this._mainTexture.onAfterUnbindObservable.add(function () {
  87180. var internalTexture = _this._blurTexture1.getInternalTexture();
  87181. if (internalTexture) {
  87182. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87183. internalTexture = _this._blurTexture2.getInternalTexture();
  87184. if (internalTexture) {
  87185. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87186. }
  87187. }
  87188. });
  87189. // Prevent autoClear.
  87190. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87191. };
  87192. /**
  87193. * Checks for the readiness of the element composing the layer.
  87194. * @param subMesh the mesh to check for
  87195. * @param useInstances specify wether or not to use instances to render the mesh
  87196. * @param emissiveTexture the associated emissive texture used to generate the glow
  87197. * @return true if ready otherwise, false
  87198. */
  87199. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87200. var material = subMesh.getMaterial();
  87201. var mesh = subMesh.getRenderingMesh();
  87202. if (!material || !mesh) {
  87203. return false;
  87204. }
  87205. var emissiveTexture = material.emissiveTexture;
  87206. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87207. };
  87208. /**
  87209. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87210. */
  87211. GlowLayer.prototype.needStencil = function () {
  87212. return false;
  87213. };
  87214. /**
  87215. * Implementation specific of rendering the generating effect on the main canvas.
  87216. * @param effect The effect used to render through
  87217. */
  87218. GlowLayer.prototype._internalRender = function (effect) {
  87219. // Texture
  87220. effect.setTexture("textureSampler", this._blurTexture1);
  87221. effect.setTexture("textureSampler2", this._blurTexture2);
  87222. effect.setFloat("offset", this._intensity);
  87223. // Cache
  87224. var engine = this._engine;
  87225. var previousStencilBuffer = engine.getStencilBuffer();
  87226. // Draw order
  87227. engine.setStencilBuffer(false);
  87228. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87229. // Draw order
  87230. engine.setStencilBuffer(previousStencilBuffer);
  87231. };
  87232. /**
  87233. * Sets the required values for both the emissive texture and and the main color.
  87234. */
  87235. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87236. var textureLevel = 1.0;
  87237. if (this.customEmissiveTextureSelector) {
  87238. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87239. }
  87240. else {
  87241. if (material) {
  87242. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87243. if (this._emissiveTextureAndColor.texture) {
  87244. textureLevel = this._emissiveTextureAndColor.texture.level;
  87245. }
  87246. }
  87247. else {
  87248. this._emissiveTextureAndColor.texture = null;
  87249. }
  87250. }
  87251. if (this.customEmissiveColorSelector) {
  87252. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87253. }
  87254. else {
  87255. if (material.emissiveColor) {
  87256. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87257. }
  87258. else {
  87259. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87260. }
  87261. }
  87262. };
  87263. /**
  87264. * Returns true if the mesh should render, otherwise false.
  87265. * @param mesh The mesh to render
  87266. * @returns true if it should render otherwise false
  87267. */
  87268. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87269. return this.hasMesh(mesh);
  87270. };
  87271. /**
  87272. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87273. * @param mesh The mesh to exclude from the glow layer
  87274. */
  87275. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87276. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87277. this._excludedMeshes.push(mesh.uniqueId);
  87278. }
  87279. };
  87280. /**
  87281. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87282. * @param mesh The mesh to remove
  87283. */
  87284. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87285. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87286. if (index !== -1) {
  87287. this._excludedMeshes.splice(index, 1);
  87288. }
  87289. };
  87290. /**
  87291. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87292. * @param mesh The mesh to include in the glow layer
  87293. */
  87294. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87295. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87296. this._includedOnlyMeshes.push(mesh.uniqueId);
  87297. }
  87298. };
  87299. /**
  87300. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87301. * @param mesh The mesh to remove
  87302. */
  87303. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87304. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87305. if (index !== -1) {
  87306. this._includedOnlyMeshes.splice(index, 1);
  87307. }
  87308. };
  87309. /**
  87310. * Determine if a given mesh will be used in the glow layer
  87311. * @param mesh The mesh to test
  87312. * @returns true if the mesh will be highlighted by the current glow layer
  87313. */
  87314. GlowLayer.prototype.hasMesh = function (mesh) {
  87315. // Included Mesh
  87316. if (this._includedOnlyMeshes.length) {
  87317. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87318. }
  87319. ;
  87320. // Excluded Mesh
  87321. if (this._excludedMeshes.length) {
  87322. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87323. }
  87324. ;
  87325. return true;
  87326. };
  87327. /**
  87328. * Free any resources and references associated to a mesh.
  87329. * Internal use
  87330. * @param mesh The mesh to free.
  87331. */
  87332. GlowLayer.prototype._disposeMesh = function (mesh) {
  87333. this.removeIncludedOnlyMesh(mesh);
  87334. this.removeExcludedMesh(mesh);
  87335. };
  87336. /**
  87337. * Effect Name of the layer.
  87338. */
  87339. GlowLayer.EffectName = "GlowLayer";
  87340. /**
  87341. * The default blur kernel size used for the glow.
  87342. */
  87343. GlowLayer.DefaultBlurKernelSize = 32;
  87344. /**
  87345. * The default texture size ratio used for the glow.
  87346. */
  87347. GlowLayer.DefaultTextureRatio = 0.5;
  87348. return GlowLayer;
  87349. }(BABYLON.EffectLayer));
  87350. BABYLON.GlowLayer = GlowLayer;
  87351. })(BABYLON || (BABYLON = {}));
  87352. //# sourceMappingURL=babylon.glowLayer.js.map
  87353. "use strict";
  87354. var BABYLON;
  87355. (function (BABYLON) {
  87356. /**
  87357. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87358. */
  87359. var AssetTaskState;
  87360. (function (AssetTaskState) {
  87361. /**
  87362. * Initialization
  87363. */
  87364. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87365. /**
  87366. * Running
  87367. */
  87368. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87369. /**
  87370. * Done
  87371. */
  87372. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87373. /**
  87374. * Error
  87375. */
  87376. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87377. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87378. /**
  87379. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87380. */
  87381. var AbstractAssetTask = /** @class */ (function () {
  87382. /**
  87383. * Creates a new {BABYLON.AssetsManager}
  87384. * @param name defines the name of the task
  87385. */
  87386. function AbstractAssetTask(
  87387. /**
  87388. * Task name
  87389. */ name) {
  87390. this.name = name;
  87391. this._isCompleted = false;
  87392. this._taskState = AssetTaskState.INIT;
  87393. }
  87394. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87395. /**
  87396. * Get if the task is completed
  87397. */
  87398. get: function () {
  87399. return this._isCompleted;
  87400. },
  87401. enumerable: true,
  87402. configurable: true
  87403. });
  87404. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87405. /**
  87406. * Gets the current state of the task
  87407. */
  87408. get: function () {
  87409. return this._taskState;
  87410. },
  87411. enumerable: true,
  87412. configurable: true
  87413. });
  87414. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87415. /**
  87416. * Gets the current error object (if task is in error)
  87417. */
  87418. get: function () {
  87419. return this._errorObject;
  87420. },
  87421. enumerable: true,
  87422. configurable: true
  87423. });
  87424. /**
  87425. * Internal only
  87426. * @ignore
  87427. */
  87428. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87429. if (this._errorObject) {
  87430. return;
  87431. }
  87432. this._errorObject = {
  87433. message: message,
  87434. exception: exception
  87435. };
  87436. };
  87437. /**
  87438. * Execute the current task
  87439. * @param scene defines the scene where you want your assets to be loaded
  87440. * @param onSuccess is a callback called when the task is successfully executed
  87441. * @param onError is a callback called if an error occurs
  87442. */
  87443. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87444. var _this = this;
  87445. this._taskState = AssetTaskState.RUNNING;
  87446. this.runTask(scene, function () {
  87447. _this.onDoneCallback(onSuccess, onError);
  87448. }, function (msg, exception) {
  87449. _this.onErrorCallback(onError, msg, exception);
  87450. });
  87451. };
  87452. /**
  87453. * Execute the current task
  87454. * @param scene defines the scene where you want your assets to be loaded
  87455. * @param onSuccess is a callback called when the task is successfully executed
  87456. * @param onError is a callback called if an error occurs
  87457. */
  87458. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87459. throw new Error("runTask is not implemented");
  87460. };
  87461. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87462. this._taskState = AssetTaskState.ERROR;
  87463. this._errorObject = {
  87464. message: message,
  87465. exception: exception
  87466. };
  87467. if (this.onError) {
  87468. this.onError(this, message, exception);
  87469. }
  87470. onError();
  87471. };
  87472. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87473. try {
  87474. this._taskState = AssetTaskState.DONE;
  87475. this._isCompleted = true;
  87476. if (this.onSuccess) {
  87477. this.onSuccess(this);
  87478. }
  87479. onSuccess();
  87480. }
  87481. catch (e) {
  87482. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87483. }
  87484. };
  87485. return AbstractAssetTask;
  87486. }());
  87487. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87488. /**
  87489. * Class used to share progress information about assets loading
  87490. */
  87491. var AssetsProgressEvent = /** @class */ (function () {
  87492. /**
  87493. * Creates a {BABYLON.AssetsProgressEvent}
  87494. * @param remainingCount defines the number of remaining tasks to process
  87495. * @param totalCount defines the total number of tasks
  87496. * @param task defines the task that was just processed
  87497. */
  87498. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87499. this.remainingCount = remainingCount;
  87500. this.totalCount = totalCount;
  87501. this.task = task;
  87502. }
  87503. return AssetsProgressEvent;
  87504. }());
  87505. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87506. /**
  87507. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87508. */
  87509. var MeshAssetTask = /** @class */ (function (_super) {
  87510. __extends(MeshAssetTask, _super);
  87511. /**
  87512. * Creates a new {BABYLON.MeshAssetTask}
  87513. * @param name defines the name of the task
  87514. * @param meshesNames defines the list of mesh's names you want to load
  87515. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87516. * @param sceneFilename defines the filename of the scene to load from
  87517. */
  87518. function MeshAssetTask(
  87519. /**
  87520. * Defines the name of the task
  87521. */
  87522. name,
  87523. /**
  87524. * Defines the list of mesh's names you want to load
  87525. */
  87526. meshesNames,
  87527. /**
  87528. * Defines the root url to use as a base to load your meshes and associated resources
  87529. */
  87530. rootUrl,
  87531. /**
  87532. * Defines the filename of the scene to load from
  87533. */
  87534. sceneFilename) {
  87535. var _this = _super.call(this, name) || this;
  87536. _this.name = name;
  87537. _this.meshesNames = meshesNames;
  87538. _this.rootUrl = rootUrl;
  87539. _this.sceneFilename = sceneFilename;
  87540. return _this;
  87541. }
  87542. /**
  87543. * Execute the current task
  87544. * @param scene defines the scene where you want your assets to be loaded
  87545. * @param onSuccess is a callback called when the task is successfully executed
  87546. * @param onError is a callback called if an error occurs
  87547. */
  87548. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87549. var _this = this;
  87550. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87551. _this.loadedMeshes = meshes;
  87552. _this.loadedParticleSystems = particleSystems;
  87553. _this.loadedSkeletons = skeletons;
  87554. onSuccess();
  87555. }, null, function (scene, message, exception) {
  87556. onError(message, exception);
  87557. });
  87558. };
  87559. return MeshAssetTask;
  87560. }(AbstractAssetTask));
  87561. BABYLON.MeshAssetTask = MeshAssetTask;
  87562. /**
  87563. * Define a task used by {BABYLON.AssetsManager} to load text content
  87564. */
  87565. var TextFileAssetTask = /** @class */ (function (_super) {
  87566. __extends(TextFileAssetTask, _super);
  87567. /**
  87568. * Creates a new TextFileAssetTask object
  87569. * @param name defines the name of the task
  87570. * @param url defines the location of the file to load
  87571. */
  87572. function TextFileAssetTask(
  87573. /**
  87574. * Defines the name of the task
  87575. */
  87576. name,
  87577. /**
  87578. * Defines the location of the file to load
  87579. */
  87580. url) {
  87581. var _this = _super.call(this, name) || this;
  87582. _this.name = name;
  87583. _this.url = url;
  87584. return _this;
  87585. }
  87586. /**
  87587. * Execute the current task
  87588. * @param scene defines the scene where you want your assets to be loaded
  87589. * @param onSuccess is a callback called when the task is successfully executed
  87590. * @param onError is a callback called if an error occurs
  87591. */
  87592. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87593. var _this = this;
  87594. scene._loadFile(this.url, function (data) {
  87595. _this.text = data;
  87596. onSuccess();
  87597. }, undefined, false, false, function (request, exception) {
  87598. if (request) {
  87599. onError(request.status + " " + request.statusText, exception);
  87600. }
  87601. });
  87602. };
  87603. return TextFileAssetTask;
  87604. }(AbstractAssetTask));
  87605. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87606. /**
  87607. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87608. */
  87609. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87610. __extends(BinaryFileAssetTask, _super);
  87611. /**
  87612. * Creates a new BinaryFileAssetTask object
  87613. * @param name defines the name of the new task
  87614. * @param url defines the location of the file to load
  87615. */
  87616. function BinaryFileAssetTask(
  87617. /**
  87618. * Defines the name of the task
  87619. */
  87620. name,
  87621. /**
  87622. * Defines the location of the file to load
  87623. */
  87624. url) {
  87625. var _this = _super.call(this, name) || this;
  87626. _this.name = name;
  87627. _this.url = url;
  87628. return _this;
  87629. }
  87630. /**
  87631. * Execute the current task
  87632. * @param scene defines the scene where you want your assets to be loaded
  87633. * @param onSuccess is a callback called when the task is successfully executed
  87634. * @param onError is a callback called if an error occurs
  87635. */
  87636. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87637. var _this = this;
  87638. scene._loadFile(this.url, function (data) {
  87639. _this.data = data;
  87640. onSuccess();
  87641. }, undefined, true, true, function (request, exception) {
  87642. if (request) {
  87643. onError(request.status + " " + request.statusText, exception);
  87644. }
  87645. });
  87646. };
  87647. return BinaryFileAssetTask;
  87648. }(AbstractAssetTask));
  87649. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87650. /**
  87651. * Define a task used by {BABYLON.AssetsManager} to load images
  87652. */
  87653. var ImageAssetTask = /** @class */ (function (_super) {
  87654. __extends(ImageAssetTask, _super);
  87655. /**
  87656. * Creates a new ImageAssetTask
  87657. * @param name defines the name of the task
  87658. * @param url defines the location of the image to load
  87659. */
  87660. function ImageAssetTask(
  87661. /**
  87662. * Defines the name of the task
  87663. */
  87664. name,
  87665. /**
  87666. * Defines the location of the image to load
  87667. */
  87668. url) {
  87669. var _this = _super.call(this, name) || this;
  87670. _this.name = name;
  87671. _this.url = url;
  87672. return _this;
  87673. }
  87674. /**
  87675. * Execute the current task
  87676. * @param scene defines the scene where you want your assets to be loaded
  87677. * @param onSuccess is a callback called when the task is successfully executed
  87678. * @param onError is a callback called if an error occurs
  87679. */
  87680. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87681. var _this = this;
  87682. var img = new Image();
  87683. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87684. img.onload = function () {
  87685. _this.image = img;
  87686. onSuccess();
  87687. };
  87688. img.onerror = function (err) {
  87689. onError("Error loading image", err);
  87690. };
  87691. img.src = this.url;
  87692. };
  87693. return ImageAssetTask;
  87694. }(AbstractAssetTask));
  87695. BABYLON.ImageAssetTask = ImageAssetTask;
  87696. /**
  87697. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87698. */
  87699. var TextureAssetTask = /** @class */ (function (_super) {
  87700. __extends(TextureAssetTask, _super);
  87701. /**
  87702. * Creates a new TextureAssetTask object
  87703. * @param name defines the name of the task
  87704. * @param url defines the location of the file to load
  87705. * @param noMipmap defines if mipmap should not be generated (default is false)
  87706. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87707. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87708. */
  87709. function TextureAssetTask(
  87710. /**
  87711. * Defines the name of the task
  87712. */
  87713. name,
  87714. /**
  87715. * Defines the location of the file to load
  87716. */
  87717. url,
  87718. /**
  87719. * Defines if mipmap should not be generated (default is false)
  87720. */
  87721. noMipmap,
  87722. /**
  87723. * Defines if texture must be inverted on Y axis (default is false)
  87724. */
  87725. invertY,
  87726. /**
  87727. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87728. */
  87729. samplingMode) {
  87730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87731. var _this = _super.call(this, name) || this;
  87732. _this.name = name;
  87733. _this.url = url;
  87734. _this.noMipmap = noMipmap;
  87735. _this.invertY = invertY;
  87736. _this.samplingMode = samplingMode;
  87737. return _this;
  87738. }
  87739. /**
  87740. * Execute the current task
  87741. * @param scene defines the scene where you want your assets to be loaded
  87742. * @param onSuccess is a callback called when the task is successfully executed
  87743. * @param onError is a callback called if an error occurs
  87744. */
  87745. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87746. var onload = function () {
  87747. onSuccess();
  87748. };
  87749. var onerror = function (message, exception) {
  87750. onError(message, exception);
  87751. };
  87752. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87753. };
  87754. return TextureAssetTask;
  87755. }(AbstractAssetTask));
  87756. BABYLON.TextureAssetTask = TextureAssetTask;
  87757. /**
  87758. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87759. */
  87760. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87761. __extends(CubeTextureAssetTask, _super);
  87762. /**
  87763. * Creates a new CubeTextureAssetTask
  87764. * @param name defines the name of the task
  87765. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87766. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87767. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87768. * @param files defines the explicit list of files (undefined by default)
  87769. */
  87770. function CubeTextureAssetTask(
  87771. /**
  87772. * Defines the name of the task
  87773. */
  87774. name,
  87775. /**
  87776. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87777. */
  87778. url,
  87779. /**
  87780. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87781. */
  87782. extensions,
  87783. /**
  87784. * Defines if mipmaps should not be generated (default is false)
  87785. */
  87786. noMipmap,
  87787. /**
  87788. * Defines the explicit list of files (undefined by default)
  87789. */
  87790. files) {
  87791. var _this = _super.call(this, name) || this;
  87792. _this.name = name;
  87793. _this.url = url;
  87794. _this.extensions = extensions;
  87795. _this.noMipmap = noMipmap;
  87796. _this.files = files;
  87797. return _this;
  87798. }
  87799. /**
  87800. * Execute the current task
  87801. * @param scene defines the scene where you want your assets to be loaded
  87802. * @param onSuccess is a callback called when the task is successfully executed
  87803. * @param onError is a callback called if an error occurs
  87804. */
  87805. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87806. var onload = function () {
  87807. onSuccess();
  87808. };
  87809. var onerror = function (message, exception) {
  87810. onError(message, exception);
  87811. };
  87812. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87813. };
  87814. return CubeTextureAssetTask;
  87815. }(AbstractAssetTask));
  87816. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87817. /**
  87818. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87819. */
  87820. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87821. __extends(HDRCubeTextureAssetTask, _super);
  87822. /**
  87823. * Creates a new HDRCubeTextureAssetTask object
  87824. * @param name defines the name of the task
  87825. * @param url defines the location of the file to load
  87826. * @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.
  87827. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87828. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87829. * @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)
  87830. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87831. */
  87832. function HDRCubeTextureAssetTask(
  87833. /**
  87834. * Defines the name of the task
  87835. */
  87836. name,
  87837. /**
  87838. * Defines the location of the file to load
  87839. */
  87840. url,
  87841. /**
  87842. * 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.
  87843. */
  87844. size,
  87845. /**
  87846. * Defines if mipmaps should not be generated (default is false)
  87847. */
  87848. noMipmap,
  87849. /**
  87850. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87851. */
  87852. generateHarmonics,
  87853. /**
  87854. * 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)
  87855. */
  87856. useInGammaSpace,
  87857. /**
  87858. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87859. */
  87860. usePMREMGenerator) {
  87861. if (noMipmap === void 0) { noMipmap = false; }
  87862. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87863. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87864. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87865. var _this = _super.call(this, name) || this;
  87866. _this.name = name;
  87867. _this.url = url;
  87868. _this.size = size;
  87869. _this.noMipmap = noMipmap;
  87870. _this.generateHarmonics = generateHarmonics;
  87871. _this.useInGammaSpace = useInGammaSpace;
  87872. _this.usePMREMGenerator = usePMREMGenerator;
  87873. return _this;
  87874. }
  87875. /**
  87876. * Execute the current task
  87877. * @param scene defines the scene where you want your assets to be loaded
  87878. * @param onSuccess is a callback called when the task is successfully executed
  87879. * @param onError is a callback called if an error occurs
  87880. */
  87881. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87882. var onload = function () {
  87883. onSuccess();
  87884. };
  87885. var onerror = function (message, exception) {
  87886. onError(message, exception);
  87887. };
  87888. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87889. };
  87890. return HDRCubeTextureAssetTask;
  87891. }(AbstractAssetTask));
  87892. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87893. /**
  87894. * This class can be used to easily import assets into a scene
  87895. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87896. */
  87897. var AssetsManager = /** @class */ (function () {
  87898. /**
  87899. * Creates a new AssetsManager
  87900. * @param scene defines the scene to work on
  87901. */
  87902. function AssetsManager(scene) {
  87903. this._isLoading = false;
  87904. this._tasks = new Array();
  87905. this._waitingTasksCount = 0;
  87906. this._totalTasksCount = 0;
  87907. /**
  87908. * Observable called when all tasks are processed
  87909. */
  87910. this.onTaskSuccessObservable = new BABYLON.Observable();
  87911. /**
  87912. * Observable called when a task had an error
  87913. */
  87914. this.onTaskErrorObservable = new BABYLON.Observable();
  87915. /**
  87916. * Observable called when a task is successful
  87917. */
  87918. this.onTasksDoneObservable = new BABYLON.Observable();
  87919. /**
  87920. * Observable called when a task is done (whatever the result is)
  87921. */
  87922. this.onProgressObservable = new BABYLON.Observable();
  87923. /**
  87924. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87925. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87926. */
  87927. this.useDefaultLoadingScreen = true;
  87928. this._scene = scene;
  87929. }
  87930. /**
  87931. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87932. * @param taskName defines the name of the new task
  87933. * @param meshesNames defines the name of meshes to load
  87934. * @param rootUrl defines the root url to use to locate files
  87935. * @param sceneFilename defines the filename of the scene file
  87936. * @returns a new {BABYLON.MeshAssetTask} object
  87937. */
  87938. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87939. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87940. this._tasks.push(task);
  87941. return task;
  87942. };
  87943. /**
  87944. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87945. * @param taskName defines the name of the new task
  87946. * @param url defines the url of the file to load
  87947. * @returns a new {BABYLON.TextFileAssetTask} object
  87948. */
  87949. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87950. var task = new TextFileAssetTask(taskName, url);
  87951. this._tasks.push(task);
  87952. return task;
  87953. };
  87954. /**
  87955. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87956. * @param taskName defines the name of the new task
  87957. * @param url defines the url of the file to load
  87958. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87959. */
  87960. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87961. var task = new BinaryFileAssetTask(taskName, url);
  87962. this._tasks.push(task);
  87963. return task;
  87964. };
  87965. /**
  87966. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87967. * @param taskName defines the name of the new task
  87968. * @param url defines the url of the file to load
  87969. * @returns a new {BABYLON.ImageAssetTask} object
  87970. */
  87971. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87972. var task = new ImageAssetTask(taskName, url);
  87973. this._tasks.push(task);
  87974. return task;
  87975. };
  87976. /**
  87977. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87978. * @param taskName defines the name of the new task
  87979. * @param url defines the url of the file to load
  87980. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87981. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87982. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87983. * @returns a new {BABYLON.TextureAssetTask} object
  87984. */
  87985. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87987. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87988. this._tasks.push(task);
  87989. return task;
  87990. };
  87991. /**
  87992. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87993. * @param taskName defines the name of the new task
  87994. * @param url defines the url of the file to load
  87995. * @param extensions defines the extension to use to load the cube map (can be null)
  87996. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87997. * @param files defines the list of files to load (can be null)
  87998. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87999. */
  88000. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88001. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88002. this._tasks.push(task);
  88003. return task;
  88004. };
  88005. /**
  88006. *
  88007. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88008. * @param taskName defines the name of the new task
  88009. * @param url defines the url of the file to load
  88010. * @param size defines the size you want for the cubemap (can be null)
  88011. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88012. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88013. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88014. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88015. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88016. */
  88017. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88018. if (noMipmap === void 0) { noMipmap = false; }
  88019. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88020. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88021. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88022. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88023. this._tasks.push(task);
  88024. return task;
  88025. };
  88026. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88027. var _this = this;
  88028. this._waitingTasksCount--;
  88029. try {
  88030. if (task.taskState === AssetTaskState.DONE) {
  88031. // Let's remove successfull tasks
  88032. BABYLON.Tools.SetImmediate(function () {
  88033. var index = _this._tasks.indexOf(task);
  88034. if (index > -1) {
  88035. _this._tasks.splice(index, 1);
  88036. }
  88037. });
  88038. }
  88039. if (this.onProgress) {
  88040. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88041. }
  88042. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88043. }
  88044. catch (e) {
  88045. BABYLON.Tools.Error("Error running progress callbacks.");
  88046. console.log(e);
  88047. }
  88048. if (this._waitingTasksCount === 0) {
  88049. try {
  88050. if (this.onFinish) {
  88051. this.onFinish(this._tasks);
  88052. }
  88053. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88054. }
  88055. catch (e) {
  88056. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88057. console.log(e);
  88058. }
  88059. this._isLoading = false;
  88060. this._scene.getEngine().hideLoadingUI();
  88061. }
  88062. };
  88063. AssetsManager.prototype._runTask = function (task) {
  88064. var _this = this;
  88065. var done = function () {
  88066. try {
  88067. if (_this.onTaskSuccess) {
  88068. _this.onTaskSuccess(task);
  88069. }
  88070. _this.onTaskSuccessObservable.notifyObservers(task);
  88071. _this._decreaseWaitingTasksCount(task);
  88072. }
  88073. catch (e) {
  88074. error("Error executing task success callbacks", e);
  88075. }
  88076. };
  88077. var error = function (message, exception) {
  88078. task._setErrorObject(message, exception);
  88079. if (_this.onTaskError) {
  88080. _this.onTaskError(task);
  88081. }
  88082. _this.onTaskErrorObservable.notifyObservers(task);
  88083. _this._decreaseWaitingTasksCount(task);
  88084. };
  88085. task.run(this._scene, done, error);
  88086. };
  88087. /**
  88088. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88089. * @return the current instance of the {BABYLON.AssetsManager}
  88090. */
  88091. AssetsManager.prototype.reset = function () {
  88092. this._isLoading = false;
  88093. this._tasks = new Array();
  88094. return this;
  88095. };
  88096. /**
  88097. * Start the loading process
  88098. * @return the current instance of the {BABYLON.AssetsManager}
  88099. */
  88100. AssetsManager.prototype.load = function () {
  88101. if (this._isLoading) {
  88102. return this;
  88103. }
  88104. this._isLoading = true;
  88105. this._waitingTasksCount = this._tasks.length;
  88106. this._totalTasksCount = this._tasks.length;
  88107. if (this._waitingTasksCount === 0) {
  88108. this._isLoading = false;
  88109. if (this.onFinish) {
  88110. this.onFinish(this._tasks);
  88111. }
  88112. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88113. return this;
  88114. }
  88115. if (this.useDefaultLoadingScreen) {
  88116. this._scene.getEngine().displayLoadingUI();
  88117. }
  88118. for (var index = 0; index < this._tasks.length; index++) {
  88119. var task = this._tasks[index];
  88120. this._runTask(task);
  88121. }
  88122. return this;
  88123. };
  88124. return AssetsManager;
  88125. }());
  88126. BABYLON.AssetsManager = AssetsManager;
  88127. })(BABYLON || (BABYLON = {}));
  88128. //# sourceMappingURL=babylon.assetsManager.js.map
  88129. "use strict";
  88130. var BABYLON;
  88131. (function (BABYLON) {
  88132. var serializedGeometries = [];
  88133. var serializeGeometry = function (geometry, serializationGeometries) {
  88134. if (serializedGeometries[geometry.id]) {
  88135. return;
  88136. }
  88137. if (geometry.doNotSerialize) {
  88138. return;
  88139. }
  88140. if (geometry instanceof BABYLON.BoxGeometry) {
  88141. serializationGeometries.boxes.push(geometry.serialize());
  88142. }
  88143. else if (geometry instanceof BABYLON.SphereGeometry) {
  88144. serializationGeometries.spheres.push(geometry.serialize());
  88145. }
  88146. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88147. serializationGeometries.cylinders.push(geometry.serialize());
  88148. }
  88149. else if (geometry instanceof BABYLON.TorusGeometry) {
  88150. serializationGeometries.toruses.push(geometry.serialize());
  88151. }
  88152. else if (geometry instanceof BABYLON.GroundGeometry) {
  88153. serializationGeometries.grounds.push(geometry.serialize());
  88154. }
  88155. else if (geometry instanceof BABYLON.Plane) {
  88156. serializationGeometries.planes.push(geometry.serialize());
  88157. }
  88158. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88159. serializationGeometries.torusKnots.push(geometry.serialize());
  88160. }
  88161. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88162. throw new Error("Unknown primitive type");
  88163. }
  88164. else {
  88165. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88166. }
  88167. serializedGeometries[geometry.id] = true;
  88168. };
  88169. var serializeMesh = function (mesh, serializationScene) {
  88170. var serializationObject = {};
  88171. // Geometry
  88172. var geometry = mesh._geometry;
  88173. if (geometry) {
  88174. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88175. // 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
  88176. serializeGeometry(geometry, serializationScene.geometries);
  88177. }
  88178. }
  88179. // Custom
  88180. if (mesh.serialize) {
  88181. mesh.serialize(serializationObject);
  88182. }
  88183. return serializationObject;
  88184. };
  88185. var finalizeSingleMesh = function (mesh, serializationObject) {
  88186. //only works if the mesh is already loaded
  88187. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88188. //serialize material
  88189. if (mesh.material) {
  88190. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88191. serializationObject.materials = serializationObject.materials || [];
  88192. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88193. serializationObject.materials.push(mesh.material.serialize());
  88194. }
  88195. }
  88196. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88197. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88198. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88199. serializationObject.multiMaterials.push(mesh.material.serialize());
  88200. }
  88201. }
  88202. }
  88203. //serialize geometry
  88204. var geometry = mesh._geometry;
  88205. if (geometry) {
  88206. if (!serializationObject.geometries) {
  88207. serializationObject.geometries = {};
  88208. serializationObject.geometries.boxes = [];
  88209. serializationObject.geometries.spheres = [];
  88210. serializationObject.geometries.cylinders = [];
  88211. serializationObject.geometries.toruses = [];
  88212. serializationObject.geometries.grounds = [];
  88213. serializationObject.geometries.planes = [];
  88214. serializationObject.geometries.torusKnots = [];
  88215. serializationObject.geometries.vertexData = [];
  88216. }
  88217. serializeGeometry(geometry, serializationObject.geometries);
  88218. }
  88219. // Skeletons
  88220. if (mesh.skeleton) {
  88221. serializationObject.skeletons = serializationObject.skeletons || [];
  88222. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88223. }
  88224. //serialize the actual mesh
  88225. serializationObject.meshes = serializationObject.meshes || [];
  88226. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88227. }
  88228. };
  88229. var SceneSerializer = /** @class */ (function () {
  88230. function SceneSerializer() {
  88231. }
  88232. SceneSerializer.ClearCache = function () {
  88233. serializedGeometries = [];
  88234. };
  88235. SceneSerializer.Serialize = function (scene) {
  88236. var serializationObject = {};
  88237. SceneSerializer.ClearCache();
  88238. // Scene
  88239. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88240. serializationObject.autoClear = scene.autoClear;
  88241. serializationObject.clearColor = scene.clearColor.asArray();
  88242. serializationObject.ambientColor = scene.ambientColor.asArray();
  88243. serializationObject.gravity = scene.gravity.asArray();
  88244. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88245. serializationObject.workerCollisions = scene.workerCollisions;
  88246. // Fog
  88247. if (scene.fogMode && scene.fogMode !== 0) {
  88248. serializationObject.fogMode = scene.fogMode;
  88249. serializationObject.fogColor = scene.fogColor.asArray();
  88250. serializationObject.fogStart = scene.fogStart;
  88251. serializationObject.fogEnd = scene.fogEnd;
  88252. serializationObject.fogDensity = scene.fogDensity;
  88253. }
  88254. //Physics
  88255. if (scene.isPhysicsEnabled()) {
  88256. var physicEngine = scene.getPhysicsEngine();
  88257. if (physicEngine) {
  88258. serializationObject.physicsEnabled = true;
  88259. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88260. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88261. }
  88262. }
  88263. // Metadata
  88264. if (scene.metadata) {
  88265. serializationObject.metadata = scene.metadata;
  88266. }
  88267. // Morph targets
  88268. serializationObject.morphTargetManagers = [];
  88269. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88270. var abstractMesh = _a[_i];
  88271. var manager = abstractMesh.morphTargetManager;
  88272. if (manager) {
  88273. serializationObject.morphTargetManagers.push(manager.serialize());
  88274. }
  88275. }
  88276. // Lights
  88277. serializationObject.lights = [];
  88278. var index;
  88279. var light;
  88280. for (index = 0; index < scene.lights.length; index++) {
  88281. light = scene.lights[index];
  88282. if (!light.doNotSerialize) {
  88283. serializationObject.lights.push(light.serialize());
  88284. }
  88285. }
  88286. // Cameras
  88287. serializationObject.cameras = [];
  88288. for (index = 0; index < scene.cameras.length; index++) {
  88289. var camera = scene.cameras[index];
  88290. if (!camera.doNotSerialize) {
  88291. serializationObject.cameras.push(camera.serialize());
  88292. }
  88293. }
  88294. if (scene.activeCamera) {
  88295. serializationObject.activeCameraID = scene.activeCamera.id;
  88296. }
  88297. // Animations
  88298. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88299. // Materials
  88300. serializationObject.materials = [];
  88301. serializationObject.multiMaterials = [];
  88302. var material;
  88303. for (index = 0; index < scene.materials.length; index++) {
  88304. material = scene.materials[index];
  88305. if (!material.doNotSerialize) {
  88306. serializationObject.materials.push(material.serialize());
  88307. }
  88308. }
  88309. // MultiMaterials
  88310. serializationObject.multiMaterials = [];
  88311. for (index = 0; index < scene.multiMaterials.length; index++) {
  88312. var multiMaterial = scene.multiMaterials[index];
  88313. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88314. }
  88315. // Environment texture
  88316. if (scene.environmentTexture) {
  88317. serializationObject.environmentTexture = scene.environmentTexture.name;
  88318. }
  88319. // Skeletons
  88320. serializationObject.skeletons = [];
  88321. for (index = 0; index < scene.skeletons.length; index++) {
  88322. var skeleton = scene.skeletons[index];
  88323. if (!skeleton.doNotSerialize) {
  88324. serializationObject.skeletons.push(skeleton.serialize());
  88325. }
  88326. }
  88327. // Transform nodes
  88328. serializationObject.transformNodes = [];
  88329. for (index = 0; index < scene.transformNodes.length; index++) {
  88330. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88331. }
  88332. // Geometries
  88333. serializationObject.geometries = {};
  88334. serializationObject.geometries.boxes = [];
  88335. serializationObject.geometries.spheres = [];
  88336. serializationObject.geometries.cylinders = [];
  88337. serializationObject.geometries.toruses = [];
  88338. serializationObject.geometries.grounds = [];
  88339. serializationObject.geometries.planes = [];
  88340. serializationObject.geometries.torusKnots = [];
  88341. serializationObject.geometries.vertexData = [];
  88342. serializedGeometries = [];
  88343. var geometries = scene.getGeometries();
  88344. for (index = 0; index < geometries.length; index++) {
  88345. var geometry = geometries[index];
  88346. if (geometry.isReady()) {
  88347. serializeGeometry(geometry, serializationObject.geometries);
  88348. }
  88349. }
  88350. // Meshes
  88351. serializationObject.meshes = [];
  88352. for (index = 0; index < scene.meshes.length; index++) {
  88353. var abstractMesh = scene.meshes[index];
  88354. if (abstractMesh instanceof BABYLON.Mesh) {
  88355. var mesh = abstractMesh;
  88356. if (!mesh.doNotSerialize) {
  88357. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88358. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88359. }
  88360. }
  88361. }
  88362. }
  88363. // Particles Systems
  88364. serializationObject.particleSystems = [];
  88365. for (index = 0; index < scene.particleSystems.length; index++) {
  88366. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88367. }
  88368. // Lens flares
  88369. serializationObject.lensFlareSystems = [];
  88370. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88371. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88372. }
  88373. // Shadows
  88374. serializationObject.shadowGenerators = [];
  88375. for (index = 0; index < scene.lights.length; index++) {
  88376. light = scene.lights[index];
  88377. var shadowGenerator = light.getShadowGenerator();
  88378. if (shadowGenerator) {
  88379. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88380. }
  88381. }
  88382. // Action Manager
  88383. if (scene.actionManager) {
  88384. serializationObject.actions = scene.actionManager.serialize("scene");
  88385. }
  88386. // Audio
  88387. serializationObject.sounds = [];
  88388. for (index = 0; index < scene.soundTracks.length; index++) {
  88389. var soundtrack = scene.soundTracks[index];
  88390. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88391. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88392. }
  88393. }
  88394. return serializationObject;
  88395. };
  88396. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88397. if (withParents === void 0) { withParents = false; }
  88398. if (withChildren === void 0) { withChildren = false; }
  88399. var serializationObject = {};
  88400. SceneSerializer.ClearCache();
  88401. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88402. if (withParents || withChildren) {
  88403. //deliberate for loop! not for each, appended should be processed as well.
  88404. for (var i = 0; i < toSerialize.length; ++i) {
  88405. if (withChildren) {
  88406. toSerialize[i].getDescendants().forEach(function (node) {
  88407. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88408. toSerialize.push(node);
  88409. }
  88410. });
  88411. }
  88412. //make sure the array doesn't contain the object already
  88413. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88414. toSerialize.push(toSerialize[i].parent);
  88415. }
  88416. }
  88417. }
  88418. toSerialize.forEach(function (mesh) {
  88419. finalizeSingleMesh(mesh, serializationObject);
  88420. });
  88421. return serializationObject;
  88422. };
  88423. return SceneSerializer;
  88424. }());
  88425. BABYLON.SceneSerializer = SceneSerializer;
  88426. })(BABYLON || (BABYLON = {}));
  88427. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88428. "use strict";
  88429. var BABYLON;
  88430. (function (BABYLON) {
  88431. var ReflectionProbe = /** @class */ (function () {
  88432. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88433. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88434. var _this = this;
  88435. this.name = name;
  88436. this._viewMatrix = BABYLON.Matrix.Identity();
  88437. this._target = BABYLON.Vector3.Zero();
  88438. this._add = BABYLON.Vector3.Zero();
  88439. this._invertYAxis = false;
  88440. this.position = BABYLON.Vector3.Zero();
  88441. this._scene = scene;
  88442. this._scene.reflectionProbes.push(this);
  88443. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88444. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88445. switch (faceIndex) {
  88446. case 0:
  88447. _this._add.copyFromFloats(1, 0, 0);
  88448. break;
  88449. case 1:
  88450. _this._add.copyFromFloats(-1, 0, 0);
  88451. break;
  88452. case 2:
  88453. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88454. break;
  88455. case 3:
  88456. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88457. break;
  88458. case 4:
  88459. _this._add.copyFromFloats(0, 0, 1);
  88460. break;
  88461. case 5:
  88462. _this._add.copyFromFloats(0, 0, -1);
  88463. break;
  88464. }
  88465. if (_this._attachedMesh) {
  88466. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88467. }
  88468. _this.position.addToRef(_this._add, _this._target);
  88469. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88470. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88471. scene._forcedViewPosition = _this.position;
  88472. });
  88473. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88474. scene._forcedViewPosition = null;
  88475. scene.updateTransformMatrix(true);
  88476. });
  88477. if (scene.activeCamera) {
  88478. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88479. }
  88480. }
  88481. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88482. get: function () {
  88483. return this._renderTargetTexture.samples;
  88484. },
  88485. set: function (value) {
  88486. this._renderTargetTexture.samples = value;
  88487. },
  88488. enumerable: true,
  88489. configurable: true
  88490. });
  88491. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88492. get: function () {
  88493. return this._renderTargetTexture.refreshRate;
  88494. },
  88495. set: function (value) {
  88496. this._renderTargetTexture.refreshRate = value;
  88497. },
  88498. enumerable: true,
  88499. configurable: true
  88500. });
  88501. ReflectionProbe.prototype.getScene = function () {
  88502. return this._scene;
  88503. };
  88504. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88505. get: function () {
  88506. return this._renderTargetTexture;
  88507. },
  88508. enumerable: true,
  88509. configurable: true
  88510. });
  88511. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88512. get: function () {
  88513. return this._renderTargetTexture.renderList;
  88514. },
  88515. enumerable: true,
  88516. configurable: true
  88517. });
  88518. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88519. this._attachedMesh = mesh;
  88520. };
  88521. /**
  88522. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88523. *
  88524. * @param renderingGroupId The rendering group id corresponding to its index
  88525. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88526. */
  88527. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88528. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88529. };
  88530. ReflectionProbe.prototype.dispose = function () {
  88531. var index = this._scene.reflectionProbes.indexOf(this);
  88532. if (index !== -1) {
  88533. // Remove from the scene if found
  88534. this._scene.reflectionProbes.splice(index, 1);
  88535. }
  88536. if (this._renderTargetTexture) {
  88537. this._renderTargetTexture.dispose();
  88538. this._renderTargetTexture = null;
  88539. }
  88540. };
  88541. return ReflectionProbe;
  88542. }());
  88543. BABYLON.ReflectionProbe = ReflectionProbe;
  88544. })(BABYLON || (BABYLON = {}));
  88545. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88546. "use strict";
  88547. var BABYLON;
  88548. (function (BABYLON) {
  88549. var Layer = /** @class */ (function () {
  88550. function Layer(name, imgUrl, scene, isBackground, color) {
  88551. this.name = name;
  88552. this.scale = new BABYLON.Vector2(1, 1);
  88553. this.offset = new BABYLON.Vector2(0, 0);
  88554. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88555. this.layerMask = 0x0FFFFFFF;
  88556. this._vertexBuffers = {};
  88557. // Events
  88558. /**
  88559. * An event triggered when the layer is disposed.
  88560. */
  88561. this.onDisposeObservable = new BABYLON.Observable();
  88562. /**
  88563. * An event triggered before rendering the scene
  88564. */
  88565. this.onBeforeRenderObservable = new BABYLON.Observable();
  88566. /**
  88567. * An event triggered after rendering the scene
  88568. */
  88569. this.onAfterRenderObservable = new BABYLON.Observable();
  88570. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88571. this.isBackground = isBackground === undefined ? true : isBackground;
  88572. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88573. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88574. this._scene.layers.push(this);
  88575. var engine = this._scene.getEngine();
  88576. // VBO
  88577. var vertices = [];
  88578. vertices.push(1, 1);
  88579. vertices.push(-1, 1);
  88580. vertices.push(-1, -1);
  88581. vertices.push(1, -1);
  88582. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88583. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88584. this._createIndexBuffer();
  88585. // Effects
  88586. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88587. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88588. }
  88589. Object.defineProperty(Layer.prototype, "onDispose", {
  88590. set: function (callback) {
  88591. if (this._onDisposeObserver) {
  88592. this.onDisposeObservable.remove(this._onDisposeObserver);
  88593. }
  88594. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88595. },
  88596. enumerable: true,
  88597. configurable: true
  88598. });
  88599. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88600. set: function (callback) {
  88601. if (this._onBeforeRenderObserver) {
  88602. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88603. }
  88604. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88605. },
  88606. enumerable: true,
  88607. configurable: true
  88608. });
  88609. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88610. set: function (callback) {
  88611. if (this._onAfterRenderObserver) {
  88612. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88613. }
  88614. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88615. },
  88616. enumerable: true,
  88617. configurable: true
  88618. });
  88619. Layer.prototype._createIndexBuffer = function () {
  88620. var engine = this._scene.getEngine();
  88621. // Indices
  88622. var indices = [];
  88623. indices.push(0);
  88624. indices.push(1);
  88625. indices.push(2);
  88626. indices.push(0);
  88627. indices.push(2);
  88628. indices.push(3);
  88629. this._indexBuffer = engine.createIndexBuffer(indices);
  88630. };
  88631. Layer.prototype._rebuild = function () {
  88632. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88633. if (vb) {
  88634. vb._rebuild();
  88635. }
  88636. this._createIndexBuffer();
  88637. };
  88638. Layer.prototype.render = function () {
  88639. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88640. // Check
  88641. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88642. return;
  88643. var engine = this._scene.getEngine();
  88644. this.onBeforeRenderObservable.notifyObservers(this);
  88645. // Render
  88646. engine.enableEffect(currentEffect);
  88647. engine.setState(false);
  88648. // Texture
  88649. currentEffect.setTexture("textureSampler", this.texture);
  88650. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88651. // Color
  88652. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88653. // Scale / offset
  88654. currentEffect.setVector2("offset", this.offset);
  88655. currentEffect.setVector2("scale", this.scale);
  88656. // VBOs
  88657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88658. // Draw order
  88659. if (!this.alphaTest) {
  88660. engine.setAlphaMode(this.alphaBlendingMode);
  88661. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88662. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88663. }
  88664. else {
  88665. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88666. }
  88667. this.onAfterRenderObservable.notifyObservers(this);
  88668. };
  88669. Layer.prototype.dispose = function () {
  88670. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88671. if (vertexBuffer) {
  88672. vertexBuffer.dispose();
  88673. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88674. }
  88675. if (this._indexBuffer) {
  88676. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88677. this._indexBuffer = null;
  88678. }
  88679. if (this.texture) {
  88680. this.texture.dispose();
  88681. this.texture = null;
  88682. }
  88683. // Remove from scene
  88684. var index = this._scene.layers.indexOf(this);
  88685. this._scene.layers.splice(index, 1);
  88686. // Callback
  88687. this.onDisposeObservable.notifyObservers(this);
  88688. this.onDisposeObservable.clear();
  88689. this.onAfterRenderObservable.clear();
  88690. this.onBeforeRenderObservable.clear();
  88691. };
  88692. return Layer;
  88693. }());
  88694. BABYLON.Layer = Layer;
  88695. })(BABYLON || (BABYLON = {}));
  88696. //# sourceMappingURL=babylon.layer.js.map
  88697. "use strict";
  88698. var BABYLON;
  88699. (function (BABYLON) {
  88700. var TextureTools = /** @class */ (function () {
  88701. function TextureTools() {
  88702. }
  88703. /**
  88704. * Uses the GPU to create a copy texture rescaled at a given size
  88705. * @param texture Texture to copy from
  88706. * @param width Desired width
  88707. * @param height Desired height
  88708. * @return Generated texture
  88709. */
  88710. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88711. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88712. var scene = texture.getScene();
  88713. var engine = scene.getEngine();
  88714. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88715. rtt.wrapU = texture.wrapU;
  88716. rtt.wrapV = texture.wrapV;
  88717. rtt.uOffset = texture.uOffset;
  88718. rtt.vOffset = texture.vOffset;
  88719. rtt.uScale = texture.uScale;
  88720. rtt.vScale = texture.vScale;
  88721. rtt.uAng = texture.uAng;
  88722. rtt.vAng = texture.vAng;
  88723. rtt.wAng = texture.wAng;
  88724. rtt.coordinatesIndex = texture.coordinatesIndex;
  88725. rtt.level = texture.level;
  88726. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88727. rtt._texture.isReady = false;
  88728. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88729. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88730. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88731. passPostProcess.getEffect().executeWhenCompiled(function () {
  88732. passPostProcess.onApply = function (effect) {
  88733. effect.setTexture("textureSampler", texture);
  88734. };
  88735. var internalTexture = rtt.getInternalTexture();
  88736. if (internalTexture) {
  88737. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88738. engine.unBindFramebuffer(internalTexture);
  88739. rtt.disposeFramebufferObjects();
  88740. passPostProcess.dispose();
  88741. internalTexture.isReady = true;
  88742. }
  88743. });
  88744. return rtt;
  88745. };
  88746. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88747. if (!scene._environmentBRDFTexture) {
  88748. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88749. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88750. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88751. scene._environmentBRDFTexture = texture;
  88752. }
  88753. return scene._environmentBRDFTexture;
  88754. };
  88755. 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=";
  88756. return TextureTools;
  88757. }());
  88758. BABYLON.TextureTools = TextureTools;
  88759. })(BABYLON || (BABYLON = {}));
  88760. //# sourceMappingURL=babylon.textureTools.js.map
  88761. "use strict";
  88762. var BABYLON;
  88763. (function (BABYLON) {
  88764. var FramingBehavior = /** @class */ (function () {
  88765. function FramingBehavior() {
  88766. this._mode = FramingBehavior.FitFrustumSidesMode;
  88767. this._radiusScale = 1.0;
  88768. this._positionScale = 0.5;
  88769. this._defaultElevation = 0.3;
  88770. this._elevationReturnTime = 1500;
  88771. this._elevationReturnWaitTime = 1000;
  88772. this._zoomStopsAnimation = false;
  88773. this._framingTime = 1500;
  88774. this._isPointerDown = false;
  88775. this._lastInteractionTime = -Infinity;
  88776. // Framing control
  88777. this._animatables = new Array();
  88778. this._betaIsAnimating = false;
  88779. }
  88780. Object.defineProperty(FramingBehavior.prototype, "name", {
  88781. get: function () {
  88782. return "Framing";
  88783. },
  88784. enumerable: true,
  88785. configurable: true
  88786. });
  88787. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88788. /**
  88789. * Gets current mode used by the behavior.
  88790. */
  88791. get: function () {
  88792. return this._mode;
  88793. },
  88794. /**
  88795. * Sets the current mode used by the behavior
  88796. */
  88797. set: function (mode) {
  88798. this._mode = mode;
  88799. },
  88800. enumerable: true,
  88801. configurable: true
  88802. });
  88803. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88804. /**
  88805. * Gets the scale applied to the radius
  88806. */
  88807. get: function () {
  88808. return this._radiusScale;
  88809. },
  88810. /**
  88811. * Sets the scale applied to the radius (1 by default)
  88812. */
  88813. set: function (radius) {
  88814. this._radiusScale = radius;
  88815. },
  88816. enumerable: true,
  88817. configurable: true
  88818. });
  88819. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88820. /**
  88821. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88822. */
  88823. get: function () {
  88824. return this._positionScale;
  88825. },
  88826. /**
  88827. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88828. */
  88829. set: function (scale) {
  88830. this._positionScale = scale;
  88831. },
  88832. enumerable: true,
  88833. configurable: true
  88834. });
  88835. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88836. /**
  88837. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88838. * behaviour is triggered, in radians.
  88839. */
  88840. get: function () {
  88841. return this._defaultElevation;
  88842. },
  88843. /**
  88844. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88845. * behaviour is triggered, in radians.
  88846. */
  88847. set: function (elevation) {
  88848. this._defaultElevation = elevation;
  88849. },
  88850. enumerable: true,
  88851. configurable: true
  88852. });
  88853. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88854. /**
  88855. * Gets the time (in milliseconds) taken to return to the default beta position.
  88856. * Negative value indicates camera should not return to default.
  88857. */
  88858. get: function () {
  88859. return this._elevationReturnTime;
  88860. },
  88861. /**
  88862. * Sets the time (in milliseconds) taken to return to the default beta position.
  88863. * Negative value indicates camera should not return to default.
  88864. */
  88865. set: function (speed) {
  88866. this._elevationReturnTime = speed;
  88867. },
  88868. enumerable: true,
  88869. configurable: true
  88870. });
  88871. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88872. /**
  88873. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88874. */
  88875. get: function () {
  88876. return this._elevationReturnWaitTime;
  88877. },
  88878. /**
  88879. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88880. */
  88881. set: function (time) {
  88882. this._elevationReturnWaitTime = time;
  88883. },
  88884. enumerable: true,
  88885. configurable: true
  88886. });
  88887. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88888. /**
  88889. * Gets the flag that indicates if user zooming should stop animation.
  88890. */
  88891. get: function () {
  88892. return this._zoomStopsAnimation;
  88893. },
  88894. /**
  88895. * Sets the flag that indicates if user zooming should stop animation.
  88896. */
  88897. set: function (flag) {
  88898. this._zoomStopsAnimation = flag;
  88899. },
  88900. enumerable: true,
  88901. configurable: true
  88902. });
  88903. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88904. /**
  88905. * Gets the transition time when framing the mesh, in milliseconds
  88906. */
  88907. get: function () {
  88908. return this._framingTime;
  88909. },
  88910. /**
  88911. * Sets the transition time when framing the mesh, in milliseconds
  88912. */
  88913. set: function (time) {
  88914. this._framingTime = time;
  88915. },
  88916. enumerable: true,
  88917. configurable: true
  88918. });
  88919. FramingBehavior.prototype.init = function () {
  88920. // Do notihng
  88921. };
  88922. FramingBehavior.prototype.attach = function (camera) {
  88923. var _this = this;
  88924. this._attachedCamera = camera;
  88925. var scene = this._attachedCamera.getScene();
  88926. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88927. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88928. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88929. _this._isPointerDown = true;
  88930. return;
  88931. }
  88932. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88933. _this._isPointerDown = false;
  88934. }
  88935. });
  88936. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88937. if (mesh) {
  88938. _this.zoomOnMesh(mesh);
  88939. }
  88940. });
  88941. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88942. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88943. _this._applyUserInteraction();
  88944. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88945. // back to the default position after a given timeout
  88946. _this._maintainCameraAboveGround();
  88947. });
  88948. };
  88949. FramingBehavior.prototype.detach = function () {
  88950. if (!this._attachedCamera) {
  88951. return;
  88952. }
  88953. var scene = this._attachedCamera.getScene();
  88954. if (this._onPrePointerObservableObserver) {
  88955. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88956. }
  88957. if (this._onAfterCheckInputsObserver) {
  88958. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88959. }
  88960. if (this._onMeshTargetChangedObserver) {
  88961. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88962. }
  88963. this._attachedCamera = null;
  88964. };
  88965. /**
  88966. * Targets the given mesh and updates zoom level accordingly.
  88967. * @param mesh The mesh to target.
  88968. * @param radius Optional. If a cached radius position already exists, overrides default.
  88969. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88970. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88971. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88972. */
  88973. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88974. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88975. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88976. mesh.computeWorldMatrix(true);
  88977. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88978. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88979. };
  88980. /**
  88981. * Targets the given mesh with its children and updates zoom level accordingly.
  88982. * @param mesh The mesh to target.
  88983. * @param radius Optional. If a cached radius position already exists, overrides default.
  88984. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88985. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88986. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88987. */
  88988. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88989. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88990. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88991. mesh.computeWorldMatrix(true);
  88992. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88993. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88994. };
  88995. /**
  88996. * Targets the given meshes with their children and updates zoom level accordingly.
  88997. * @param meshes The mesh to target.
  88998. * @param radius Optional. If a cached radius position already exists, overrides default.
  88999. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89000. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89001. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89002. */
  89003. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89004. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89005. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89006. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89007. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89008. for (var i = 0; i < meshes.length; i++) {
  89009. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89010. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89011. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89012. }
  89013. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89014. };
  89015. /**
  89016. * Targets the given mesh and updates zoom level accordingly.
  89017. * @param mesh The mesh to target.
  89018. * @param radius Optional. If a cached radius position already exists, overrides default.
  89019. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89020. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89021. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89022. */
  89023. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89024. var _this = this;
  89025. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89026. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89027. var zoomTarget;
  89028. if (!this._attachedCamera) {
  89029. return;
  89030. }
  89031. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89032. var bottom = minimumWorld.y;
  89033. var top = maximumWorld.y;
  89034. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89035. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89036. if (focusOnOriginXZ) {
  89037. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89038. }
  89039. else {
  89040. var centerWorld = minimumWorld.add(radiusWorld);
  89041. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89042. }
  89043. if (!this._vectorTransition) {
  89044. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89045. }
  89046. this._betaIsAnimating = true;
  89047. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89048. if (animatable) {
  89049. this._animatables.push(animatable);
  89050. }
  89051. // sets the radius and lower radius bounds
  89052. // Small delta ensures camera is not always at lower zoom limit.
  89053. var radius = 0;
  89054. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89055. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89056. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89057. radius = position;
  89058. }
  89059. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89060. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89061. if (this._attachedCamera.lowerRadiusLimit === null) {
  89062. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89063. }
  89064. }
  89065. // Set sensibilities
  89066. var extend = maximumWorld.subtract(minimumWorld).length();
  89067. this._attachedCamera.panningSensibility = 5000 / extend;
  89068. this._attachedCamera.wheelPrecision = 100 / radius;
  89069. // transition to new radius
  89070. if (!this._radiusTransition) {
  89071. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89072. }
  89073. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89074. _this.stopAllAnimations();
  89075. if (onAnimationEnd) {
  89076. onAnimationEnd();
  89077. }
  89078. if (_this._attachedCamera) {
  89079. _this._attachedCamera.storeState();
  89080. }
  89081. });
  89082. if (animatable) {
  89083. this._animatables.push(animatable);
  89084. }
  89085. };
  89086. /**
  89087. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89088. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89089. * frustum width.
  89090. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89091. * to fully enclose the mesh in the viewing frustum.
  89092. */
  89093. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89094. var size = maximumWorld.subtract(minimumWorld);
  89095. var boxVectorGlobalDiagonal = size.length();
  89096. var frustumSlope = this._getFrustumSlope();
  89097. // Formula for setting distance
  89098. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89099. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89100. // Horizon distance
  89101. var radius = radiusWithoutFraming * this._radiusScale;
  89102. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89103. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89104. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89105. var camera = this._attachedCamera;
  89106. if (!camera) {
  89107. return 0;
  89108. }
  89109. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89110. // Don't exceed the requested limit
  89111. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89112. }
  89113. // Don't exceed the upper radius limit
  89114. if (camera.upperRadiusLimit) {
  89115. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89116. }
  89117. return distance;
  89118. };
  89119. /**
  89120. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89121. * is automatically returned to its default position (expected to be above ground plane).
  89122. */
  89123. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89124. var _this = this;
  89125. if (this._elevationReturnTime < 0) {
  89126. return;
  89127. }
  89128. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89129. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89130. var limitBeta = Math.PI * 0.5;
  89131. // Bring the camera back up if below the ground plane
  89132. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89133. this._betaIsAnimating = true;
  89134. //Transition to new position
  89135. this.stopAllAnimations();
  89136. if (!this._betaTransition) {
  89137. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89138. }
  89139. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89140. _this._clearAnimationLocks();
  89141. _this.stopAllAnimations();
  89142. });
  89143. if (animatabe) {
  89144. this._animatables.push(animatabe);
  89145. }
  89146. }
  89147. };
  89148. /**
  89149. * Returns the frustum slope based on the canvas ratio and camera FOV
  89150. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89151. */
  89152. FramingBehavior.prototype._getFrustumSlope = function () {
  89153. // Calculate the viewport ratio
  89154. // Aspect Ratio is Height/Width.
  89155. var camera = this._attachedCamera;
  89156. if (!camera) {
  89157. return BABYLON.Vector2.Zero();
  89158. }
  89159. var engine = camera.getScene().getEngine();
  89160. var aspectRatio = engine.getAspectRatio(camera);
  89161. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89162. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89163. var frustumSlopeY = Math.tan(camera.fov / 2);
  89164. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89165. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89166. // along the forward vector.
  89167. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89168. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89169. };
  89170. /**
  89171. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89172. */
  89173. FramingBehavior.prototype._clearAnimationLocks = function () {
  89174. this._betaIsAnimating = false;
  89175. };
  89176. /**
  89177. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89178. */
  89179. FramingBehavior.prototype._applyUserInteraction = function () {
  89180. if (this.isUserIsMoving) {
  89181. this._lastInteractionTime = BABYLON.Tools.Now;
  89182. this.stopAllAnimations();
  89183. this._clearAnimationLocks();
  89184. }
  89185. };
  89186. /**
  89187. * Stops and removes all animations that have been applied to the camera
  89188. */
  89189. FramingBehavior.prototype.stopAllAnimations = function () {
  89190. if (this._attachedCamera) {
  89191. this._attachedCamera.animations = [];
  89192. }
  89193. while (this._animatables.length) {
  89194. if (this._animatables[0]) {
  89195. this._animatables[0].onAnimationEnd = null;
  89196. this._animatables[0].stop();
  89197. }
  89198. this._animatables.shift();
  89199. }
  89200. };
  89201. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89202. /**
  89203. * Gets a value indicating if the user is moving the camera
  89204. */
  89205. get: function () {
  89206. if (!this._attachedCamera) {
  89207. return false;
  89208. }
  89209. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89210. this._attachedCamera.inertialBetaOffset !== 0 ||
  89211. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89212. this._attachedCamera.inertialPanningX !== 0 ||
  89213. this._attachedCamera.inertialPanningY !== 0 ||
  89214. this._isPointerDown;
  89215. },
  89216. enumerable: true,
  89217. configurable: true
  89218. });
  89219. /**
  89220. * The easing function used by animations
  89221. */
  89222. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89223. /**
  89224. * The easing mode used by animations
  89225. */
  89226. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89227. // Statics
  89228. /**
  89229. * The camera can move all the way towards the mesh.
  89230. */
  89231. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89232. /**
  89233. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89234. */
  89235. FramingBehavior.FitFrustumSidesMode = 1;
  89236. return FramingBehavior;
  89237. }());
  89238. BABYLON.FramingBehavior = FramingBehavior;
  89239. })(BABYLON || (BABYLON = {}));
  89240. //# sourceMappingURL=babylon.framingBehavior.js.map
  89241. "use strict";
  89242. var BABYLON;
  89243. (function (BABYLON) {
  89244. /**
  89245. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89246. */
  89247. var BouncingBehavior = /** @class */ (function () {
  89248. function BouncingBehavior() {
  89249. /**
  89250. * The duration of the animation, in milliseconds
  89251. */
  89252. this.transitionDuration = 450;
  89253. /**
  89254. * Length of the distance animated by the transition when lower radius is reached
  89255. */
  89256. this.lowerRadiusTransitionRange = 2;
  89257. /**
  89258. * Length of the distance animated by the transition when upper radius is reached
  89259. */
  89260. this.upperRadiusTransitionRange = -2;
  89261. this._autoTransitionRange = false;
  89262. // Animations
  89263. this._radiusIsAnimating = false;
  89264. this._radiusBounceTransition = null;
  89265. this._animatables = new Array();
  89266. }
  89267. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89268. get: function () {
  89269. return "Bouncing";
  89270. },
  89271. enumerable: true,
  89272. configurable: true
  89273. });
  89274. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89275. /**
  89276. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89277. */
  89278. get: function () {
  89279. return this._autoTransitionRange;
  89280. },
  89281. /**
  89282. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89283. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89284. */
  89285. set: function (value) {
  89286. var _this = this;
  89287. if (this._autoTransitionRange === value) {
  89288. return;
  89289. }
  89290. this._autoTransitionRange = value;
  89291. var camera = this._attachedCamera;
  89292. if (!camera) {
  89293. return;
  89294. }
  89295. if (value) {
  89296. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89297. if (!mesh) {
  89298. return;
  89299. }
  89300. mesh.computeWorldMatrix(true);
  89301. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89302. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89303. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89304. });
  89305. }
  89306. else if (this._onMeshTargetChangedObserver) {
  89307. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89308. }
  89309. },
  89310. enumerable: true,
  89311. configurable: true
  89312. });
  89313. BouncingBehavior.prototype.init = function () {
  89314. // Do notihng
  89315. };
  89316. BouncingBehavior.prototype.attach = function (camera) {
  89317. var _this = this;
  89318. this._attachedCamera = camera;
  89319. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89320. if (!_this._attachedCamera) {
  89321. return;
  89322. }
  89323. // Add the bounce animation to the lower radius limit
  89324. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89325. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89326. }
  89327. // Add the bounce animation to the upper radius limit
  89328. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89329. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89330. }
  89331. });
  89332. };
  89333. BouncingBehavior.prototype.detach = function () {
  89334. if (!this._attachedCamera) {
  89335. return;
  89336. }
  89337. if (this._onAfterCheckInputsObserver) {
  89338. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89339. }
  89340. if (this._onMeshTargetChangedObserver) {
  89341. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89342. }
  89343. this._attachedCamera = null;
  89344. };
  89345. /**
  89346. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89347. * @param radiusLimit The limit to check against.
  89348. * @return Bool to indicate if at limit.
  89349. */
  89350. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89351. if (!this._attachedCamera) {
  89352. return false;
  89353. }
  89354. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89355. return true;
  89356. }
  89357. return false;
  89358. };
  89359. /**
  89360. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89361. * @param radiusDelta The delta by which to animate to. Can be negative.
  89362. */
  89363. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89364. var _this = this;
  89365. if (!this._attachedCamera) {
  89366. return;
  89367. }
  89368. if (!this._radiusBounceTransition) {
  89369. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89370. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89371. }
  89372. // Prevent zoom until bounce has completed
  89373. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89374. this._attachedCamera.wheelPrecision = Infinity;
  89375. this._attachedCamera.inertialRadiusOffset = 0;
  89376. // Animate to the radius limit
  89377. this.stopAllAnimations();
  89378. this._radiusIsAnimating = true;
  89379. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89380. if (animatable) {
  89381. this._animatables.push(animatable);
  89382. }
  89383. };
  89384. /**
  89385. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89386. */
  89387. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89388. this._radiusIsAnimating = false;
  89389. if (this._attachedCamera) {
  89390. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89391. }
  89392. };
  89393. /**
  89394. * Stops and removes all animations that have been applied to the camera
  89395. */
  89396. BouncingBehavior.prototype.stopAllAnimations = function () {
  89397. if (this._attachedCamera) {
  89398. this._attachedCamera.animations = [];
  89399. }
  89400. while (this._animatables.length) {
  89401. this._animatables[0].onAnimationEnd = null;
  89402. this._animatables[0].stop();
  89403. this._animatables.shift();
  89404. }
  89405. };
  89406. /**
  89407. * The easing function used by animations
  89408. */
  89409. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89410. /**
  89411. * The easing mode used by animations
  89412. */
  89413. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89414. return BouncingBehavior;
  89415. }());
  89416. BABYLON.BouncingBehavior = BouncingBehavior;
  89417. })(BABYLON || (BABYLON = {}));
  89418. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89419. "use strict";
  89420. var BABYLON;
  89421. (function (BABYLON) {
  89422. var AutoRotationBehavior = /** @class */ (function () {
  89423. function AutoRotationBehavior() {
  89424. this._zoomStopsAnimation = false;
  89425. this._idleRotationSpeed = 0.05;
  89426. this._idleRotationWaitTime = 2000;
  89427. this._idleRotationSpinupTime = 2000;
  89428. this._isPointerDown = false;
  89429. this._lastFrameTime = null;
  89430. this._lastInteractionTime = -Infinity;
  89431. this._cameraRotationSpeed = 0;
  89432. this._lastFrameRadius = 0;
  89433. }
  89434. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89435. get: function () {
  89436. return "AutoRotation";
  89437. },
  89438. enumerable: true,
  89439. configurable: true
  89440. });
  89441. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89442. /**
  89443. * Gets the flag that indicates if user zooming should stop animation.
  89444. */
  89445. get: function () {
  89446. return this._zoomStopsAnimation;
  89447. },
  89448. /**
  89449. * Sets the flag that indicates if user zooming should stop animation.
  89450. */
  89451. set: function (flag) {
  89452. this._zoomStopsAnimation = flag;
  89453. },
  89454. enumerable: true,
  89455. configurable: true
  89456. });
  89457. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89458. /**
  89459. * Gets the default speed at which the camera rotates around the model.
  89460. */
  89461. get: function () {
  89462. return this._idleRotationSpeed;
  89463. },
  89464. /**
  89465. * Sets the default speed at which the camera rotates around the model.
  89466. */
  89467. set: function (speed) {
  89468. this._idleRotationSpeed = speed;
  89469. },
  89470. enumerable: true,
  89471. configurable: true
  89472. });
  89473. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89474. /**
  89475. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89476. */
  89477. get: function () {
  89478. return this._idleRotationWaitTime;
  89479. },
  89480. /**
  89481. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89482. */
  89483. set: function (time) {
  89484. this._idleRotationWaitTime = time;
  89485. },
  89486. enumerable: true,
  89487. configurable: true
  89488. });
  89489. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89490. /**
  89491. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89492. */
  89493. get: function () {
  89494. return this._idleRotationSpinupTime;
  89495. },
  89496. /**
  89497. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89498. */
  89499. set: function (time) {
  89500. this._idleRotationSpinupTime = time;
  89501. },
  89502. enumerable: true,
  89503. configurable: true
  89504. });
  89505. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89506. /**
  89507. * Gets a value indicating if the camera is currently rotating because of this behavior
  89508. */
  89509. get: function () {
  89510. return Math.abs(this._cameraRotationSpeed) > 0;
  89511. },
  89512. enumerable: true,
  89513. configurable: true
  89514. });
  89515. AutoRotationBehavior.prototype.init = function () {
  89516. // Do notihng
  89517. };
  89518. AutoRotationBehavior.prototype.attach = function (camera) {
  89519. var _this = this;
  89520. this._attachedCamera = camera;
  89521. var scene = this._attachedCamera.getScene();
  89522. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89523. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89524. _this._isPointerDown = true;
  89525. return;
  89526. }
  89527. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89528. _this._isPointerDown = false;
  89529. }
  89530. });
  89531. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89532. var now = BABYLON.Tools.Now;
  89533. var dt = 0;
  89534. if (_this._lastFrameTime != null) {
  89535. dt = now - _this._lastFrameTime;
  89536. }
  89537. _this._lastFrameTime = now;
  89538. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89539. _this._applyUserInteraction();
  89540. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89541. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89542. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89543. // Step camera rotation by rotation speed
  89544. if (_this._attachedCamera) {
  89545. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89546. }
  89547. });
  89548. };
  89549. AutoRotationBehavior.prototype.detach = function () {
  89550. if (!this._attachedCamera) {
  89551. return;
  89552. }
  89553. var scene = this._attachedCamera.getScene();
  89554. if (this._onPrePointerObservableObserver) {
  89555. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89556. }
  89557. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89558. this._attachedCamera = null;
  89559. };
  89560. /**
  89561. * Returns true if user is scrolling.
  89562. * @return true if user is scrolling.
  89563. */
  89564. AutoRotationBehavior.prototype._userIsZooming = function () {
  89565. if (!this._attachedCamera) {
  89566. return false;
  89567. }
  89568. return this._attachedCamera.inertialRadiusOffset !== 0;
  89569. };
  89570. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89571. if (!this._attachedCamera) {
  89572. return false;
  89573. }
  89574. var zoomHasHitLimit = false;
  89575. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89576. zoomHasHitLimit = true;
  89577. }
  89578. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89579. this._lastFrameRadius = this._attachedCamera.radius;
  89580. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89581. };
  89582. /**
  89583. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89584. */
  89585. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89586. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89587. this._lastInteractionTime = BABYLON.Tools.Now;
  89588. }
  89589. };
  89590. // Tools
  89591. AutoRotationBehavior.prototype._userIsMoving = function () {
  89592. if (!this._attachedCamera) {
  89593. return false;
  89594. }
  89595. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89596. this._attachedCamera.inertialBetaOffset !== 0 ||
  89597. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89598. this._attachedCamera.inertialPanningX !== 0 ||
  89599. this._attachedCamera.inertialPanningY !== 0 ||
  89600. this._isPointerDown;
  89601. };
  89602. return AutoRotationBehavior;
  89603. }());
  89604. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89605. })(BABYLON || (BABYLON = {}));
  89606. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89607. "use strict";
  89608. var BABYLON;
  89609. (function (BABYLON) {
  89610. var NullEngineOptions = /** @class */ (function () {
  89611. function NullEngineOptions() {
  89612. this.renderWidth = 512;
  89613. this.renderHeight = 256;
  89614. this.textureSize = 512;
  89615. this.deterministicLockstep = false;
  89616. this.lockstepMaxSteps = 4;
  89617. }
  89618. return NullEngineOptions;
  89619. }());
  89620. BABYLON.NullEngineOptions = NullEngineOptions;
  89621. /**
  89622. * The null engine class provides support for headless version of babylon.js.
  89623. * This can be used in server side scenario or for testing purposes
  89624. */
  89625. var NullEngine = /** @class */ (function (_super) {
  89626. __extends(NullEngine, _super);
  89627. function NullEngine(options) {
  89628. if (options === void 0) { options = new NullEngineOptions(); }
  89629. var _this = _super.call(this, null) || this;
  89630. if (options.deterministicLockstep === undefined) {
  89631. options.deterministicLockstep = false;
  89632. }
  89633. if (options.lockstepMaxSteps === undefined) {
  89634. options.lockstepMaxSteps = 4;
  89635. }
  89636. _this._options = options;
  89637. // Init caps
  89638. // We consider we are on a webgl1 capable device
  89639. _this._caps = new BABYLON.EngineCapabilities();
  89640. _this._caps.maxTexturesImageUnits = 16;
  89641. _this._caps.maxVertexTextureImageUnits = 16;
  89642. _this._caps.maxTextureSize = 512;
  89643. _this._caps.maxCubemapTextureSize = 512;
  89644. _this._caps.maxRenderTextureSize = 512;
  89645. _this._caps.maxVertexAttribs = 16;
  89646. _this._caps.maxVaryingVectors = 16;
  89647. _this._caps.maxFragmentUniformVectors = 16;
  89648. _this._caps.maxVertexUniformVectors = 16;
  89649. // Extensions
  89650. _this._caps.standardDerivatives = false;
  89651. _this._caps.astc = null;
  89652. _this._caps.s3tc = null;
  89653. _this._caps.pvrtc = null;
  89654. _this._caps.etc1 = null;
  89655. _this._caps.etc2 = null;
  89656. _this._caps.textureAnisotropicFilterExtension = null;
  89657. _this._caps.maxAnisotropy = 0;
  89658. _this._caps.uintIndices = false;
  89659. _this._caps.fragmentDepthSupported = false;
  89660. _this._caps.highPrecisionShaderSupported = true;
  89661. _this._caps.colorBufferFloat = false;
  89662. _this._caps.textureFloat = false;
  89663. _this._caps.textureFloatLinearFiltering = false;
  89664. _this._caps.textureFloatRender = false;
  89665. _this._caps.textureHalfFloat = false;
  89666. _this._caps.textureHalfFloatLinearFiltering = false;
  89667. _this._caps.textureHalfFloatRender = false;
  89668. _this._caps.textureLOD = false;
  89669. _this._caps.drawBuffersExtension = false;
  89670. _this._caps.depthTextureExtension = false;
  89671. _this._caps.vertexArrayObject = false;
  89672. _this._caps.instancedArrays = false;
  89673. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89674. // Wrappers
  89675. if (typeof URL === "undefined") {
  89676. URL = {
  89677. createObjectURL: function () { },
  89678. revokeObjectURL: function () { }
  89679. };
  89680. }
  89681. if (typeof Blob === "undefined") {
  89682. Blob = function () { };
  89683. }
  89684. return _this;
  89685. }
  89686. NullEngine.prototype.isDeterministicLockStep = function () {
  89687. return this._options.deterministicLockstep;
  89688. };
  89689. NullEngine.prototype.getLockstepMaxSteps = function () {
  89690. return this._options.lockstepMaxSteps;
  89691. };
  89692. NullEngine.prototype.getHardwareScalingLevel = function () {
  89693. return 1.0;
  89694. };
  89695. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89696. return {
  89697. capacity: 0,
  89698. references: 1,
  89699. is32Bits: false
  89700. };
  89701. };
  89702. NullEngine.prototype.createIndexBuffer = function (indices) {
  89703. return {
  89704. capacity: 0,
  89705. references: 1,
  89706. is32Bits: false
  89707. };
  89708. };
  89709. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89710. if (stencil === void 0) { stencil = false; }
  89711. };
  89712. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89713. if (useScreen === void 0) { useScreen = false; }
  89714. if (!useScreen && this._currentRenderTarget) {
  89715. return this._currentRenderTarget.width;
  89716. }
  89717. return this._options.renderWidth;
  89718. };
  89719. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89720. if (useScreen === void 0) { useScreen = false; }
  89721. if (!useScreen && this._currentRenderTarget) {
  89722. return this._currentRenderTarget.height;
  89723. }
  89724. return this._options.renderHeight;
  89725. };
  89726. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89727. this._cachedViewport = viewport;
  89728. };
  89729. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89730. return {
  89731. transformFeedback: null,
  89732. __SPECTOR_rebuildProgram: null
  89733. };
  89734. };
  89735. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89736. return [];
  89737. };
  89738. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89739. return [];
  89740. };
  89741. NullEngine.prototype.bindSamplers = function (effect) {
  89742. this._currentEffect = null;
  89743. };
  89744. NullEngine.prototype.enableEffect = function (effect) {
  89745. this._currentEffect = effect;
  89746. if (effect.onBind) {
  89747. effect.onBind(effect);
  89748. }
  89749. effect.onBindObservable.notifyObservers(effect);
  89750. };
  89751. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89752. if (zOffset === void 0) { zOffset = 0; }
  89753. if (reverseSide === void 0) { reverseSide = false; }
  89754. };
  89755. NullEngine.prototype.setIntArray = function (uniform, array) {
  89756. };
  89757. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89758. };
  89759. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89760. };
  89761. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89762. };
  89763. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89764. };
  89765. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89766. };
  89767. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89768. };
  89769. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89770. };
  89771. NullEngine.prototype.setArray = function (uniform, array) {
  89772. };
  89773. NullEngine.prototype.setArray2 = function (uniform, array) {
  89774. };
  89775. NullEngine.prototype.setArray3 = function (uniform, array) {
  89776. };
  89777. NullEngine.prototype.setArray4 = function (uniform, array) {
  89778. };
  89779. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89780. };
  89781. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89782. };
  89783. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89784. };
  89785. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89786. };
  89787. NullEngine.prototype.setFloat = function (uniform, value) {
  89788. };
  89789. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89790. };
  89791. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89792. };
  89793. NullEngine.prototype.setBool = function (uniform, bool) {
  89794. };
  89795. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89796. };
  89797. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89798. };
  89799. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89800. };
  89801. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89802. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89803. if (this._alphaMode === mode) {
  89804. return;
  89805. }
  89806. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89807. if (!noDepthWriteChange) {
  89808. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89809. }
  89810. this._alphaMode = mode;
  89811. };
  89812. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89813. };
  89814. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89815. if (this.preventCacheWipeBetweenFrames) {
  89816. return;
  89817. }
  89818. this.resetTextureCache();
  89819. this._currentEffect = null;
  89820. if (bruteForce) {
  89821. this._currentProgram = null;
  89822. this._stencilState.reset();
  89823. this._depthCullingState.reset();
  89824. this._alphaState.reset();
  89825. }
  89826. this._cachedVertexBuffers = null;
  89827. this._cachedIndexBuffer = null;
  89828. this._cachedEffectForVertexBuffers = null;
  89829. };
  89830. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89831. };
  89832. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89833. };
  89834. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89835. };
  89836. NullEngine.prototype._createTexture = function () {
  89837. return {};
  89838. };
  89839. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89841. if (onLoad === void 0) { onLoad = null; }
  89842. if (onError === void 0) { onError = null; }
  89843. if (buffer === void 0) { buffer = null; }
  89844. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89845. var url = String(urlArg);
  89846. texture.url = url;
  89847. texture.generateMipMaps = !noMipmap;
  89848. texture.samplingMode = samplingMode;
  89849. texture.invertY = invertY;
  89850. texture.baseWidth = this._options.textureSize;
  89851. texture.baseHeight = this._options.textureSize;
  89852. texture.width = this._options.textureSize;
  89853. texture.height = this._options.textureSize;
  89854. if (format) {
  89855. texture.format = format;
  89856. }
  89857. texture.isReady = true;
  89858. if (onLoad) {
  89859. onLoad();
  89860. }
  89861. return texture;
  89862. };
  89863. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89864. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89865. if (options !== undefined && typeof options === "object") {
  89866. fullOptions.generateMipMaps = options.generateMipMaps;
  89867. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89868. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89869. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89870. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89871. }
  89872. else {
  89873. fullOptions.generateMipMaps = options;
  89874. fullOptions.generateDepthBuffer = true;
  89875. fullOptions.generateStencilBuffer = false;
  89876. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89877. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89878. }
  89879. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89880. var width = size.width || size;
  89881. var height = size.height || size;
  89882. texture._depthStencilBuffer = {};
  89883. texture._framebuffer = {};
  89884. texture.baseWidth = width;
  89885. texture.baseHeight = height;
  89886. texture.width = width;
  89887. texture.height = height;
  89888. texture.isReady = true;
  89889. texture.samples = 1;
  89890. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89891. texture.samplingMode = fullOptions.samplingMode;
  89892. texture.type = fullOptions.type;
  89893. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89894. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89895. return texture;
  89896. };
  89897. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89898. texture.samplingMode = samplingMode;
  89899. };
  89900. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89901. if (this._currentRenderTarget) {
  89902. this.unBindFramebuffer(this._currentRenderTarget);
  89903. }
  89904. this._currentRenderTarget = texture;
  89905. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89906. if (this._cachedViewport && !forceFullscreenViewport) {
  89907. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89908. }
  89909. };
  89910. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89911. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89912. this._currentRenderTarget = null;
  89913. if (onBeforeUnbind) {
  89914. if (texture._MSAAFramebuffer) {
  89915. this._currentFramebuffer = texture._framebuffer;
  89916. }
  89917. onBeforeUnbind();
  89918. }
  89919. this._currentFramebuffer = null;
  89920. };
  89921. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89922. var vbo = {
  89923. capacity: 1,
  89924. references: 1,
  89925. is32Bits: false
  89926. };
  89927. return vbo;
  89928. };
  89929. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  89930. if (offset === void 0) { offset = 0; }
  89931. };
  89932. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89933. };
  89934. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89935. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89936. this._boundTexturesCache[this._activeChannel] = texture;
  89937. }
  89938. };
  89939. NullEngine.prototype._bindTexture = function (channel, texture) {
  89940. if (channel < 0) {
  89941. return;
  89942. }
  89943. this._bindTextureDirectly(0, texture);
  89944. };
  89945. NullEngine.prototype._releaseBuffer = function (buffer) {
  89946. buffer.references--;
  89947. if (buffer.references === 0) {
  89948. return true;
  89949. }
  89950. return false;
  89951. };
  89952. return NullEngine;
  89953. }(BABYLON.Engine));
  89954. BABYLON.NullEngine = NullEngine;
  89955. })(BABYLON || (BABYLON = {}));
  89956. //# sourceMappingURL=babylon.nullEngine.js.map
  89957. "use strict";
  89958. var BABYLON;
  89959. (function (BABYLON) {
  89960. /**
  89961. * This class can be used to get instrumentation data from a Babylon engine
  89962. */
  89963. var EngineInstrumentation = /** @class */ (function () {
  89964. function EngineInstrumentation(engine) {
  89965. this.engine = engine;
  89966. this._captureGPUFrameTime = false;
  89967. this._gpuFrameTime = new BABYLON.PerfCounter();
  89968. this._captureShaderCompilationTime = false;
  89969. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89970. // Observers
  89971. this._onBeginFrameObserver = null;
  89972. this._onEndFrameObserver = null;
  89973. this._onBeforeShaderCompilationObserver = null;
  89974. this._onAfterShaderCompilationObserver = null;
  89975. }
  89976. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89977. // Properties
  89978. /**
  89979. * Gets the perf counter used for GPU frame time
  89980. */
  89981. get: function () {
  89982. return this._gpuFrameTime;
  89983. },
  89984. enumerable: true,
  89985. configurable: true
  89986. });
  89987. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89988. /**
  89989. * Gets the GPU frame time capture status
  89990. */
  89991. get: function () {
  89992. return this._captureGPUFrameTime;
  89993. },
  89994. /**
  89995. * Enable or disable the GPU frame time capture
  89996. */
  89997. set: function (value) {
  89998. var _this = this;
  89999. if (value === this._captureGPUFrameTime) {
  90000. return;
  90001. }
  90002. this._captureGPUFrameTime = value;
  90003. if (value) {
  90004. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90005. if (!_this._gpuFrameTimeToken) {
  90006. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90007. }
  90008. });
  90009. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90010. if (!_this._gpuFrameTimeToken) {
  90011. return;
  90012. }
  90013. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90014. if (time > -1) {
  90015. _this._gpuFrameTimeToken = null;
  90016. _this._gpuFrameTime.fetchNewFrame();
  90017. _this._gpuFrameTime.addCount(time, true);
  90018. }
  90019. });
  90020. }
  90021. else {
  90022. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90023. this._onBeginFrameObserver = null;
  90024. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90025. this._onEndFrameObserver = null;
  90026. }
  90027. },
  90028. enumerable: true,
  90029. configurable: true
  90030. });
  90031. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90032. /**
  90033. * Gets the perf counter used for shader compilation time
  90034. */
  90035. get: function () {
  90036. return this._shaderCompilationTime;
  90037. },
  90038. enumerable: true,
  90039. configurable: true
  90040. });
  90041. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90042. /**
  90043. * Gets the shader compilation time capture status
  90044. */
  90045. get: function () {
  90046. return this._captureShaderCompilationTime;
  90047. },
  90048. /**
  90049. * Enable or disable the shader compilation time capture
  90050. */
  90051. set: function (value) {
  90052. var _this = this;
  90053. if (value === this._captureShaderCompilationTime) {
  90054. return;
  90055. }
  90056. this._captureShaderCompilationTime = value;
  90057. if (value) {
  90058. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90059. _this._shaderCompilationTime.fetchNewFrame();
  90060. _this._shaderCompilationTime.beginMonitoring();
  90061. });
  90062. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90063. _this._shaderCompilationTime.endMonitoring();
  90064. });
  90065. }
  90066. else {
  90067. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90068. this._onBeforeShaderCompilationObserver = null;
  90069. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90070. this._onAfterShaderCompilationObserver = null;
  90071. }
  90072. },
  90073. enumerable: true,
  90074. configurable: true
  90075. });
  90076. EngineInstrumentation.prototype.dispose = function () {
  90077. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90078. this._onBeginFrameObserver = null;
  90079. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90080. this._onEndFrameObserver = null;
  90081. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90082. this._onBeforeShaderCompilationObserver = null;
  90083. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90084. this._onAfterShaderCompilationObserver = null;
  90085. this.engine = null;
  90086. };
  90087. return EngineInstrumentation;
  90088. }());
  90089. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90090. })(BABYLON || (BABYLON = {}));
  90091. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90092. "use strict";
  90093. var BABYLON;
  90094. (function (BABYLON) {
  90095. /**
  90096. * This class can be used to get instrumentation data from a Babylon engine
  90097. */
  90098. var SceneInstrumentation = /** @class */ (function () {
  90099. function SceneInstrumentation(scene) {
  90100. var _this = this;
  90101. this.scene = scene;
  90102. this._captureActiveMeshesEvaluationTime = false;
  90103. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90104. this._captureRenderTargetsRenderTime = false;
  90105. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90106. this._captureFrameTime = false;
  90107. this._frameTime = new BABYLON.PerfCounter();
  90108. this._captureRenderTime = false;
  90109. this._renderTime = new BABYLON.PerfCounter();
  90110. this._captureInterFrameTime = false;
  90111. this._interFrameTime = new BABYLON.PerfCounter();
  90112. this._captureParticlesRenderTime = false;
  90113. this._particlesRenderTime = new BABYLON.PerfCounter();
  90114. this._captureSpritesRenderTime = false;
  90115. this._spritesRenderTime = new BABYLON.PerfCounter();
  90116. this._capturePhysicsTime = false;
  90117. this._physicsTime = new BABYLON.PerfCounter();
  90118. this._captureAnimationsTime = false;
  90119. this._animationsTime = new BABYLON.PerfCounter();
  90120. // Observers
  90121. this._onBeforeActiveMeshesEvaluationObserver = null;
  90122. this._onAfterActiveMeshesEvaluationObserver = null;
  90123. this._onBeforeRenderTargetsRenderObserver = null;
  90124. this._onAfterRenderTargetsRenderObserver = null;
  90125. this._onAfterRenderObserver = null;
  90126. this._onBeforeDrawPhaseObserver = null;
  90127. this._onAfterDrawPhaseObserver = null;
  90128. this._onBeforeAnimationsObserver = null;
  90129. this._onBeforeParticlesRenderingObserver = null;
  90130. this._onAfterParticlesRenderingObserver = null;
  90131. this._onBeforeSpritesRenderingObserver = null;
  90132. this._onAfterSpritesRenderingObserver = null;
  90133. this._onBeforePhysicsObserver = null;
  90134. this._onAfterPhysicsObserver = null;
  90135. this._onAfterAnimationsObserver = null;
  90136. // Before render
  90137. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90138. if (_this._captureActiveMeshesEvaluationTime) {
  90139. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90140. }
  90141. if (_this._captureRenderTargetsRenderTime) {
  90142. _this._renderTargetsRenderTime.fetchNewFrame();
  90143. }
  90144. if (_this._captureFrameTime) {
  90145. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90146. _this._frameTime.beginMonitoring();
  90147. }
  90148. if (_this._captureInterFrameTime) {
  90149. _this._interFrameTime.endMonitoring();
  90150. }
  90151. if (_this._captureParticlesRenderTime) {
  90152. _this._particlesRenderTime.fetchNewFrame();
  90153. }
  90154. if (_this._captureSpritesRenderTime) {
  90155. _this._spritesRenderTime.fetchNewFrame();
  90156. }
  90157. if (_this._captureAnimationsTime) {
  90158. _this._animationsTime.beginMonitoring();
  90159. }
  90160. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90161. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90162. });
  90163. // After render
  90164. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90165. if (_this._captureFrameTime) {
  90166. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90167. _this._frameTime.endMonitoring();
  90168. }
  90169. if (_this._captureRenderTime) {
  90170. _this._renderTime.endMonitoring(false);
  90171. }
  90172. if (_this._captureInterFrameTime) {
  90173. _this._interFrameTime.beginMonitoring();
  90174. }
  90175. });
  90176. }
  90177. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90178. // Properties
  90179. /**
  90180. * Gets the perf counter used for active meshes evaluation time
  90181. */
  90182. get: function () {
  90183. return this._activeMeshesEvaluationTime;
  90184. },
  90185. enumerable: true,
  90186. configurable: true
  90187. });
  90188. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90189. /**
  90190. * Gets the active meshes evaluation time capture status
  90191. */
  90192. get: function () {
  90193. return this._captureActiveMeshesEvaluationTime;
  90194. },
  90195. /**
  90196. * Enable or disable the active meshes evaluation time capture
  90197. */
  90198. set: function (value) {
  90199. var _this = this;
  90200. if (value === this._captureActiveMeshesEvaluationTime) {
  90201. return;
  90202. }
  90203. this._captureActiveMeshesEvaluationTime = value;
  90204. if (value) {
  90205. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90206. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90207. _this._activeMeshesEvaluationTime.beginMonitoring();
  90208. });
  90209. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90210. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90211. _this._activeMeshesEvaluationTime.endMonitoring();
  90212. });
  90213. }
  90214. else {
  90215. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90216. this._onBeforeActiveMeshesEvaluationObserver = null;
  90217. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90218. this._onAfterActiveMeshesEvaluationObserver = null;
  90219. }
  90220. },
  90221. enumerable: true,
  90222. configurable: true
  90223. });
  90224. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90225. /**
  90226. * Gets the perf counter used for render targets render time
  90227. */
  90228. get: function () {
  90229. return this._renderTargetsRenderTime;
  90230. },
  90231. enumerable: true,
  90232. configurable: true
  90233. });
  90234. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90235. /**
  90236. * Gets the render targets render time capture status
  90237. */
  90238. get: function () {
  90239. return this._captureRenderTargetsRenderTime;
  90240. },
  90241. /**
  90242. * Enable or disable the render targets render time capture
  90243. */
  90244. set: function (value) {
  90245. var _this = this;
  90246. if (value === this._captureRenderTargetsRenderTime) {
  90247. return;
  90248. }
  90249. this._captureRenderTargetsRenderTime = value;
  90250. if (value) {
  90251. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90252. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90253. _this._renderTargetsRenderTime.beginMonitoring();
  90254. });
  90255. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90256. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90257. _this._renderTargetsRenderTime.endMonitoring(false);
  90258. });
  90259. }
  90260. else {
  90261. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90262. this._onBeforeRenderTargetsRenderObserver = null;
  90263. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90264. this._onAfterRenderTargetsRenderObserver = null;
  90265. }
  90266. },
  90267. enumerable: true,
  90268. configurable: true
  90269. });
  90270. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90271. /**
  90272. * Gets the perf counter used for particles render time
  90273. */
  90274. get: function () {
  90275. return this._particlesRenderTime;
  90276. },
  90277. enumerable: true,
  90278. configurable: true
  90279. });
  90280. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90281. /**
  90282. * Gets the particles render time capture status
  90283. */
  90284. get: function () {
  90285. return this._captureParticlesRenderTime;
  90286. },
  90287. /**
  90288. * Enable or disable the particles render time capture
  90289. */
  90290. set: function (value) {
  90291. var _this = this;
  90292. if (value === this._captureParticlesRenderTime) {
  90293. return;
  90294. }
  90295. this._captureParticlesRenderTime = value;
  90296. if (value) {
  90297. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90298. BABYLON.Tools.StartPerformanceCounter("Particles");
  90299. _this._particlesRenderTime.beginMonitoring();
  90300. });
  90301. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90302. BABYLON.Tools.EndPerformanceCounter("Particles");
  90303. _this._particlesRenderTime.endMonitoring(false);
  90304. });
  90305. }
  90306. else {
  90307. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90308. this._onBeforeParticlesRenderingObserver = null;
  90309. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90310. this._onAfterParticlesRenderingObserver = null;
  90311. }
  90312. },
  90313. enumerable: true,
  90314. configurable: true
  90315. });
  90316. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90317. /**
  90318. * Gets the perf counter used for sprites render time
  90319. */
  90320. get: function () {
  90321. return this._spritesRenderTime;
  90322. },
  90323. enumerable: true,
  90324. configurable: true
  90325. });
  90326. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90327. /**
  90328. * Gets the sprites render time capture status
  90329. */
  90330. get: function () {
  90331. return this._captureSpritesRenderTime;
  90332. },
  90333. /**
  90334. * Enable or disable the sprites render time capture
  90335. */
  90336. set: function (value) {
  90337. var _this = this;
  90338. if (value === this._captureSpritesRenderTime) {
  90339. return;
  90340. }
  90341. this._captureSpritesRenderTime = value;
  90342. if (value) {
  90343. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90344. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90345. _this._spritesRenderTime.beginMonitoring();
  90346. });
  90347. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90348. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90349. _this._spritesRenderTime.endMonitoring(false);
  90350. });
  90351. }
  90352. else {
  90353. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90354. this._onBeforeSpritesRenderingObserver = null;
  90355. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90356. this._onAfterSpritesRenderingObserver = null;
  90357. }
  90358. },
  90359. enumerable: true,
  90360. configurable: true
  90361. });
  90362. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90363. /**
  90364. * Gets the perf counter used for physics time
  90365. */
  90366. get: function () {
  90367. return this._physicsTime;
  90368. },
  90369. enumerable: true,
  90370. configurable: true
  90371. });
  90372. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90373. /**
  90374. * Gets the physics time capture status
  90375. */
  90376. get: function () {
  90377. return this._capturePhysicsTime;
  90378. },
  90379. /**
  90380. * Enable or disable the physics time capture
  90381. */
  90382. set: function (value) {
  90383. var _this = this;
  90384. if (value === this._capturePhysicsTime) {
  90385. return;
  90386. }
  90387. this._capturePhysicsTime = value;
  90388. if (value) {
  90389. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90390. BABYLON.Tools.StartPerformanceCounter("Physics");
  90391. _this._physicsTime.beginMonitoring();
  90392. });
  90393. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90394. BABYLON.Tools.EndPerformanceCounter("Physics");
  90395. _this._physicsTime.endMonitoring();
  90396. });
  90397. }
  90398. else {
  90399. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90400. this._onBeforePhysicsObserver = null;
  90401. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90402. this._onAfterPhysicsObserver = null;
  90403. }
  90404. },
  90405. enumerable: true,
  90406. configurable: true
  90407. });
  90408. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90409. /**
  90410. * Gets the perf counter used for animations time
  90411. */
  90412. get: function () {
  90413. return this._animationsTime;
  90414. },
  90415. enumerable: true,
  90416. configurable: true
  90417. });
  90418. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90419. /**
  90420. * Gets the animations time capture status
  90421. */
  90422. get: function () {
  90423. return this._captureAnimationsTime;
  90424. },
  90425. /**
  90426. * Enable or disable the animations time capture
  90427. */
  90428. set: function (value) {
  90429. var _this = this;
  90430. if (value === this._captureAnimationsTime) {
  90431. return;
  90432. }
  90433. this._captureAnimationsTime = value;
  90434. if (value) {
  90435. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90436. _this._animationsTime.endMonitoring();
  90437. });
  90438. }
  90439. else {
  90440. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90441. this._onAfterAnimationsObserver = null;
  90442. }
  90443. },
  90444. enumerable: true,
  90445. configurable: true
  90446. });
  90447. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90448. /**
  90449. * Gets the perf counter used for frame time capture
  90450. */
  90451. get: function () {
  90452. return this._frameTime;
  90453. },
  90454. enumerable: true,
  90455. configurable: true
  90456. });
  90457. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90458. /**
  90459. * Gets the frame time capture status
  90460. */
  90461. get: function () {
  90462. return this._captureFrameTime;
  90463. },
  90464. /**
  90465. * Enable or disable the frame time capture
  90466. */
  90467. set: function (value) {
  90468. this._captureFrameTime = value;
  90469. },
  90470. enumerable: true,
  90471. configurable: true
  90472. });
  90473. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90474. /**
  90475. * Gets the perf counter used for inter-frames time capture
  90476. */
  90477. get: function () {
  90478. return this._interFrameTime;
  90479. },
  90480. enumerable: true,
  90481. configurable: true
  90482. });
  90483. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90484. /**
  90485. * Gets the inter-frames time capture status
  90486. */
  90487. get: function () {
  90488. return this._captureInterFrameTime;
  90489. },
  90490. /**
  90491. * Enable or disable the inter-frames time capture
  90492. */
  90493. set: function (value) {
  90494. this._captureInterFrameTime = value;
  90495. },
  90496. enumerable: true,
  90497. configurable: true
  90498. });
  90499. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90500. /**
  90501. * Gets the perf counter used for render time capture
  90502. */
  90503. get: function () {
  90504. return this._renderTime;
  90505. },
  90506. enumerable: true,
  90507. configurable: true
  90508. });
  90509. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90510. /**
  90511. * Gets the render time capture status
  90512. */
  90513. get: function () {
  90514. return this._captureRenderTime;
  90515. },
  90516. /**
  90517. * Enable or disable the render time capture
  90518. */
  90519. set: function (value) {
  90520. var _this = this;
  90521. if (value === this._captureRenderTime) {
  90522. return;
  90523. }
  90524. this._captureRenderTime = value;
  90525. if (value) {
  90526. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90527. _this._renderTime.beginMonitoring();
  90528. BABYLON.Tools.StartPerformanceCounter("Main render");
  90529. });
  90530. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90531. _this._renderTime.endMonitoring(false);
  90532. BABYLON.Tools.EndPerformanceCounter("Main render");
  90533. });
  90534. }
  90535. else {
  90536. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90537. this._onBeforeDrawPhaseObserver = null;
  90538. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90539. this._onAfterDrawPhaseObserver = null;
  90540. }
  90541. },
  90542. enumerable: true,
  90543. configurable: true
  90544. });
  90545. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90546. /**
  90547. * Gets the perf counter used for draw calls
  90548. */
  90549. get: function () {
  90550. return this.scene.getEngine()._drawCalls;
  90551. },
  90552. enumerable: true,
  90553. configurable: true
  90554. });
  90555. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90556. /**
  90557. * Gets the perf counter used for texture collisions
  90558. */
  90559. get: function () {
  90560. return this.scene.getEngine()._textureCollisions;
  90561. },
  90562. enumerable: true,
  90563. configurable: true
  90564. });
  90565. SceneInstrumentation.prototype.dispose = function () {
  90566. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90567. this._onAfterRenderObserver = null;
  90568. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90569. this._onBeforeActiveMeshesEvaluationObserver = null;
  90570. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90571. this._onAfterActiveMeshesEvaluationObserver = null;
  90572. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90573. this._onBeforeRenderTargetsRenderObserver = null;
  90574. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90575. this._onAfterRenderTargetsRenderObserver = null;
  90576. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90577. this._onBeforeAnimationsObserver = null;
  90578. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90579. this._onBeforeParticlesRenderingObserver = null;
  90580. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90581. this._onAfterParticlesRenderingObserver = null;
  90582. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90583. this._onBeforeSpritesRenderingObserver = null;
  90584. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90585. this._onAfterSpritesRenderingObserver = null;
  90586. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90587. this._onBeforeDrawPhaseObserver = null;
  90588. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90589. this._onAfterDrawPhaseObserver = null;
  90590. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90591. this._onBeforePhysicsObserver = null;
  90592. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90593. this._onAfterPhysicsObserver = null;
  90594. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90595. this._onAfterAnimationsObserver = null;
  90596. this.scene = null;
  90597. };
  90598. return SceneInstrumentation;
  90599. }());
  90600. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90601. })(BABYLON || (BABYLON = {}));
  90602. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90603. "use strict";
  90604. var BABYLON;
  90605. (function (BABYLON) {
  90606. var _TimeToken = /** @class */ (function () {
  90607. function _TimeToken() {
  90608. this._timeElapsedQueryEnded = false;
  90609. }
  90610. return _TimeToken;
  90611. }());
  90612. BABYLON._TimeToken = _TimeToken;
  90613. })(BABYLON || (BABYLON = {}));
  90614. //# sourceMappingURL=babylon.timeToken.js.map
  90615. "use strict";
  90616. var BABYLON;
  90617. (function (BABYLON) {
  90618. /**
  90619. * Background material defines definition.
  90620. * @ignore Mainly internal Use
  90621. */
  90622. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90623. __extends(BackgroundMaterialDefines, _super);
  90624. /**
  90625. * Constructor of the defines.
  90626. */
  90627. function BackgroundMaterialDefines() {
  90628. var _this = _super.call(this) || this;
  90629. /**
  90630. * True if the diffuse texture is in use.
  90631. */
  90632. _this.DIFFUSE = false;
  90633. /**
  90634. * The direct UV channel to use.
  90635. */
  90636. _this.DIFFUSEDIRECTUV = 0;
  90637. /**
  90638. * True if the diffuse texture is in gamma space.
  90639. */
  90640. _this.GAMMADIFFUSE = false;
  90641. /**
  90642. * True if the diffuse texture has opacity in the alpha channel.
  90643. */
  90644. _this.DIFFUSEHASALPHA = false;
  90645. /**
  90646. * True if you want the material to fade to transparent at grazing angle.
  90647. */
  90648. _this.OPACITYFRESNEL = false;
  90649. /**
  90650. * True if an extra blur needs to be added in the reflection.
  90651. */
  90652. _this.REFLECTIONBLUR = false;
  90653. /**
  90654. * True if you want the material to fade to reflection at grazing angle.
  90655. */
  90656. _this.REFLECTIONFRESNEL = false;
  90657. /**
  90658. * True if you want the material to falloff as far as you move away from the scene center.
  90659. */
  90660. _this.REFLECTIONFALLOFF = false;
  90661. /**
  90662. * False if the current Webgl implementation does not support the texture lod extension.
  90663. */
  90664. _this.TEXTURELODSUPPORT = false;
  90665. /**
  90666. * True to ensure the data are premultiplied.
  90667. */
  90668. _this.PREMULTIPLYALPHA = false;
  90669. /**
  90670. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90671. */
  90672. _this.USERGBCOLOR = false;
  90673. /**
  90674. * True to add noise in order to reduce the banding effect.
  90675. */
  90676. _this.NOISE = false;
  90677. /**
  90678. * is the reflection texture in BGR color scheme?
  90679. * Mainly used to solve a bug in ios10 video tag
  90680. */
  90681. _this.REFLECTIONBGR = false;
  90682. _this.IMAGEPROCESSING = false;
  90683. _this.VIGNETTE = false;
  90684. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90685. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90686. _this.TONEMAPPING = false;
  90687. _this.CONTRAST = false;
  90688. _this.COLORCURVES = false;
  90689. _this.COLORGRADING = false;
  90690. _this.COLORGRADING3D = false;
  90691. _this.SAMPLER3DGREENDEPTH = false;
  90692. _this.SAMPLER3DBGRMAP = false;
  90693. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90694. _this.EXPOSURE = false;
  90695. // Reflection.
  90696. _this.REFLECTION = false;
  90697. _this.REFLECTIONMAP_3D = false;
  90698. _this.REFLECTIONMAP_SPHERICAL = false;
  90699. _this.REFLECTIONMAP_PLANAR = false;
  90700. _this.REFLECTIONMAP_CUBIC = false;
  90701. _this.REFLECTIONMAP_PROJECTION = false;
  90702. _this.REFLECTIONMAP_SKYBOX = false;
  90703. _this.REFLECTIONMAP_EXPLICIT = false;
  90704. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90705. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90706. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90707. _this.INVERTCUBICMAP = false;
  90708. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90709. _this.LODINREFLECTIONALPHA = false;
  90710. _this.GAMMAREFLECTION = false;
  90711. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90712. // Default BJS.
  90713. _this.MAINUV1 = false;
  90714. _this.MAINUV2 = false;
  90715. _this.UV1 = false;
  90716. _this.UV2 = false;
  90717. _this.CLIPPLANE = false;
  90718. _this.POINTSIZE = false;
  90719. _this.FOG = false;
  90720. _this.NORMAL = false;
  90721. _this.NUM_BONE_INFLUENCERS = 0;
  90722. _this.BonesPerMesh = 0;
  90723. _this.INSTANCES = false;
  90724. _this.SHADOWFLOAT = false;
  90725. _this.rebuild();
  90726. return _this;
  90727. }
  90728. return BackgroundMaterialDefines;
  90729. }(BABYLON.MaterialDefines));
  90730. /**
  90731. * Background material used to create an efficient environement around your scene.
  90732. */
  90733. var BackgroundMaterial = /** @class */ (function (_super) {
  90734. __extends(BackgroundMaterial, _super);
  90735. /**
  90736. * Instantiates a Background Material in the given scene
  90737. * @param name The friendly name of the material
  90738. * @param scene The scene to add the material to
  90739. */
  90740. function BackgroundMaterial(name, scene) {
  90741. var _this = _super.call(this, name, scene) || this;
  90742. /**
  90743. * Key light Color (multiply against the R channel of the environement texture)
  90744. */
  90745. _this.primaryColor = BABYLON.Color3.White();
  90746. /**
  90747. * Key light Level (allowing HDR output of the background)
  90748. */
  90749. _this.primaryLevel = 1;
  90750. /**
  90751. * Secondary light Color (multiply against the G channel of the environement texture)
  90752. */
  90753. _this.secondaryColor = BABYLON.Color3.Gray();
  90754. /**
  90755. * Secondary light Level (allowing HDR output of the background)
  90756. */
  90757. _this.secondaryLevel = 1;
  90758. /**
  90759. * Tertiary light Color (multiply against the B channel of the environement texture)
  90760. */
  90761. _this.tertiaryColor = BABYLON.Color3.Black();
  90762. /**
  90763. * Tertiary light Level (allowing HDR output of the background)
  90764. */
  90765. _this.tertiaryLevel = 1;
  90766. /**
  90767. * Reflection Texture used in the material.
  90768. * Should be author in a specific way for the best result (refer to the documentation).
  90769. */
  90770. _this.reflectionTexture = null;
  90771. /**
  90772. * Reflection Texture level of blur.
  90773. *
  90774. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90775. * texture twice.
  90776. */
  90777. _this.reflectionBlur = 0;
  90778. /**
  90779. * Diffuse Texture used in the material.
  90780. * Should be author in a specific way for the best result (refer to the documentation).
  90781. */
  90782. _this.diffuseTexture = null;
  90783. _this._shadowLights = null;
  90784. /**
  90785. * Specify the list of lights casting shadow on the material.
  90786. * All scene shadow lights will be included if null.
  90787. */
  90788. _this.shadowLights = null;
  90789. /**
  90790. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90791. * soft lighting on the background.
  90792. */
  90793. _this.shadowBlurScale = 1;
  90794. /**
  90795. * Helps adjusting the shadow to a softer level if required.
  90796. * 0 means black shadows and 1 means no shadows.
  90797. */
  90798. _this.shadowLevel = 0;
  90799. /**
  90800. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90801. * It is usually zero but might be interesting to modify according to your setup.
  90802. */
  90803. _this.sceneCenter = BABYLON.Vector3.Zero();
  90804. /**
  90805. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90806. * This helps ensuring a nice transition when the camera goes under the ground.
  90807. */
  90808. _this.opacityFresnel = true;
  90809. /**
  90810. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90811. * This helps adding a mirror texture on the ground.
  90812. */
  90813. _this.reflectionFresnel = false;
  90814. /**
  90815. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90816. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90817. */
  90818. _this.reflectionFalloffDistance = 0.0;
  90819. /**
  90820. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90821. */
  90822. _this.reflectionAmount = 1.0;
  90823. /**
  90824. * This specifies the weight of the reflection at grazing angle.
  90825. */
  90826. _this.reflectionReflectance0 = 0.05;
  90827. /**
  90828. * This specifies the weight of the reflection at a perpendicular point of view.
  90829. */
  90830. _this.reflectionReflectance90 = 0.5;
  90831. /**
  90832. * Helps to directly use the maps channels instead of their level.
  90833. */
  90834. _this.useRGBColor = true;
  90835. /**
  90836. * This helps reducing the banding effect that could occur on the background.
  90837. */
  90838. _this.enableNoise = false;
  90839. _this._fovMultiplier = 1.0;
  90840. /**
  90841. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90842. */
  90843. _this.useEquirectangularFOV = false;
  90844. _this._maxSimultaneousLights = 4;
  90845. /**
  90846. * Number of Simultaneous lights allowed on the material.
  90847. */
  90848. _this.maxSimultaneousLights = 4;
  90849. /**
  90850. * Keep track of the image processing observer to allow dispose and replace.
  90851. */
  90852. _this._imageProcessingObserver = null;
  90853. /**
  90854. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90855. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90856. */
  90857. _this.switchToBGR = false;
  90858. // Temp values kept as cache in the material.
  90859. _this._renderTargets = new BABYLON.SmartArray(16);
  90860. _this._reflectionControls = BABYLON.Vector4.Zero();
  90861. // Setup the default processing configuration to the scene.
  90862. _this._attachImageProcessingConfiguration(null);
  90863. _this.getRenderTargetTextures = function () {
  90864. _this._renderTargets.reset();
  90865. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90866. _this._renderTargets.push(_this._diffuseTexture);
  90867. }
  90868. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90869. _this._renderTargets.push(_this._reflectionTexture);
  90870. }
  90871. return _this._renderTargets;
  90872. };
  90873. return _this;
  90874. }
  90875. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90876. /**
  90877. * Sets the reflection reflectance fresnel values according to the default standard
  90878. * empirically know to work well :-)
  90879. */
  90880. set: function (value) {
  90881. var reflectionWeight = value;
  90882. if (reflectionWeight < 0.5) {
  90883. reflectionWeight = reflectionWeight * 2.0;
  90884. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90885. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90886. }
  90887. else {
  90888. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90889. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90890. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90891. }
  90892. },
  90893. enumerable: true,
  90894. configurable: true
  90895. });
  90896. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90897. /**
  90898. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90899. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90900. * Recommended to be keep at 1.0 except for special cases.
  90901. */
  90902. get: function () {
  90903. return this._fovMultiplier;
  90904. },
  90905. set: function (value) {
  90906. if (isNaN(value)) {
  90907. value = 1.0;
  90908. }
  90909. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90910. },
  90911. enumerable: true,
  90912. configurable: true
  90913. });
  90914. /**
  90915. * Attaches a new image processing configuration to the PBR Material.
  90916. * @param configuration (if null the scene configuration will be use)
  90917. */
  90918. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90919. var _this = this;
  90920. if (configuration === this._imageProcessingConfiguration) {
  90921. return;
  90922. }
  90923. // Detaches observer.
  90924. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90925. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90926. }
  90927. // Pick the scene configuration if needed.
  90928. if (!configuration) {
  90929. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  90930. }
  90931. else {
  90932. this._imageProcessingConfiguration = configuration;
  90933. }
  90934. // Attaches observer.
  90935. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90936. _this._markAllSubMeshesAsImageProcessingDirty();
  90937. });
  90938. };
  90939. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90940. /**
  90941. * Gets the image processing configuration used either in this material.
  90942. */
  90943. get: function () {
  90944. return this._imageProcessingConfiguration;
  90945. },
  90946. /**
  90947. * Sets the Default image processing configuration used either in the this material.
  90948. *
  90949. * If sets to null, the scene one is in use.
  90950. */
  90951. set: function (value) {
  90952. this._attachImageProcessingConfiguration(value);
  90953. // Ensure the effect will be rebuilt.
  90954. this._markAllSubMeshesAsTexturesDirty();
  90955. },
  90956. enumerable: true,
  90957. configurable: true
  90958. });
  90959. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90960. /**
  90961. * Gets wether the color curves effect is enabled.
  90962. */
  90963. get: function () {
  90964. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90965. },
  90966. /**
  90967. * Sets wether the color curves effect is enabled.
  90968. */
  90969. set: function (value) {
  90970. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90971. },
  90972. enumerable: true,
  90973. configurable: true
  90974. });
  90975. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90976. /**
  90977. * Gets wether the color grading effect is enabled.
  90978. */
  90979. get: function () {
  90980. return this.imageProcessingConfiguration.colorGradingEnabled;
  90981. },
  90982. /**
  90983. * Gets wether the color grading effect is enabled.
  90984. */
  90985. set: function (value) {
  90986. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90987. },
  90988. enumerable: true,
  90989. configurable: true
  90990. });
  90991. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90992. /**
  90993. * Gets wether tonemapping is enabled or not.
  90994. */
  90995. get: function () {
  90996. return this._imageProcessingConfiguration.toneMappingEnabled;
  90997. },
  90998. /**
  90999. * Sets wether tonemapping is enabled or not
  91000. */
  91001. set: function (value) {
  91002. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91003. },
  91004. enumerable: true,
  91005. configurable: true
  91006. });
  91007. ;
  91008. ;
  91009. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91010. /**
  91011. * The camera exposure used on this material.
  91012. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91013. * This corresponds to a photographic exposure.
  91014. */
  91015. get: function () {
  91016. return this._imageProcessingConfiguration.exposure;
  91017. },
  91018. /**
  91019. * The camera exposure used on this material.
  91020. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91021. * This corresponds to a photographic exposure.
  91022. */
  91023. set: function (value) {
  91024. this._imageProcessingConfiguration.exposure = value;
  91025. },
  91026. enumerable: true,
  91027. configurable: true
  91028. });
  91029. ;
  91030. ;
  91031. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91032. /**
  91033. * Gets The camera contrast used on this material.
  91034. */
  91035. get: function () {
  91036. return this._imageProcessingConfiguration.contrast;
  91037. },
  91038. /**
  91039. * Sets The camera contrast used on this material.
  91040. */
  91041. set: function (value) {
  91042. this._imageProcessingConfiguration.contrast = value;
  91043. },
  91044. enumerable: true,
  91045. configurable: true
  91046. });
  91047. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91048. /**
  91049. * Gets the Color Grading 2D Lookup Texture.
  91050. */
  91051. get: function () {
  91052. return this._imageProcessingConfiguration.colorGradingTexture;
  91053. },
  91054. /**
  91055. * Sets the Color Grading 2D Lookup Texture.
  91056. */
  91057. set: function (value) {
  91058. this.imageProcessingConfiguration.colorGradingTexture = value;
  91059. },
  91060. enumerable: true,
  91061. configurable: true
  91062. });
  91063. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91064. /**
  91065. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91066. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91067. * 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;
  91068. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91069. */
  91070. get: function () {
  91071. return this.imageProcessingConfiguration.colorCurves;
  91072. },
  91073. /**
  91074. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91075. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91076. * 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;
  91077. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91078. */
  91079. set: function (value) {
  91080. this.imageProcessingConfiguration.colorCurves = value;
  91081. },
  91082. enumerable: true,
  91083. configurable: true
  91084. });
  91085. /**
  91086. * The entire material has been created in order to prevent overdraw.
  91087. * @returns false
  91088. */
  91089. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91090. return true;
  91091. };
  91092. /**
  91093. * The entire material has been created in order to prevent overdraw.
  91094. * @returns true if blending is enable
  91095. */
  91096. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91097. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91098. };
  91099. /**
  91100. * Checks wether the material is ready to be rendered for a given mesh.
  91101. * @param mesh The mesh to render
  91102. * @param subMesh The submesh to check against
  91103. * @param useInstances Specify wether or not the material is used with instances
  91104. * @returns true if all the dependencies are ready (Textures, Effects...)
  91105. */
  91106. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91107. var _this = this;
  91108. if (useInstances === void 0) { useInstances = false; }
  91109. if (subMesh.effect && this.isFrozen) {
  91110. if (this._wasPreviouslyReady) {
  91111. return true;
  91112. }
  91113. }
  91114. if (!subMesh._materialDefines) {
  91115. subMesh._materialDefines = new BackgroundMaterialDefines();
  91116. }
  91117. var scene = this.getScene();
  91118. var defines = subMesh._materialDefines;
  91119. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91120. if (defines._renderId === scene.getRenderId()) {
  91121. return true;
  91122. }
  91123. }
  91124. var engine = scene.getEngine();
  91125. // Lights
  91126. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91127. defines._needNormals = true;
  91128. // Textures
  91129. if (defines._areTexturesDirty) {
  91130. defines._needUVs = false;
  91131. if (scene.texturesEnabled) {
  91132. if (scene.getEngine().getCaps().textureLOD) {
  91133. defines.TEXTURELODSUPPORT = true;
  91134. }
  91135. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91136. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91137. return false;
  91138. }
  91139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91140. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91141. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91142. defines.OPACITYFRESNEL = this._opacityFresnel;
  91143. }
  91144. else {
  91145. defines.DIFFUSE = false;
  91146. defines.DIFFUSEHASALPHA = false;
  91147. defines.GAMMADIFFUSE = false;
  91148. defines.OPACITYFRESNEL = false;
  91149. }
  91150. var reflectionTexture = this._reflectionTexture;
  91151. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91152. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91153. return false;
  91154. }
  91155. defines.REFLECTION = true;
  91156. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91157. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91158. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91159. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91160. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91161. defines.REFLECTIONBGR = this.switchToBGR;
  91162. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91163. defines.INVERTCUBICMAP = true;
  91164. }
  91165. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91166. switch (reflectionTexture.coordinatesMode) {
  91167. case BABYLON.Texture.CUBIC_MODE:
  91168. case BABYLON.Texture.INVCUBIC_MODE:
  91169. defines.REFLECTIONMAP_CUBIC = true;
  91170. break;
  91171. case BABYLON.Texture.EXPLICIT_MODE:
  91172. defines.REFLECTIONMAP_EXPLICIT = true;
  91173. break;
  91174. case BABYLON.Texture.PLANAR_MODE:
  91175. defines.REFLECTIONMAP_PLANAR = true;
  91176. break;
  91177. case BABYLON.Texture.PROJECTION_MODE:
  91178. defines.REFLECTIONMAP_PROJECTION = true;
  91179. break;
  91180. case BABYLON.Texture.SKYBOX_MODE:
  91181. defines.REFLECTIONMAP_SKYBOX = true;
  91182. break;
  91183. case BABYLON.Texture.SPHERICAL_MODE:
  91184. defines.REFLECTIONMAP_SPHERICAL = true;
  91185. break;
  91186. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91187. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91188. break;
  91189. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91190. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91191. break;
  91192. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91193. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91194. break;
  91195. }
  91196. if (this.reflectionFresnel) {
  91197. defines.REFLECTIONFRESNEL = true;
  91198. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91199. this._reflectionControls.x = this.reflectionAmount;
  91200. this._reflectionControls.y = this.reflectionReflectance0;
  91201. this._reflectionControls.z = this.reflectionReflectance90;
  91202. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91203. }
  91204. else {
  91205. defines.REFLECTIONFRESNEL = false;
  91206. defines.REFLECTIONFALLOFF = false;
  91207. }
  91208. }
  91209. else {
  91210. defines.REFLECTION = false;
  91211. defines.REFLECTIONFALLOFF = false;
  91212. defines.REFLECTIONBLUR = false;
  91213. defines.REFLECTIONMAP_3D = false;
  91214. defines.REFLECTIONMAP_SPHERICAL = false;
  91215. defines.REFLECTIONMAP_PLANAR = false;
  91216. defines.REFLECTIONMAP_CUBIC = false;
  91217. defines.REFLECTIONMAP_PROJECTION = false;
  91218. defines.REFLECTIONMAP_SKYBOX = false;
  91219. defines.REFLECTIONMAP_EXPLICIT = false;
  91220. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91221. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91222. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91223. defines.INVERTCUBICMAP = false;
  91224. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91225. defines.LODINREFLECTIONALPHA = false;
  91226. defines.GAMMAREFLECTION = false;
  91227. }
  91228. }
  91229. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91230. defines.USERGBCOLOR = this._useRGBColor;
  91231. defines.NOISE = this._enableNoise;
  91232. }
  91233. if (defines._areImageProcessingDirty) {
  91234. if (!this._imageProcessingConfiguration.isReady()) {
  91235. return false;
  91236. }
  91237. this._imageProcessingConfiguration.prepareDefines(defines);
  91238. }
  91239. // Misc.
  91240. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91241. // Values that need to be evaluated on every frame
  91242. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91243. // Attribs
  91244. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91245. if (mesh) {
  91246. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91247. mesh.createNormals(true);
  91248. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91249. }
  91250. }
  91251. }
  91252. // Get correct effect
  91253. if (defines.isDirty) {
  91254. defines.markAsProcessed();
  91255. scene.resetCachedMaterial();
  91256. // Fallbacks
  91257. var fallbacks = new BABYLON.EffectFallbacks();
  91258. if (defines.FOG) {
  91259. fallbacks.addFallback(0, "FOG");
  91260. }
  91261. if (defines.POINTSIZE) {
  91262. fallbacks.addFallback(1, "POINTSIZE");
  91263. }
  91264. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91265. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91266. fallbacks.addCPUSkinningFallback(0, mesh);
  91267. }
  91268. //Attributes
  91269. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91270. if (defines.NORMAL) {
  91271. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91272. }
  91273. if (defines.UV1) {
  91274. attribs.push(BABYLON.VertexBuffer.UVKind);
  91275. }
  91276. if (defines.UV2) {
  91277. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91278. }
  91279. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91280. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91281. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91282. "vFogInfos", "vFogColor", "pointSize",
  91283. "vClipPlane", "mBones",
  91284. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91285. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91286. "shadowLevel", "alpha",
  91287. "vBackgroundCenter", "vReflectionControl",
  91288. "vDiffuseInfos", "diffuseMatrix",
  91289. ];
  91290. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91291. var uniformBuffers = ["Material", "Scene"];
  91292. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91293. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91294. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91295. uniformsNames: uniforms,
  91296. uniformBuffersNames: uniformBuffers,
  91297. samplers: samplers,
  91298. defines: defines,
  91299. maxSimultaneousLights: this._maxSimultaneousLights
  91300. });
  91301. var onCompiled = function (effect) {
  91302. if (_this.onCompiled) {
  91303. _this.onCompiled(effect);
  91304. }
  91305. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91306. };
  91307. var join = defines.toString();
  91308. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91309. attributes: attribs,
  91310. uniformsNames: uniforms,
  91311. uniformBuffersNames: uniformBuffers,
  91312. samplers: samplers,
  91313. defines: join,
  91314. fallbacks: fallbacks,
  91315. onCompiled: onCompiled,
  91316. onError: this.onError,
  91317. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91318. }, engine), defines);
  91319. this.buildUniformLayout();
  91320. }
  91321. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91322. return false;
  91323. }
  91324. defines._renderId = scene.getRenderId();
  91325. this._wasPreviouslyReady = true;
  91326. return true;
  91327. };
  91328. /**
  91329. * Build the uniform buffer used in the material.
  91330. */
  91331. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91332. // Order is important !
  91333. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91334. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91335. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91336. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91337. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91338. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91339. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91340. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91341. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91342. this._uniformBuffer.addUniform("pointSize", 1);
  91343. this._uniformBuffer.addUniform("shadowLevel", 1);
  91344. this._uniformBuffer.addUniform("alpha", 1);
  91345. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91346. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91347. this._uniformBuffer.create();
  91348. };
  91349. /**
  91350. * Unbind the material.
  91351. */
  91352. BackgroundMaterial.prototype.unbind = function () {
  91353. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91354. this._uniformBuffer.setTexture("diffuseSampler", null);
  91355. }
  91356. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91357. this._uniformBuffer.setTexture("reflectionSampler", null);
  91358. }
  91359. _super.prototype.unbind.call(this);
  91360. };
  91361. /**
  91362. * Bind only the world matrix to the material.
  91363. * @param world The world matrix to bind.
  91364. */
  91365. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91366. this._activeEffect.setMatrix("world", world);
  91367. };
  91368. /**
  91369. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91370. * @param world The world matrix to bind.
  91371. * @param subMesh The submesh to bind for.
  91372. */
  91373. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91374. var scene = this.getScene();
  91375. var defines = subMesh._materialDefines;
  91376. if (!defines) {
  91377. return;
  91378. }
  91379. var effect = subMesh.effect;
  91380. if (!effect) {
  91381. return;
  91382. }
  91383. this._activeEffect = effect;
  91384. // Matrices
  91385. this.bindOnlyWorldMatrix(world);
  91386. // Bones
  91387. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91388. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91389. if (mustRebind) {
  91390. this._uniformBuffer.bindToEffect(effect, "Material");
  91391. this.bindViewProjection(effect);
  91392. var reflectionTexture = this._reflectionTexture;
  91393. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91394. // Texture uniforms
  91395. if (scene.texturesEnabled) {
  91396. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91397. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91398. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91399. }
  91400. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91401. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91402. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91403. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91404. }
  91405. }
  91406. if (this.shadowLevel > 0) {
  91407. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91408. }
  91409. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91410. // Point size
  91411. if (this.pointsCloud) {
  91412. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91413. }
  91414. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91415. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91416. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91417. }
  91418. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91419. // Textures
  91420. if (scene.texturesEnabled) {
  91421. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91422. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91423. }
  91424. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91425. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91426. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91427. }
  91428. else if (!defines.REFLECTIONBLUR) {
  91429. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91430. }
  91431. else {
  91432. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91433. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91434. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91435. }
  91436. if (defines.REFLECTIONFRESNEL) {
  91437. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91438. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91439. }
  91440. }
  91441. }
  91442. // Clip plane
  91443. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91444. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91445. }
  91446. if (mustRebind || !this.isFrozen) {
  91447. if (scene.lightsEnabled) {
  91448. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91449. }
  91450. // View
  91451. this.bindView(effect);
  91452. // Fog
  91453. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91454. // image processing
  91455. this._imageProcessingConfiguration.bind(this._activeEffect);
  91456. }
  91457. this._uniformBuffer.update();
  91458. this._afterBind(mesh);
  91459. };
  91460. /**
  91461. * Dispose the material.
  91462. * @param forceDisposeEffect Force disposal of the associated effect.
  91463. * @param forceDisposeTextures Force disposal of the associated textures.
  91464. */
  91465. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91466. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91467. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91468. if (forceDisposeTextures) {
  91469. if (this.diffuseTexture) {
  91470. this.diffuseTexture.dispose();
  91471. }
  91472. if (this.reflectionTexture) {
  91473. this.reflectionTexture.dispose();
  91474. }
  91475. }
  91476. this._renderTargets.dispose();
  91477. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91478. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91479. }
  91480. _super.prototype.dispose.call(this, forceDisposeEffect);
  91481. };
  91482. /**
  91483. * Clones the material.
  91484. * @param name The cloned name.
  91485. * @returns The cloned material.
  91486. */
  91487. BackgroundMaterial.prototype.clone = function (name) {
  91488. var _this = this;
  91489. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91490. };
  91491. /**
  91492. * Serializes the current material to its JSON representation.
  91493. * @returns The JSON representation.
  91494. */
  91495. BackgroundMaterial.prototype.serialize = function () {
  91496. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91497. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91498. return serializationObject;
  91499. };
  91500. /**
  91501. * Gets the class name of the material
  91502. * @returns "BackgroundMaterial"
  91503. */
  91504. BackgroundMaterial.prototype.getClassName = function () {
  91505. return "BackgroundMaterial";
  91506. };
  91507. /**
  91508. * Parse a JSON input to create back a background material.
  91509. * @param source The JSON data to parse
  91510. * @param scene The scene to create the parsed material in
  91511. * @param rootUrl The root url of the assets the material depends upon
  91512. * @returns the instantiated BackgroundMaterial.
  91513. */
  91514. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91515. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91516. };
  91517. /**
  91518. * Standard reflectance value at parallel view angle.
  91519. */
  91520. BackgroundMaterial.StandardReflectance0 = 0.05;
  91521. /**
  91522. * Standard reflectance value at grazing angle.
  91523. */
  91524. BackgroundMaterial.StandardReflectance90 = 0.5;
  91525. __decorate([
  91526. BABYLON.serializeAsColor3()
  91527. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91528. __decorate([
  91529. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91530. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91531. __decorate([
  91532. BABYLON.serialize()
  91533. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91534. __decorate([
  91535. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91536. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91537. __decorate([
  91538. BABYLON.serializeAsColor3()
  91539. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91540. __decorate([
  91541. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91542. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91543. __decorate([
  91544. BABYLON.serialize()
  91545. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91546. __decorate([
  91547. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91548. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91549. __decorate([
  91550. BABYLON.serializeAsColor3()
  91551. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91552. __decorate([
  91553. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91554. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91555. __decorate([
  91556. BABYLON.serialize()
  91557. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91558. __decorate([
  91559. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91560. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91561. __decorate([
  91562. BABYLON.serializeAsTexture()
  91563. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91564. __decorate([
  91565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91566. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91567. __decorate([
  91568. BABYLON.serialize()
  91569. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91570. __decorate([
  91571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91572. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91573. __decorate([
  91574. BABYLON.serializeAsTexture()
  91575. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91576. __decorate([
  91577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91578. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91579. __decorate([
  91580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91581. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91582. __decorate([
  91583. BABYLON.serialize()
  91584. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91585. __decorate([
  91586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91587. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91588. __decorate([
  91589. BABYLON.serialize()
  91590. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91591. __decorate([
  91592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91593. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91594. __decorate([
  91595. BABYLON.serializeAsVector3()
  91596. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91597. __decorate([
  91598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91599. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91600. __decorate([
  91601. BABYLON.serialize()
  91602. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91603. __decorate([
  91604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91605. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91606. __decorate([
  91607. BABYLON.serialize()
  91608. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91609. __decorate([
  91610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91611. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91612. __decorate([
  91613. BABYLON.serialize()
  91614. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91615. __decorate([
  91616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91617. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91618. __decorate([
  91619. BABYLON.serialize()
  91620. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91621. __decorate([
  91622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91623. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91624. __decorate([
  91625. BABYLON.serialize()
  91626. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91627. __decorate([
  91628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91629. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91630. __decorate([
  91631. BABYLON.serialize()
  91632. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91633. __decorate([
  91634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91635. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91636. __decorate([
  91637. BABYLON.serialize()
  91638. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91639. __decorate([
  91640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91641. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91642. __decorate([
  91643. BABYLON.serialize()
  91644. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91645. __decorate([
  91646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91647. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91648. __decorate([
  91649. BABYLON.serialize()
  91650. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91651. __decorate([
  91652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91653. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91654. __decorate([
  91655. BABYLON.serializeAsImageProcessingConfiguration()
  91656. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91657. return BackgroundMaterial;
  91658. }(BABYLON.PushMaterial));
  91659. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91660. })(BABYLON || (BABYLON = {}));
  91661. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91662. "use strict";
  91663. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91664. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91665. s = arguments[i];
  91666. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91667. t[p] = s[p];
  91668. }
  91669. return t;
  91670. };
  91671. var BABYLON;
  91672. (function (BABYLON) {
  91673. /**
  91674. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91675. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91676. * It also helps with the default setup of your imageProcessing configuration.
  91677. */
  91678. var EnvironmentHelper = /** @class */ (function () {
  91679. /**
  91680. * constructor
  91681. * @param options
  91682. * @param scene The scene to add the material to
  91683. */
  91684. function EnvironmentHelper(options, scene) {
  91685. var _this = this;
  91686. this._errorHandler = function (message, exception) {
  91687. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91688. };
  91689. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91690. this._scene = scene;
  91691. this.onErrorObservable = new BABYLON.Observable();
  91692. this._setupBackground();
  91693. this._setupImageProcessing();
  91694. }
  91695. /**
  91696. * Creates the default options for the helper.
  91697. */
  91698. EnvironmentHelper._getDefaultOptions = function () {
  91699. return {
  91700. createGround: true,
  91701. groundSize: 15,
  91702. groundTexture: this._groundTextureCDNUrl,
  91703. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91704. groundOpacity: 0.9,
  91705. enableGroundShadow: true,
  91706. groundShadowLevel: 0.5,
  91707. enableGroundMirror: false,
  91708. groundMirrorSizeRatio: 0.3,
  91709. groundMirrorBlurKernel: 64,
  91710. groundMirrorAmount: 1,
  91711. groundMirrorFresnelWeight: 1,
  91712. groundMirrorFallOffDistance: 0,
  91713. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91714. groundYBias: 0.00001,
  91715. createSkybox: true,
  91716. skyboxSize: 20,
  91717. skyboxTexture: this._skyboxTextureCDNUrl,
  91718. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91719. backgroundYRotation: 0,
  91720. sizeAuto: true,
  91721. rootPosition: BABYLON.Vector3.Zero(),
  91722. setupImageProcessing: true,
  91723. environmentTexture: this._environmentTextureCDNUrl,
  91724. cameraExposure: 0.8,
  91725. cameraContrast: 1.2,
  91726. toneMappingEnabled: true,
  91727. };
  91728. };
  91729. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91730. /**
  91731. * Gets the root mesh created by the helper.
  91732. */
  91733. get: function () {
  91734. return this._rootMesh;
  91735. },
  91736. enumerable: true,
  91737. configurable: true
  91738. });
  91739. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91740. /**
  91741. * Gets the skybox created by the helper.
  91742. */
  91743. get: function () {
  91744. return this._skybox;
  91745. },
  91746. enumerable: true,
  91747. configurable: true
  91748. });
  91749. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91750. /**
  91751. * Gets the skybox texture created by the helper.
  91752. */
  91753. get: function () {
  91754. return this._skyboxTexture;
  91755. },
  91756. enumerable: true,
  91757. configurable: true
  91758. });
  91759. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91760. /**
  91761. * Gets the skybox material created by the helper.
  91762. */
  91763. get: function () {
  91764. return this._skyboxMaterial;
  91765. },
  91766. enumerable: true,
  91767. configurable: true
  91768. });
  91769. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91770. /**
  91771. * Gets the ground mesh created by the helper.
  91772. */
  91773. get: function () {
  91774. return this._ground;
  91775. },
  91776. enumerable: true,
  91777. configurable: true
  91778. });
  91779. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91780. /**
  91781. * Gets the ground texture created by the helper.
  91782. */
  91783. get: function () {
  91784. return this._groundTexture;
  91785. },
  91786. enumerable: true,
  91787. configurable: true
  91788. });
  91789. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91790. /**
  91791. * Gets the ground mirror created by the helper.
  91792. */
  91793. get: function () {
  91794. return this._groundMirror;
  91795. },
  91796. enumerable: true,
  91797. configurable: true
  91798. });
  91799. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91800. /**
  91801. * Gets the ground mirror render list to helps pushing the meshes
  91802. * you wish in the ground reflection.
  91803. */
  91804. get: function () {
  91805. if (this._groundMirror) {
  91806. return this._groundMirror.renderList;
  91807. }
  91808. return null;
  91809. },
  91810. enumerable: true,
  91811. configurable: true
  91812. });
  91813. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91814. /**
  91815. * Gets the ground material created by the helper.
  91816. */
  91817. get: function () {
  91818. return this._groundMaterial;
  91819. },
  91820. enumerable: true,
  91821. configurable: true
  91822. });
  91823. /**
  91824. * Updates the background according to the new options
  91825. * @param options
  91826. */
  91827. EnvironmentHelper.prototype.updateOptions = function (options) {
  91828. var newOptions = __assign({}, this._options, options);
  91829. if (this._ground && !newOptions.createGround) {
  91830. this._ground.dispose();
  91831. this._ground = null;
  91832. }
  91833. if (this._groundMaterial && !newOptions.createGround) {
  91834. this._groundMaterial.dispose();
  91835. this._groundMaterial = null;
  91836. }
  91837. if (this._groundTexture) {
  91838. if (this._options.groundTexture != newOptions.groundTexture) {
  91839. this._groundTexture.dispose();
  91840. this._groundTexture = null;
  91841. }
  91842. }
  91843. if (this._skybox && !newOptions.createSkybox) {
  91844. this._skybox.dispose();
  91845. this._skybox = null;
  91846. }
  91847. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91848. this._skyboxMaterial.dispose();
  91849. this._skyboxMaterial = null;
  91850. }
  91851. if (this._skyboxTexture) {
  91852. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91853. this._skyboxTexture.dispose();
  91854. this._skyboxTexture = null;
  91855. }
  91856. }
  91857. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91858. this._groundMirror.dispose();
  91859. this._groundMirror = null;
  91860. }
  91861. if (this._scene.environmentTexture) {
  91862. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91863. this._scene.environmentTexture.dispose();
  91864. }
  91865. }
  91866. this._options = newOptions;
  91867. this._setupBackground();
  91868. this._setupImageProcessing();
  91869. };
  91870. /**
  91871. * Sets the primary color of all the available elements.
  91872. * @param color
  91873. */
  91874. EnvironmentHelper.prototype.setMainColor = function (color) {
  91875. if (this.groundMaterial) {
  91876. this.groundMaterial.primaryColor = color;
  91877. }
  91878. if (this.skyboxMaterial) {
  91879. this.skyboxMaterial.primaryColor = color;
  91880. }
  91881. if (this.groundMirror) {
  91882. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91883. }
  91884. };
  91885. /**
  91886. * Setup the image processing according to the specified options.
  91887. */
  91888. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91889. if (this._options.setupImageProcessing) {
  91890. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91891. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91892. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91893. this._setupEnvironmentTexture();
  91894. }
  91895. };
  91896. /**
  91897. * Setup the environment texture according to the specified options.
  91898. */
  91899. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91900. if (this._scene.environmentTexture) {
  91901. return;
  91902. }
  91903. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91904. this._scene.environmentTexture = this._options.environmentTexture;
  91905. return;
  91906. }
  91907. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91908. this._scene.environmentTexture = environmentTexture;
  91909. };
  91910. /**
  91911. * Setup the background according to the specified options.
  91912. */
  91913. EnvironmentHelper.prototype._setupBackground = function () {
  91914. if (!this._rootMesh) {
  91915. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91916. }
  91917. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91918. var sceneSize = this._getSceneSize();
  91919. if (this._options.createGround) {
  91920. this._setupGround(sceneSize);
  91921. this._setupGroundMaterial();
  91922. this._setupGroundDiffuseTexture();
  91923. if (this._options.enableGroundMirror) {
  91924. this._setupGroundMirrorTexture(sceneSize);
  91925. }
  91926. this._setupMirrorInGroundMaterial();
  91927. }
  91928. if (this._options.createSkybox) {
  91929. this._setupSkybox(sceneSize);
  91930. this._setupSkyboxMaterial();
  91931. this._setupSkyboxReflectionTexture();
  91932. }
  91933. this._rootMesh.position.x = sceneSize.rootPosition.x;
  91934. this._rootMesh.position.z = sceneSize.rootPosition.z;
  91935. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91936. };
  91937. /**
  91938. * Get the scene sizes according to the setup.
  91939. */
  91940. EnvironmentHelper.prototype._getSceneSize = function () {
  91941. var _this = this;
  91942. var groundSize = this._options.groundSize;
  91943. var skyboxSize = this._options.skyboxSize;
  91944. var rootPosition = this._options.rootPosition;
  91945. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91946. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91947. }
  91948. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91949. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91950. });
  91951. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91952. if (this._options.sizeAuto) {
  91953. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91954. this._scene.activeCamera.upperRadiusLimit) {
  91955. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91956. skyboxSize = groundSize;
  91957. }
  91958. var sceneDiagonalLenght = sceneDiagonal.length();
  91959. if (sceneDiagonalLenght > groundSize) {
  91960. groundSize = sceneDiagonalLenght * 2;
  91961. skyboxSize = groundSize;
  91962. }
  91963. // 10 % bigger.
  91964. groundSize *= 1.1;
  91965. skyboxSize *= 1.5;
  91966. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91967. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91968. }
  91969. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91970. };
  91971. /**
  91972. * Setup the ground according to the specified options.
  91973. */
  91974. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91975. var _this = this;
  91976. if (!this._ground) {
  91977. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91978. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91979. this._ground.parent = this._rootMesh;
  91980. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91981. }
  91982. this._ground.receiveShadows = this._options.enableGroundShadow;
  91983. };
  91984. /**
  91985. * Setup the ground material according to the specified options.
  91986. */
  91987. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91988. if (!this._groundMaterial) {
  91989. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91990. }
  91991. this._groundMaterial.alpha = this._options.groundOpacity;
  91992. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  91993. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  91994. this._groundMaterial.primaryLevel = 1;
  91995. this._groundMaterial.primaryColor = this._options.groundColor;
  91996. this._groundMaterial.secondaryLevel = 0;
  91997. this._groundMaterial.tertiaryLevel = 0;
  91998. this._groundMaterial.useRGBColor = false;
  91999. this._groundMaterial.enableNoise = true;
  92000. if (this._ground) {
  92001. this._ground.material = this._groundMaterial;
  92002. }
  92003. };
  92004. /**
  92005. * Setup the ground diffuse texture according to the specified options.
  92006. */
  92007. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92008. if (!this._groundMaterial) {
  92009. return;
  92010. }
  92011. if (this._groundTexture) {
  92012. return;
  92013. }
  92014. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92015. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92016. return;
  92017. }
  92018. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92019. diffuseTexture.gammaSpace = false;
  92020. diffuseTexture.hasAlpha = true;
  92021. this._groundMaterial.diffuseTexture = diffuseTexture;
  92022. };
  92023. /**
  92024. * Setup the ground mirror texture according to the specified options.
  92025. */
  92026. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92027. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92028. if (!this._groundMirror) {
  92029. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92030. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92031. this._groundMirror.anisotropicFilteringLevel = 1;
  92032. this._groundMirror.wrapU = wrapping;
  92033. this._groundMirror.wrapV = wrapping;
  92034. this._groundMirror.gammaSpace = false;
  92035. if (this._groundMirror.renderList) {
  92036. for (var i = 0; i < this._scene.meshes.length; i++) {
  92037. var mesh = this._scene.meshes[i];
  92038. if (mesh !== this._ground &&
  92039. mesh !== this._skybox &&
  92040. mesh !== this._rootMesh) {
  92041. this._groundMirror.renderList.push(mesh);
  92042. }
  92043. }
  92044. }
  92045. }
  92046. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92047. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92048. };
  92049. /**
  92050. * Setup the ground to receive the mirror texture.
  92051. */
  92052. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92053. if (this._groundMaterial) {
  92054. this._groundMaterial.reflectionTexture = this._groundMirror;
  92055. this._groundMaterial.reflectionFresnel = true;
  92056. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92057. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92058. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92059. }
  92060. };
  92061. /**
  92062. * Setup the skybox according to the specified options.
  92063. */
  92064. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92065. var _this = this;
  92066. if (!this._skybox) {
  92067. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92068. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92069. }
  92070. this._skybox.parent = this._rootMesh;
  92071. };
  92072. /**
  92073. * Setup the skybox material according to the specified options.
  92074. */
  92075. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92076. if (!this._skybox) {
  92077. return;
  92078. }
  92079. if (!this._skyboxMaterial) {
  92080. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92081. }
  92082. this._skyboxMaterial.useRGBColor = false;
  92083. this._skyboxMaterial.primaryLevel = 1;
  92084. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92085. this._skyboxMaterial.secondaryLevel = 0;
  92086. this._skyboxMaterial.tertiaryLevel = 0;
  92087. this._skyboxMaterial.enableNoise = true;
  92088. this._skybox.material = this._skyboxMaterial;
  92089. };
  92090. /**
  92091. * Setup the skybox reflection texture according to the specified options.
  92092. */
  92093. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92094. if (!this._skyboxMaterial) {
  92095. return;
  92096. }
  92097. if (this._skyboxTexture) {
  92098. return;
  92099. }
  92100. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92101. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92102. return;
  92103. }
  92104. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92105. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92106. this._skyboxTexture.gammaSpace = false;
  92107. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92108. };
  92109. /**
  92110. * Dispose all the elements created by the Helper.
  92111. */
  92112. EnvironmentHelper.prototype.dispose = function () {
  92113. if (this._groundMaterial) {
  92114. this._groundMaterial.dispose(true, true);
  92115. }
  92116. if (this._skyboxMaterial) {
  92117. this._skyboxMaterial.dispose(true, true);
  92118. }
  92119. this._rootMesh.dispose(false);
  92120. };
  92121. /**
  92122. * Default ground texture URL.
  92123. */
  92124. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92125. /**
  92126. * Default skybox texture URL.
  92127. */
  92128. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92129. /**
  92130. * Default environment texture URL.
  92131. */
  92132. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92133. return EnvironmentHelper;
  92134. }());
  92135. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92136. })(BABYLON || (BABYLON = {}));
  92137. //# sourceMappingURL=babylon.environmentHelper.js.map
  92138. "use strict";
  92139. var BABYLON;
  92140. (function (BABYLON) {
  92141. /**
  92142. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92143. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92144. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92145. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92146. */
  92147. var VideoDome = /** @class */ (function (_super) {
  92148. __extends(VideoDome, _super);
  92149. /**
  92150. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92151. * @param name Element's name, child elements will append suffixes for their own names.
  92152. * @param urlsOrVideo
  92153. * @param options An object containing optional or exposed sub element properties:
  92154. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92155. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92156. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92157. * @param options **loop=true** Automatically loop video on end.
  92158. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92159. */
  92160. function VideoDome(name, urlsOrVideo, options, scene) {
  92161. var _this = _super.call(this, name, scene) || this;
  92162. // set defaults and manage values
  92163. name = name || "videoDome";
  92164. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92165. options.clickToPlay = Boolean(options.clickToPlay);
  92166. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92167. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92168. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92169. // create
  92170. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92171. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92172. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92173. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92174. flat: false,
  92175. radius: options.size,
  92176. subdivisions: options.resolution,
  92177. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92178. }, scene);
  92179. // configure material
  92180. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92181. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92182. material.reflectionTexture = _this._videoTexture;
  92183. material.useEquirectangularFOV = true;
  92184. material.fovMultiplier = 1.0;
  92185. // configure mesh
  92186. _this._mesh.material = material;
  92187. _this._mesh.parent = _this;
  92188. // optional configuration
  92189. if (options.clickToPlay) {
  92190. scene.onPointerUp = function () {
  92191. _this._videoTexture.video.play();
  92192. };
  92193. }
  92194. return _this;
  92195. }
  92196. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92197. /**
  92198. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92199. * Also see the options.resolution property.
  92200. */
  92201. get: function () {
  92202. return this._material.fovMultiplier;
  92203. },
  92204. set: function (value) {
  92205. this._material.fovMultiplier = value;
  92206. },
  92207. enumerable: true,
  92208. configurable: true
  92209. });
  92210. /**
  92211. * Releases resources associated with this node.
  92212. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92213. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92214. */
  92215. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92216. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92217. this._videoTexture.dispose();
  92218. this._mesh.dispose();
  92219. this._material.dispose();
  92220. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92221. };
  92222. return VideoDome;
  92223. }(BABYLON.Node));
  92224. BABYLON.VideoDome = VideoDome;
  92225. })(BABYLON || (BABYLON = {}));
  92226. //# sourceMappingURL=babylon.videoDome.js.map
  92227. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","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}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\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}","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#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  92228. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92229. globalObject["BABYLON"] = BABYLON;
  92230. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var VideoDome = BABYLON.VideoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  92231. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };