es6.js 4.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587
  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. case 11:// Camera reference
  7063. destination[property] = sourceProperty;
  7064. break;
  7065. case 1:// Texture
  7066. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7067. break;
  7068. case 2: // Color3
  7069. case 3: // FresnelParameters
  7070. case 4: // Vector2
  7071. case 5: // Vector3
  7072. case 7: // Color Curves
  7073. case 10:// Quaternion
  7074. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7075. break;
  7076. }
  7077. }
  7078. }
  7079. return destination;
  7080. };
  7081. function getDirectStore(target) {
  7082. var classKey = target.getClassName();
  7083. if (!__decoratorInitialStore[classKey]) {
  7084. __decoratorInitialStore[classKey] = {};
  7085. }
  7086. return __decoratorInitialStore[classKey];
  7087. }
  7088. /**
  7089. * Return the list of properties flagged as serializable
  7090. * @param target: host object
  7091. */
  7092. function getMergedStore(target) {
  7093. var classKey = target.getClassName();
  7094. if (__mergedStore[classKey]) {
  7095. return __mergedStore[classKey];
  7096. }
  7097. __mergedStore[classKey] = {};
  7098. var store = __mergedStore[classKey];
  7099. var currentTarget = target;
  7100. var currentKey = classKey;
  7101. while (currentKey) {
  7102. var initialStore = __decoratorInitialStore[currentKey];
  7103. for (var property in initialStore) {
  7104. store[property] = initialStore[property];
  7105. }
  7106. var parent_1 = void 0;
  7107. var done = false;
  7108. do {
  7109. parent_1 = Object.getPrototypeOf(currentTarget);
  7110. if (!parent_1.getClassName) {
  7111. done = true;
  7112. break;
  7113. }
  7114. if (parent_1.getClassName() !== currentKey) {
  7115. break;
  7116. }
  7117. currentTarget = parent_1;
  7118. } while (parent_1);
  7119. if (done) {
  7120. break;
  7121. }
  7122. currentKey = parent_1.getClassName();
  7123. currentTarget = parent_1;
  7124. }
  7125. return store;
  7126. }
  7127. function generateSerializableMember(type, sourceName) {
  7128. return function (target, propertyKey) {
  7129. var classStore = getDirectStore(target);
  7130. if (!classStore[propertyKey]) {
  7131. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7132. }
  7133. };
  7134. }
  7135. function generateExpandMember(setCallback, targetKey) {
  7136. if (targetKey === void 0) { targetKey = null; }
  7137. return function (target, propertyKey) {
  7138. var key = targetKey || ("_" + propertyKey);
  7139. Object.defineProperty(target, propertyKey, {
  7140. get: function () {
  7141. return this[key];
  7142. },
  7143. set: function (value) {
  7144. if (this[key] === value) {
  7145. return;
  7146. }
  7147. this[key] = value;
  7148. target[setCallback].apply(this);
  7149. },
  7150. enumerable: true,
  7151. configurable: true
  7152. });
  7153. };
  7154. }
  7155. function expandToProperty(callback, targetKey) {
  7156. if (targetKey === void 0) { targetKey = null; }
  7157. return generateExpandMember(callback, targetKey);
  7158. }
  7159. BABYLON.expandToProperty = expandToProperty;
  7160. function serialize(sourceName) {
  7161. return generateSerializableMember(0, sourceName); // value member
  7162. }
  7163. BABYLON.serialize = serialize;
  7164. function serializeAsTexture(sourceName) {
  7165. return generateSerializableMember(1, sourceName); // texture member
  7166. }
  7167. BABYLON.serializeAsTexture = serializeAsTexture;
  7168. function serializeAsColor3(sourceName) {
  7169. return generateSerializableMember(2, sourceName); // color3 member
  7170. }
  7171. BABYLON.serializeAsColor3 = serializeAsColor3;
  7172. function serializeAsFresnelParameters(sourceName) {
  7173. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7174. }
  7175. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7176. function serializeAsVector2(sourceName) {
  7177. return generateSerializableMember(4, sourceName); // vector2 member
  7178. }
  7179. BABYLON.serializeAsVector2 = serializeAsVector2;
  7180. function serializeAsVector3(sourceName) {
  7181. return generateSerializableMember(5, sourceName); // vector3 member
  7182. }
  7183. BABYLON.serializeAsVector3 = serializeAsVector3;
  7184. function serializeAsMeshReference(sourceName) {
  7185. return generateSerializableMember(6, sourceName); // mesh reference member
  7186. }
  7187. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7188. function serializeAsColorCurves(sourceName) {
  7189. return generateSerializableMember(7, sourceName); // color curves
  7190. }
  7191. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7192. function serializeAsColor4(sourceName) {
  7193. return generateSerializableMember(8, sourceName); // color 4
  7194. }
  7195. BABYLON.serializeAsColor4 = serializeAsColor4;
  7196. function serializeAsImageProcessingConfiguration(sourceName) {
  7197. return generateSerializableMember(9, sourceName); // image processing
  7198. }
  7199. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7200. function serializeAsQuaternion(sourceName) {
  7201. return generateSerializableMember(10, sourceName); // quaternion member
  7202. }
  7203. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7204. /**
  7205. * Decorator used to define property that can be serialized as reference to a camera
  7206. * @param sourceName defines the name of the property to decorate
  7207. */
  7208. function serializeAsCameraReference(sourceName) {
  7209. return generateSerializableMember(11, sourceName); // camera reference member
  7210. }
  7211. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7212. var SerializationHelper = /** @class */ (function () {
  7213. function SerializationHelper() {
  7214. }
  7215. SerializationHelper.Serialize = function (entity, serializationObject) {
  7216. if (!serializationObject) {
  7217. serializationObject = {};
  7218. }
  7219. // Tags
  7220. if (BABYLON.Tags) {
  7221. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7222. }
  7223. var serializedProperties = getMergedStore(entity);
  7224. // Properties
  7225. for (var property in serializedProperties) {
  7226. var propertyDescriptor = serializedProperties[property];
  7227. var targetPropertyName = propertyDescriptor.sourceName || property;
  7228. var propertyType = propertyDescriptor.type;
  7229. var sourceProperty = entity[property];
  7230. if (sourceProperty !== undefined && sourceProperty !== null) {
  7231. switch (propertyType) {
  7232. case 0:// Value
  7233. serializationObject[targetPropertyName] = sourceProperty;
  7234. break;
  7235. case 1:// Texture
  7236. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7237. break;
  7238. case 2:// Color3
  7239. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7240. break;
  7241. case 3:// FresnelParameters
  7242. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7243. break;
  7244. case 4:// Vector2
  7245. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7246. break;
  7247. case 5:// Vector3
  7248. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7249. break;
  7250. case 6:// Mesh reference
  7251. serializationObject[targetPropertyName] = sourceProperty.id;
  7252. break;
  7253. case 7:// Color Curves
  7254. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7255. break;
  7256. case 8:// Color 4
  7257. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7258. break;
  7259. case 9:// Image Processing
  7260. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7261. break;
  7262. case 10:// Quaternion
  7263. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7264. break;
  7265. case 11:// Camera reference
  7266. serializationObject[targetPropertyName] = sourceProperty.id;
  7267. break;
  7268. }
  7269. }
  7270. }
  7271. return serializationObject;
  7272. };
  7273. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7274. if (rootUrl === void 0) { rootUrl = null; }
  7275. var destination = creationFunction();
  7276. if (!rootUrl) {
  7277. rootUrl = "";
  7278. }
  7279. // Tags
  7280. if (BABYLON.Tags) {
  7281. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7282. }
  7283. var classStore = getMergedStore(destination);
  7284. // Properties
  7285. for (var property in classStore) {
  7286. var propertyDescriptor = classStore[property];
  7287. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7288. var propertyType = propertyDescriptor.type;
  7289. if (sourceProperty !== undefined && sourceProperty !== null) {
  7290. var dest = destination;
  7291. switch (propertyType) {
  7292. case 0:// Value
  7293. dest[property] = sourceProperty;
  7294. break;
  7295. case 1:// Texture
  7296. if (scene) {
  7297. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7298. }
  7299. break;
  7300. case 2:// Color3
  7301. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7302. break;
  7303. case 3:// FresnelParameters
  7304. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7305. break;
  7306. case 4:// Vector2
  7307. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7308. break;
  7309. case 5:// Vector3
  7310. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7311. break;
  7312. case 6:// Mesh reference
  7313. if (scene) {
  7314. dest[property] = scene.getLastMeshByID(sourceProperty);
  7315. }
  7316. break;
  7317. case 7:// Color Curves
  7318. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7319. break;
  7320. case 8:// Color 4
  7321. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7322. break;
  7323. case 9:// Image Processing
  7324. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7325. break;
  7326. case 10:// Quaternion
  7327. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7328. break;
  7329. case 11:// Camera reference
  7330. if (scene) {
  7331. dest[property] = scene.getCameraByID(sourceProperty);
  7332. }
  7333. break;
  7334. }
  7335. }
  7336. }
  7337. return destination;
  7338. };
  7339. SerializationHelper.Clone = function (creationFunction, source) {
  7340. return _copySource(creationFunction, source, false);
  7341. };
  7342. SerializationHelper.Instanciate = function (creationFunction, source) {
  7343. return _copySource(creationFunction, source, true);
  7344. };
  7345. return SerializationHelper;
  7346. }());
  7347. BABYLON.SerializationHelper = SerializationHelper;
  7348. })(BABYLON || (BABYLON = {}));
  7349. //# sourceMappingURL=babylon.decorators.js.map
  7350. "use strict";
  7351. var BABYLON;
  7352. (function (BABYLON) {
  7353. /**
  7354. * Wrapper class for promise with external resolve and reject.
  7355. */
  7356. var Deferred = /** @class */ (function () {
  7357. /**
  7358. * Constructor for this deferred object.
  7359. */
  7360. function Deferred() {
  7361. var _this = this;
  7362. this.promise = new Promise(function (resolve, reject) {
  7363. _this._resolve = resolve;
  7364. _this._reject = reject;
  7365. });
  7366. }
  7367. Object.defineProperty(Deferred.prototype, "resolve", {
  7368. /**
  7369. * The resolve method of the promise associated with this deferred object.
  7370. */
  7371. get: function () {
  7372. return this._resolve;
  7373. },
  7374. enumerable: true,
  7375. configurable: true
  7376. });
  7377. Object.defineProperty(Deferred.prototype, "reject", {
  7378. /**
  7379. * The reject method of the promise associated with this deferred object.
  7380. */
  7381. get: function () {
  7382. return this._reject;
  7383. },
  7384. enumerable: true,
  7385. configurable: true
  7386. });
  7387. return Deferred;
  7388. }());
  7389. BABYLON.Deferred = Deferred;
  7390. })(BABYLON || (BABYLON = {}));
  7391. //# sourceMappingURL=babylon.deferred.js.map
  7392. "use strict";
  7393. var BABYLON;
  7394. (function (BABYLON) {
  7395. /**
  7396. * A class serves as a medium between the observable and its observers
  7397. */
  7398. var EventState = /** @class */ (function () {
  7399. /**
  7400. * Create a new EventState
  7401. * @param mask defines the mask associated with this state
  7402. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7403. * @param target defines the original target of the state
  7404. * @param currentTarget defines the current target of the state
  7405. */
  7406. function EventState(mask, skipNextObservers, target, currentTarget) {
  7407. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7408. this.initalize(mask, skipNextObservers, target, currentTarget);
  7409. }
  7410. /**
  7411. * Initialize the current event state
  7412. * @param mask defines the mask associated with this state
  7413. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7414. * @param target defines the original target of the state
  7415. * @param currentTarget defines the current target of the state
  7416. * @returns the current event state
  7417. */
  7418. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7419. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7420. this.mask = mask;
  7421. this.skipNextObservers = skipNextObservers;
  7422. this.target = target;
  7423. this.currentTarget = currentTarget;
  7424. return this;
  7425. };
  7426. return EventState;
  7427. }());
  7428. BABYLON.EventState = EventState;
  7429. /**
  7430. * Represent an Observer registered to a given Observable object.
  7431. */
  7432. var Observer = /** @class */ (function () {
  7433. /**
  7434. * Creates a new observer
  7435. * @param callback defines the callback to call when the observer is notified
  7436. * @param mask defines the mask of the observer (used to filter notifications)
  7437. * @param scope defines the current scope used to restore the JS context
  7438. */
  7439. function Observer(
  7440. /**
  7441. * Defines the callback to call when the observer is notified
  7442. */
  7443. callback,
  7444. /**
  7445. * Defines the mask of the observer (used to filter notifications)
  7446. */
  7447. mask,
  7448. /**
  7449. * Defines the current scope used to restore the JS context
  7450. */
  7451. scope) {
  7452. if (scope === void 0) { scope = null; }
  7453. this.callback = callback;
  7454. this.mask = mask;
  7455. this.scope = scope;
  7456. /** @ignore */
  7457. this._willBeUnregistered = false;
  7458. /**
  7459. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7460. */
  7461. this.unregisterOnNextCall = false;
  7462. }
  7463. return Observer;
  7464. }());
  7465. BABYLON.Observer = Observer;
  7466. /**
  7467. * Represent a list of observers registered to multiple Observables object.
  7468. */
  7469. var MultiObserver = /** @class */ (function () {
  7470. function MultiObserver() {
  7471. }
  7472. /**
  7473. * Release associated resources
  7474. */
  7475. MultiObserver.prototype.dispose = function () {
  7476. if (this._observers && this._observables) {
  7477. for (var index = 0; index < this._observers.length; index++) {
  7478. this._observables[index].remove(this._observers[index]);
  7479. }
  7480. }
  7481. this._observers = null;
  7482. this._observables = null;
  7483. };
  7484. /**
  7485. * Raise a callback when one of the observable will notify
  7486. * @param observables defines a list of observables to watch
  7487. * @param callback defines the callback to call on notification
  7488. * @param mask defines the mask used to filter notifications
  7489. * @param scope defines the current scope used to restore the JS context
  7490. * @returns the new MultiObserver
  7491. */
  7492. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7493. if (mask === void 0) { mask = -1; }
  7494. if (scope === void 0) { scope = null; }
  7495. var result = new MultiObserver();
  7496. result._observers = new Array();
  7497. result._observables = observables;
  7498. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7499. var observable = observables_1[_i];
  7500. var observer = observable.add(callback, mask, false, scope);
  7501. if (observer) {
  7502. result._observers.push(observer);
  7503. }
  7504. }
  7505. return result;
  7506. };
  7507. return MultiObserver;
  7508. }());
  7509. BABYLON.MultiObserver = MultiObserver;
  7510. /**
  7511. * The Observable class is a simple implementation of the Observable pattern.
  7512. *
  7513. * 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.
  7514. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7515. * 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).
  7516. * 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.
  7517. */
  7518. var Observable = /** @class */ (function () {
  7519. /**
  7520. * Creates a new observable
  7521. * @param onObserverAdded defines a callback to call when a new observer is added
  7522. */
  7523. function Observable(onObserverAdded) {
  7524. this._observers = new Array();
  7525. this._eventState = new EventState(0);
  7526. if (onObserverAdded) {
  7527. this._onObserverAdded = onObserverAdded;
  7528. }
  7529. }
  7530. /**
  7531. * Create a new Observer with the specified callback
  7532. * @param callback the callback that will be executed for that Observer
  7533. * @param mask the mask used to filter observers
  7534. * @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.
  7535. * @param scope optional scope for the callback to be called from
  7536. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7537. * @returns the new observer created for the callback
  7538. */
  7539. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7540. if (mask === void 0) { mask = -1; }
  7541. if (insertFirst === void 0) { insertFirst = false; }
  7542. if (scope === void 0) { scope = null; }
  7543. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7544. if (!callback) {
  7545. return null;
  7546. }
  7547. var observer = new Observer(callback, mask, scope);
  7548. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7549. if (insertFirst) {
  7550. this._observers.unshift(observer);
  7551. }
  7552. else {
  7553. this._observers.push(observer);
  7554. }
  7555. if (this._onObserverAdded) {
  7556. this._onObserverAdded(observer);
  7557. }
  7558. return observer;
  7559. };
  7560. /**
  7561. * Remove an Observer from the Observable object
  7562. * @param observer the instance of the Observer to remove
  7563. * @returns false if it doesn't belong to this Observable
  7564. */
  7565. Observable.prototype.remove = function (observer) {
  7566. if (!observer) {
  7567. return false;
  7568. }
  7569. var index = this._observers.indexOf(observer);
  7570. if (index !== -1) {
  7571. this._observers.splice(index, 1);
  7572. return true;
  7573. }
  7574. return false;
  7575. };
  7576. /**
  7577. * Remove a callback from the Observable object
  7578. * @param callback the callback to remove
  7579. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7580. * @returns false if it doesn't belong to this Observable
  7581. */
  7582. Observable.prototype.removeCallback = function (callback, scope) {
  7583. for (var index = 0; index < this._observers.length; index++) {
  7584. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7585. this._observers.splice(index, 1);
  7586. return true;
  7587. }
  7588. }
  7589. return false;
  7590. };
  7591. Observable.prototype._deferUnregister = function (observer) {
  7592. var _this = this;
  7593. observer.unregisterOnNextCall = false;
  7594. observer._willBeUnregistered = true;
  7595. BABYLON.Tools.SetImmediate(function () {
  7596. _this.remove(observer);
  7597. });
  7598. };
  7599. /**
  7600. * Notify all Observers by calling their respective callback with the given data
  7601. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7602. * @param eventData defines the data to send to all observers
  7603. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7604. * @param target defines the original target of the state
  7605. * @param currentTarget defines the current target of the state
  7606. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7607. */
  7608. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7609. if (mask === void 0) { mask = -1; }
  7610. if (!this._observers.length) {
  7611. return true;
  7612. }
  7613. var state = this._eventState;
  7614. state.mask = mask;
  7615. state.target = target;
  7616. state.currentTarget = currentTarget;
  7617. state.skipNextObservers = false;
  7618. state.lastReturnValue = eventData;
  7619. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7620. var obs = _a[_i];
  7621. if (obs._willBeUnregistered) {
  7622. continue;
  7623. }
  7624. if (obs.mask & mask) {
  7625. if (obs.scope) {
  7626. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7627. }
  7628. else {
  7629. state.lastReturnValue = obs.callback(eventData, state);
  7630. }
  7631. if (obs.unregisterOnNextCall) {
  7632. this._deferUnregister(obs);
  7633. }
  7634. }
  7635. if (state.skipNextObservers) {
  7636. return false;
  7637. }
  7638. }
  7639. return true;
  7640. };
  7641. /**
  7642. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7643. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7644. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7645. * and it is crucial that all callbacks will be executed.
  7646. * The order of the callbacks is kept, callbacks are not executed parallel.
  7647. *
  7648. * @param eventData The data to be sent to each callback
  7649. * @param mask is used to filter observers defaults to -1
  7650. * @param target defines the callback target (see EventState)
  7651. * @param currentTarget defines he current object in the bubbling phase
  7652. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7653. */
  7654. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7655. var _this = this;
  7656. if (mask === void 0) { mask = -1; }
  7657. // create an empty promise
  7658. var p = Promise.resolve(eventData);
  7659. // no observers? return this promise.
  7660. if (!this._observers.length) {
  7661. return p;
  7662. }
  7663. var state = this._eventState;
  7664. state.mask = mask;
  7665. state.target = target;
  7666. state.currentTarget = currentTarget;
  7667. state.skipNextObservers = false;
  7668. // execute one callback after another (not using Promise.all, the order is important)
  7669. this._observers.forEach(function (obs) {
  7670. if (state.skipNextObservers) {
  7671. return;
  7672. }
  7673. if (obs._willBeUnregistered) {
  7674. return;
  7675. }
  7676. if (obs.mask & mask) {
  7677. if (obs.scope) {
  7678. p = p.then(function (lastReturnedValue) {
  7679. state.lastReturnValue = lastReturnedValue;
  7680. return obs.callback.apply(obs.scope, [eventData, state]);
  7681. });
  7682. }
  7683. else {
  7684. p = p.then(function (lastReturnedValue) {
  7685. state.lastReturnValue = lastReturnedValue;
  7686. return obs.callback(eventData, state);
  7687. });
  7688. }
  7689. if (obs.unregisterOnNextCall) {
  7690. _this._deferUnregister(obs);
  7691. }
  7692. }
  7693. });
  7694. // return the eventData
  7695. return p.then(function () { return eventData; });
  7696. };
  7697. /**
  7698. * Notify a specific observer
  7699. * @param observer defines the observer to notify
  7700. * @param eventData defines the data to be sent to each callback
  7701. * @param mask is used to filter observers defaults to -1
  7702. */
  7703. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7704. if (mask === void 0) { mask = -1; }
  7705. var state = this._eventState;
  7706. state.mask = mask;
  7707. state.skipNextObservers = false;
  7708. observer.callback(eventData, state);
  7709. };
  7710. /**
  7711. * Gets a boolean indicating if the observable has at least one observer
  7712. * @returns true is the Observable has at least one Observer registered
  7713. */
  7714. Observable.prototype.hasObservers = function () {
  7715. return this._observers.length > 0;
  7716. };
  7717. /**
  7718. * Clear the list of observers
  7719. */
  7720. Observable.prototype.clear = function () {
  7721. this._observers = new Array();
  7722. this._onObserverAdded = null;
  7723. };
  7724. /**
  7725. * Clone the current observable
  7726. * @returns a new observable
  7727. */
  7728. Observable.prototype.clone = function () {
  7729. var result = new Observable();
  7730. result._observers = this._observers.slice(0);
  7731. return result;
  7732. };
  7733. /**
  7734. * Does this observable handles observer registered with a given mask
  7735. * @param mask defines the mask to be tested
  7736. * @return whether or not one observer registered with the given mask is handeled
  7737. **/
  7738. Observable.prototype.hasSpecificMask = function (mask) {
  7739. if (mask === void 0) { mask = -1; }
  7740. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7741. var obs = _a[_i];
  7742. if (obs.mask & mask || obs.mask === mask) {
  7743. return true;
  7744. }
  7745. }
  7746. return false;
  7747. };
  7748. return Observable;
  7749. }());
  7750. BABYLON.Observable = Observable;
  7751. })(BABYLON || (BABYLON = {}));
  7752. //# sourceMappingURL=babylon.observable.js.map
  7753. "use strict";
  7754. var BABYLON;
  7755. (function (BABYLON) {
  7756. var SmartArray = /** @class */ (function () {
  7757. function SmartArray(capacity) {
  7758. this.length = 0;
  7759. this.data = new Array(capacity);
  7760. this._id = SmartArray._GlobalId++;
  7761. }
  7762. SmartArray.prototype.push = function (value) {
  7763. this.data[this.length++] = value;
  7764. if (this.length > this.data.length) {
  7765. this.data.length *= 2;
  7766. }
  7767. };
  7768. SmartArray.prototype.forEach = function (func) {
  7769. for (var index = 0; index < this.length; index++) {
  7770. func(this.data[index]);
  7771. }
  7772. };
  7773. SmartArray.prototype.sort = function (compareFn) {
  7774. this.data.sort(compareFn);
  7775. };
  7776. SmartArray.prototype.reset = function () {
  7777. this.length = 0;
  7778. };
  7779. SmartArray.prototype.dispose = function () {
  7780. this.reset();
  7781. if (this.data) {
  7782. this.data.length = 0;
  7783. this.data = [];
  7784. }
  7785. };
  7786. SmartArray.prototype.concat = function (array) {
  7787. if (array.length === 0) {
  7788. return;
  7789. }
  7790. if (this.length + array.length > this.data.length) {
  7791. this.data.length = (this.length + array.length) * 2;
  7792. }
  7793. for (var index = 0; index < array.length; index++) {
  7794. this.data[this.length++] = (array.data || array)[index];
  7795. }
  7796. };
  7797. SmartArray.prototype.indexOf = function (value) {
  7798. var position = this.data.indexOf(value);
  7799. if (position >= this.length) {
  7800. return -1;
  7801. }
  7802. return position;
  7803. };
  7804. SmartArray.prototype.contains = function (value) {
  7805. return this.data.indexOf(value) !== -1;
  7806. };
  7807. // Statics
  7808. SmartArray._GlobalId = 0;
  7809. return SmartArray;
  7810. }());
  7811. BABYLON.SmartArray = SmartArray;
  7812. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7813. __extends(SmartArrayNoDuplicate, _super);
  7814. function SmartArrayNoDuplicate() {
  7815. var _this = _super !== null && _super.apply(this, arguments) || this;
  7816. _this._duplicateId = 0;
  7817. return _this;
  7818. }
  7819. SmartArrayNoDuplicate.prototype.push = function (value) {
  7820. _super.prototype.push.call(this, value);
  7821. if (!value.__smartArrayFlags) {
  7822. value.__smartArrayFlags = {};
  7823. }
  7824. value.__smartArrayFlags[this._id] = this._duplicateId;
  7825. };
  7826. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7827. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7828. return false;
  7829. }
  7830. this.push(value);
  7831. return true;
  7832. };
  7833. SmartArrayNoDuplicate.prototype.reset = function () {
  7834. _super.prototype.reset.call(this);
  7835. this._duplicateId++;
  7836. };
  7837. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7838. if (array.length === 0) {
  7839. return;
  7840. }
  7841. if (this.length + array.length > this.data.length) {
  7842. this.data.length = (this.length + array.length) * 2;
  7843. }
  7844. for (var index = 0; index < array.length; index++) {
  7845. var item = (array.data || array)[index];
  7846. this.pushNoDuplicate(item);
  7847. }
  7848. };
  7849. return SmartArrayNoDuplicate;
  7850. }(SmartArray));
  7851. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7852. })(BABYLON || (BABYLON = {}));
  7853. //# sourceMappingURL=babylon.smartArray.js.map
  7854. "use strict";
  7855. var BABYLON;
  7856. (function (BABYLON) {
  7857. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7858. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7859. var LoadFileError = /** @class */ (function (_super) {
  7860. __extends(LoadFileError, _super);
  7861. function LoadFileError(message, request) {
  7862. var _this = _super.call(this, message) || this;
  7863. _this.request = request;
  7864. _this.name = "LoadFileError";
  7865. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7866. return _this;
  7867. }
  7868. // Polyfill for Object.setPrototypeOf if necessary.
  7869. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7870. return LoadFileError;
  7871. }(Error));
  7872. BABYLON.LoadFileError = LoadFileError;
  7873. var RetryStrategy = /** @class */ (function () {
  7874. function RetryStrategy() {
  7875. }
  7876. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7877. if (maxRetries === void 0) { maxRetries = 3; }
  7878. if (baseInterval === void 0) { baseInterval = 500; }
  7879. return function (url, request, retryIndex) {
  7880. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7881. return -1;
  7882. }
  7883. return Math.pow(2, retryIndex) * baseInterval;
  7884. };
  7885. };
  7886. return RetryStrategy;
  7887. }());
  7888. BABYLON.RetryStrategy = RetryStrategy;
  7889. // Screenshots
  7890. var screenshotCanvas;
  7891. var cloneValue = function (source, destinationObject) {
  7892. if (!source)
  7893. return null;
  7894. if (source instanceof BABYLON.Mesh) {
  7895. return null;
  7896. }
  7897. if (source instanceof BABYLON.SubMesh) {
  7898. return source.clone(destinationObject);
  7899. }
  7900. else if (source.clone) {
  7901. return source.clone();
  7902. }
  7903. return null;
  7904. };
  7905. var Tools = /** @class */ (function () {
  7906. function Tools() {
  7907. }
  7908. /**
  7909. * Interpolates between a and b via alpha
  7910. * @param a The lower value (returned when alpha = 0)
  7911. * @param b The upper value (returned when alpha = 1)
  7912. * @param alpha The interpolation-factor
  7913. * @return The mixed value
  7914. */
  7915. Tools.Mix = function (a, b, alpha) {
  7916. return a * (1 - alpha) + b * alpha;
  7917. };
  7918. Tools.Instantiate = function (className) {
  7919. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7920. return Tools.RegisteredExternalClasses[className];
  7921. }
  7922. var arr = className.split(".");
  7923. var fn = (window || this);
  7924. for (var i = 0, len = arr.length; i < len; i++) {
  7925. fn = fn[arr[i]];
  7926. }
  7927. if (typeof fn !== "function") {
  7928. return null;
  7929. }
  7930. return fn;
  7931. };
  7932. /**
  7933. * Provides a slice function that will work even on IE
  7934. * @param data defines the array to slice
  7935. * @param start defines the start of the data (optional)
  7936. * @param end defines the end of the data (optional)
  7937. * @returns the new sliced array
  7938. */
  7939. Tools.Slice = function (data, start, end) {
  7940. if (data.slice) {
  7941. return data.slice(start, end);
  7942. }
  7943. return Array.prototype.slice.call(data, start, end);
  7944. };
  7945. Tools.SetImmediate = function (action) {
  7946. if (window.setImmediate) {
  7947. window.setImmediate(action);
  7948. }
  7949. else {
  7950. setTimeout(action, 1);
  7951. }
  7952. };
  7953. Tools.IsExponentOfTwo = function (value) {
  7954. var count = 1;
  7955. do {
  7956. count *= 2;
  7957. } while (count < value);
  7958. return count === value;
  7959. };
  7960. /**
  7961. * Find the next highest power of two.
  7962. * @param x Number to start search from.
  7963. * @return Next highest power of two.
  7964. */
  7965. Tools.CeilingPOT = function (x) {
  7966. x--;
  7967. x |= x >> 1;
  7968. x |= x >> 2;
  7969. x |= x >> 4;
  7970. x |= x >> 8;
  7971. x |= x >> 16;
  7972. x++;
  7973. return x;
  7974. };
  7975. /**
  7976. * Find the next lowest power of two.
  7977. * @param x Number to start search from.
  7978. * @return Next lowest power of two.
  7979. */
  7980. Tools.FloorPOT = function (x) {
  7981. x = x | (x >> 1);
  7982. x = x | (x >> 2);
  7983. x = x | (x >> 4);
  7984. x = x | (x >> 8);
  7985. x = x | (x >> 16);
  7986. return x - (x >> 1);
  7987. };
  7988. /**
  7989. * Find the nearest power of two.
  7990. * @param x Number to start search from.
  7991. * @return Next nearest power of two.
  7992. */
  7993. Tools.NearestPOT = function (x) {
  7994. var c = Tools.CeilingPOT(x);
  7995. var f = Tools.FloorPOT(x);
  7996. return (c - x) > (x - f) ? f : c;
  7997. };
  7998. Tools.GetExponentOfTwo = function (value, max, mode) {
  7999. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8000. var pot;
  8001. switch (mode) {
  8002. case BABYLON.Engine.SCALEMODE_FLOOR:
  8003. pot = Tools.FloorPOT(value);
  8004. break;
  8005. case BABYLON.Engine.SCALEMODE_NEAREST:
  8006. pot = Tools.NearestPOT(value);
  8007. break;
  8008. case BABYLON.Engine.SCALEMODE_CEILING:
  8009. default:
  8010. pot = Tools.CeilingPOT(value);
  8011. break;
  8012. }
  8013. return Math.min(pot, max);
  8014. };
  8015. Tools.GetFilename = function (path) {
  8016. var index = path.lastIndexOf("/");
  8017. if (index < 0)
  8018. return path;
  8019. return path.substring(index + 1);
  8020. };
  8021. /**
  8022. * Extracts the "folder" part of a path (everything before the filename).
  8023. * @param uri The URI to extract the info from
  8024. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8025. * @returns The "folder" part of the path
  8026. */
  8027. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8028. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8029. var index = uri.lastIndexOf("/");
  8030. if (index < 0) {
  8031. if (returnUnchangedIfNoSlash) {
  8032. return uri;
  8033. }
  8034. return "";
  8035. }
  8036. return uri.substring(0, index + 1);
  8037. };
  8038. Tools.GetDOMTextContent = function (element) {
  8039. var result = "";
  8040. var child = element.firstChild;
  8041. while (child) {
  8042. if (child.nodeType === 3) {
  8043. result += child.textContent;
  8044. }
  8045. child = child.nextSibling;
  8046. }
  8047. return result;
  8048. };
  8049. Tools.ToDegrees = function (angle) {
  8050. return angle * 180 / Math.PI;
  8051. };
  8052. Tools.ToRadians = function (angle) {
  8053. return angle * Math.PI / 180;
  8054. };
  8055. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8056. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8057. var output = "";
  8058. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8059. var i = 0;
  8060. var bytes = new Uint8Array(buffer);
  8061. while (i < bytes.length) {
  8062. chr1 = bytes[i++];
  8063. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8064. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8065. enc1 = chr1 >> 2;
  8066. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8067. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8068. enc4 = chr3 & 63;
  8069. if (isNaN(chr2)) {
  8070. enc3 = enc4 = 64;
  8071. }
  8072. else if (isNaN(chr3)) {
  8073. enc4 = 64;
  8074. }
  8075. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8076. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8077. }
  8078. return "data:image/png;base64," + output;
  8079. };
  8080. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8081. if (bias === void 0) { bias = null; }
  8082. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8083. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8084. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8085. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 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.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8103. if (bias === void 0) { bias = null; }
  8104. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8105. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8106. if (!stride) {
  8107. stride = 3;
  8108. }
  8109. for (var index = start; index < start + count; index++) {
  8110. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8111. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8112. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8113. }
  8114. if (bias) {
  8115. minimum.x -= minimum.x * bias.x + bias.y;
  8116. minimum.y -= minimum.y * bias.x + bias.y;
  8117. minimum.z -= minimum.z * bias.x + bias.y;
  8118. maximum.x += maximum.x * bias.x + bias.y;
  8119. maximum.y += maximum.y * bias.x + bias.y;
  8120. maximum.z += maximum.z * bias.x + bias.y;
  8121. }
  8122. return {
  8123. minimum: minimum,
  8124. maximum: maximum
  8125. };
  8126. };
  8127. Tools.Vector2ArrayFeeder = function (array) {
  8128. return function (index) {
  8129. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8130. var length = isFloatArray ? array.length / 2 : array.length;
  8131. if (index >= length) {
  8132. return null;
  8133. }
  8134. if (isFloatArray) {
  8135. var fa = array;
  8136. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8137. }
  8138. var a = array;
  8139. return a[index];
  8140. };
  8141. };
  8142. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8143. if (bias === void 0) { bias = null; }
  8144. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8145. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8146. var i = 0;
  8147. var cur = feeder(i++);
  8148. while (cur) {
  8149. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8150. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8151. cur = feeder(i++);
  8152. }
  8153. if (bias) {
  8154. minimum.x -= minimum.x * bias.x + bias.y;
  8155. minimum.y -= minimum.y * bias.x + bias.y;
  8156. maximum.x += maximum.x * bias.x + bias.y;
  8157. maximum.y += maximum.y * bias.x + bias.y;
  8158. }
  8159. return {
  8160. minimum: minimum,
  8161. maximum: maximum
  8162. };
  8163. };
  8164. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8165. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8166. return null;
  8167. return Array.isArray(obj) ? obj : [obj];
  8168. };
  8169. // Misc.
  8170. Tools.GetPointerPrefix = function () {
  8171. var eventPrefix = "pointer";
  8172. // Check if pointer events are supported
  8173. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8174. eventPrefix = "mouse";
  8175. }
  8176. return eventPrefix;
  8177. };
  8178. /**
  8179. * @param func - the function to be called
  8180. * @param requester - the object that will request the next frame. Falls back to window.
  8181. */
  8182. Tools.QueueNewFrame = function (func, requester) {
  8183. if (!Tools.IsWindowObjectExist()) {
  8184. return setTimeout(func, 16);
  8185. }
  8186. if (!requester) {
  8187. requester = window;
  8188. }
  8189. if (requester.requestAnimationFrame) {
  8190. return requester.requestAnimationFrame(func);
  8191. }
  8192. else if (requester.msRequestAnimationFrame) {
  8193. return requester.msRequestAnimationFrame(func);
  8194. }
  8195. else if (requester.webkitRequestAnimationFrame) {
  8196. return requester.webkitRequestAnimationFrame(func);
  8197. }
  8198. else if (requester.mozRequestAnimationFrame) {
  8199. return requester.mozRequestAnimationFrame(func);
  8200. }
  8201. else if (requester.oRequestAnimationFrame) {
  8202. return requester.oRequestAnimationFrame(func);
  8203. }
  8204. else {
  8205. return window.setTimeout(func, 16);
  8206. }
  8207. };
  8208. Tools.RequestFullscreen = function (element) {
  8209. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8210. if (!requestFunction)
  8211. return;
  8212. requestFunction.call(element);
  8213. };
  8214. Tools.ExitFullscreen = function () {
  8215. if (document.exitFullscreen) {
  8216. document.exitFullscreen();
  8217. }
  8218. else if (document.mozCancelFullScreen) {
  8219. document.mozCancelFullScreen();
  8220. }
  8221. else if (document.webkitCancelFullScreen) {
  8222. document.webkitCancelFullScreen();
  8223. }
  8224. else if (document.msCancelFullScreen) {
  8225. document.msCancelFullScreen();
  8226. }
  8227. };
  8228. Tools.SetCorsBehavior = function (url, element) {
  8229. if (url && url.indexOf("data:") === 0) {
  8230. return;
  8231. }
  8232. if (Tools.CorsBehavior) {
  8233. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8234. element.crossOrigin = Tools.CorsBehavior;
  8235. }
  8236. else {
  8237. var result = Tools.CorsBehavior(url);
  8238. if (result) {
  8239. element.crossOrigin = result;
  8240. }
  8241. }
  8242. }
  8243. };
  8244. // External files
  8245. Tools.CleanUrl = function (url) {
  8246. url = url.replace(/#/mg, "%23");
  8247. return url;
  8248. };
  8249. Tools.LoadImage = function (url, onLoad, onError, database) {
  8250. if (url instanceof ArrayBuffer) {
  8251. url = Tools.EncodeArrayBufferTobase64(url);
  8252. }
  8253. url = Tools.CleanUrl(url);
  8254. url = Tools.PreprocessUrl(url);
  8255. var img = new Image();
  8256. Tools.SetCorsBehavior(url, img);
  8257. var loadHandler = function () {
  8258. img.removeEventListener("load", loadHandler);
  8259. img.removeEventListener("error", errorHandler);
  8260. onLoad(img);
  8261. };
  8262. var errorHandler = function (err) {
  8263. img.removeEventListener("load", loadHandler);
  8264. img.removeEventListener("error", errorHandler);
  8265. Tools.Error("Error while trying to load image: " + url);
  8266. if (onError) {
  8267. onError("Error while trying to load image: " + url, err);
  8268. }
  8269. };
  8270. img.addEventListener("load", loadHandler);
  8271. img.addEventListener("error", errorHandler);
  8272. var noIndexedDB = function () {
  8273. img.src = url;
  8274. };
  8275. var loadFromIndexedDB = function () {
  8276. if (database) {
  8277. database.loadImageFromDB(url, img);
  8278. }
  8279. };
  8280. //ANY database to do!
  8281. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8282. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8283. }
  8284. else {
  8285. if (url.indexOf("file:") !== -1) {
  8286. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8287. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8288. try {
  8289. var blobURL;
  8290. try {
  8291. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8292. }
  8293. catch (ex) {
  8294. // Chrome doesn't support oneTimeOnly parameter
  8295. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8296. }
  8297. img.src = blobURL;
  8298. }
  8299. catch (e) {
  8300. img.src = "";
  8301. }
  8302. return img;
  8303. }
  8304. }
  8305. noIndexedDB();
  8306. }
  8307. return img;
  8308. };
  8309. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8310. url = Tools.CleanUrl(url);
  8311. url = Tools.PreprocessUrl(url);
  8312. // If file and file input are set
  8313. if (url.indexOf("file:") !== -1) {
  8314. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8315. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8316. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8317. }
  8318. }
  8319. var loadUrl = Tools.BaseUrl + url;
  8320. var aborted = false;
  8321. var fileRequest = {
  8322. onCompleteObservable: new BABYLON.Observable(),
  8323. abort: function () { return aborted = true; },
  8324. };
  8325. var requestFile = function () {
  8326. var request = new XMLHttpRequest();
  8327. var retryHandle = null;
  8328. fileRequest.abort = function () {
  8329. aborted = true;
  8330. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8331. request.abort();
  8332. }
  8333. if (retryHandle !== null) {
  8334. clearTimeout(retryHandle);
  8335. retryHandle = null;
  8336. }
  8337. };
  8338. var retryLoop = function (retryIndex) {
  8339. request.open('GET', loadUrl, true);
  8340. if (useArrayBuffer) {
  8341. request.responseType = "arraybuffer";
  8342. }
  8343. if (onProgress) {
  8344. request.addEventListener("progress", onProgress);
  8345. }
  8346. var onLoadEnd = function () {
  8347. request.removeEventListener("loadend", onLoadEnd);
  8348. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8349. fileRequest.onCompleteObservable.clear();
  8350. };
  8351. request.addEventListener("loadend", onLoadEnd);
  8352. var onReadyStateChange = function () {
  8353. if (aborted) {
  8354. return;
  8355. }
  8356. // In case of undefined state in some browsers.
  8357. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8358. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8359. request.removeEventListener("readystatechange", onReadyStateChange);
  8360. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8361. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8362. return;
  8363. }
  8364. var retryStrategy = Tools.DefaultRetryStrategy;
  8365. if (retryStrategy) {
  8366. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8367. if (waitTime !== -1) {
  8368. // Prevent the request from completing for retry.
  8369. request.removeEventListener("loadend", onLoadEnd);
  8370. request = new XMLHttpRequest();
  8371. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8372. return;
  8373. }
  8374. }
  8375. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8376. if (onError) {
  8377. onError(request, e);
  8378. }
  8379. else {
  8380. throw e;
  8381. }
  8382. }
  8383. };
  8384. request.addEventListener("readystatechange", onReadyStateChange);
  8385. request.send();
  8386. };
  8387. retryLoop(0);
  8388. };
  8389. // Caching all files
  8390. if (database && database.enableSceneOffline) {
  8391. var noIndexedDB_1 = function () {
  8392. if (!aborted) {
  8393. requestFile();
  8394. }
  8395. };
  8396. var loadFromIndexedDB = function () {
  8397. // TODO: database needs to support aborting and should return a IFileRequest
  8398. if (aborted) {
  8399. return;
  8400. }
  8401. if (database) {
  8402. database.loadFileFromDB(url, function (data) {
  8403. if (!aborted) {
  8404. onSuccess(data);
  8405. }
  8406. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8407. }, onProgress ? function (event) {
  8408. if (!aborted) {
  8409. onProgress(event);
  8410. }
  8411. } : undefined, noIndexedDB_1, useArrayBuffer);
  8412. }
  8413. };
  8414. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8415. }
  8416. else {
  8417. requestFile();
  8418. }
  8419. return fileRequest;
  8420. };
  8421. /**
  8422. * Load a script (identified by an url). When the url returns, the
  8423. * content of this file is added into a new script element, attached to the DOM (body element)
  8424. */
  8425. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8426. var head = document.getElementsByTagName('head')[0];
  8427. var script = document.createElement('script');
  8428. script.type = 'text/javascript';
  8429. script.src = scriptUrl;
  8430. script.onload = function () {
  8431. if (onSuccess) {
  8432. onSuccess();
  8433. }
  8434. };
  8435. script.onerror = function (e) {
  8436. if (onError) {
  8437. onError("Unable to load script", e);
  8438. }
  8439. };
  8440. head.appendChild(script);
  8441. };
  8442. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8443. var reader = new FileReader();
  8444. var request = {
  8445. onCompleteObservable: new BABYLON.Observable(),
  8446. abort: function () { return reader.abort(); },
  8447. };
  8448. reader.onloadend = function (e) {
  8449. request.onCompleteObservable.notifyObservers(request);
  8450. };
  8451. reader.onload = function (e) {
  8452. //target doesn't have result from ts 1.3
  8453. callback(e.target['result']);
  8454. };
  8455. reader.onprogress = progressCallback;
  8456. reader.readAsDataURL(fileToLoad);
  8457. return request;
  8458. };
  8459. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8460. var reader = new FileReader();
  8461. var request = {
  8462. onCompleteObservable: new BABYLON.Observable(),
  8463. abort: function () { return reader.abort(); },
  8464. };
  8465. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8466. reader.onerror = function (e) {
  8467. Tools.Log("Error while reading file: " + fileToLoad.name);
  8468. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8469. };
  8470. reader.onload = function (e) {
  8471. //target doesn't have result from ts 1.3
  8472. callback(e.target['result']);
  8473. };
  8474. if (progressCallBack) {
  8475. reader.onprogress = progressCallBack;
  8476. }
  8477. if (!useArrayBuffer) {
  8478. // Asynchronous read
  8479. reader.readAsText(fileToLoad);
  8480. }
  8481. else {
  8482. reader.readAsArrayBuffer(fileToLoad);
  8483. }
  8484. return request;
  8485. };
  8486. //returns a downloadable url to a file content.
  8487. Tools.FileAsURL = function (content) {
  8488. var fileBlob = new Blob([content]);
  8489. var url = window.URL || window.webkitURL;
  8490. var link = url.createObjectURL(fileBlob);
  8491. return link;
  8492. };
  8493. // Misc.
  8494. Tools.Format = function (value, decimals) {
  8495. if (decimals === void 0) { decimals = 2; }
  8496. return value.toFixed(decimals);
  8497. };
  8498. Tools.CheckExtends = function (v, min, max) {
  8499. if (v.x < min.x)
  8500. min.x = v.x;
  8501. if (v.y < min.y)
  8502. min.y = v.y;
  8503. if (v.z < min.z)
  8504. min.z = v.z;
  8505. if (v.x > max.x)
  8506. max.x = v.x;
  8507. if (v.y > max.y)
  8508. max.y = v.y;
  8509. if (v.z > max.z)
  8510. max.z = v.z;
  8511. };
  8512. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8513. for (var prop in source) {
  8514. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8515. continue;
  8516. }
  8517. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8518. continue;
  8519. }
  8520. var sourceValue = source[prop];
  8521. var typeOfSourceValue = typeof sourceValue;
  8522. if (typeOfSourceValue === "function") {
  8523. continue;
  8524. }
  8525. try {
  8526. if (typeOfSourceValue === "object") {
  8527. if (sourceValue instanceof Array) {
  8528. destination[prop] = [];
  8529. if (sourceValue.length > 0) {
  8530. if (typeof sourceValue[0] == "object") {
  8531. for (var index = 0; index < sourceValue.length; index++) {
  8532. var clonedValue = cloneValue(sourceValue[index], destination);
  8533. if (destination[prop].indexOf(clonedValue) === -1) {
  8534. destination[prop].push(clonedValue);
  8535. }
  8536. }
  8537. }
  8538. else {
  8539. destination[prop] = sourceValue.slice(0);
  8540. }
  8541. }
  8542. }
  8543. else {
  8544. destination[prop] = cloneValue(sourceValue, destination);
  8545. }
  8546. }
  8547. else {
  8548. destination[prop] = sourceValue;
  8549. }
  8550. }
  8551. catch (e) {
  8552. // Just ignore error (it could be because of a read-only property)
  8553. }
  8554. }
  8555. };
  8556. Tools.IsEmpty = function (obj) {
  8557. for (var i in obj) {
  8558. if (obj.hasOwnProperty(i)) {
  8559. return false;
  8560. }
  8561. }
  8562. return true;
  8563. };
  8564. Tools.RegisterTopRootEvents = function (events) {
  8565. for (var index = 0; index < events.length; index++) {
  8566. var event = events[index];
  8567. window.addEventListener(event.name, event.handler, false);
  8568. try {
  8569. if (window.parent) {
  8570. window.parent.addEventListener(event.name, event.handler, false);
  8571. }
  8572. }
  8573. catch (e) {
  8574. // Silently fails...
  8575. }
  8576. }
  8577. };
  8578. Tools.UnregisterTopRootEvents = function (events) {
  8579. for (var index = 0; index < events.length; index++) {
  8580. var event = events[index];
  8581. window.removeEventListener(event.name, event.handler);
  8582. try {
  8583. if (window.parent) {
  8584. window.parent.removeEventListener(event.name, event.handler);
  8585. }
  8586. }
  8587. catch (e) {
  8588. // Silently fails...
  8589. }
  8590. }
  8591. };
  8592. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8593. if (mimeType === void 0) { mimeType = "image/png"; }
  8594. // Read the contents of the framebuffer
  8595. var numberOfChannelsByLine = width * 4;
  8596. var halfHeight = height / 2;
  8597. //Reading datas from WebGL
  8598. var data = engine.readPixels(0, 0, width, height);
  8599. //To flip image on Y axis.
  8600. for (var i = 0; i < halfHeight; i++) {
  8601. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8602. var currentCell = j + i * numberOfChannelsByLine;
  8603. var targetLine = height - i - 1;
  8604. var targetCell = j + targetLine * numberOfChannelsByLine;
  8605. var temp = data[currentCell];
  8606. data[currentCell] = data[targetCell];
  8607. data[targetCell] = temp;
  8608. }
  8609. }
  8610. // Create a 2D canvas to store the result
  8611. if (!screenshotCanvas) {
  8612. screenshotCanvas = document.createElement('canvas');
  8613. }
  8614. screenshotCanvas.width = width;
  8615. screenshotCanvas.height = height;
  8616. var context = screenshotCanvas.getContext('2d');
  8617. if (context) {
  8618. // Copy the pixels to a 2D canvas
  8619. var imageData = context.createImageData(width, height);
  8620. var castData = (imageData.data);
  8621. castData.set(data);
  8622. context.putImageData(imageData, 0, 0);
  8623. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8624. }
  8625. };
  8626. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8627. if (mimeType === void 0) { mimeType = "image/png"; }
  8628. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8629. if (successCallback) {
  8630. successCallback(base64Image);
  8631. }
  8632. else {
  8633. // We need HTMLCanvasElement.toBlob for HD screenshots
  8634. if (!screenshotCanvas.toBlob) {
  8635. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8636. screenshotCanvas.toBlob = function (callback, type, quality) {
  8637. var _this = this;
  8638. setTimeout(function () {
  8639. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8640. for (var i = 0; i < len; i++) {
  8641. arr[i] = binStr.charCodeAt(i);
  8642. }
  8643. callback(new Blob([arr], { type: type || 'image/png' }));
  8644. });
  8645. };
  8646. }
  8647. screenshotCanvas.toBlob(function (blob) {
  8648. var url = URL.createObjectURL(blob);
  8649. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8650. if (("download" in document.createElement("a"))) {
  8651. var a = window.document.createElement("a");
  8652. a.href = url;
  8653. if (fileName) {
  8654. a.setAttribute("download", fileName);
  8655. }
  8656. else {
  8657. var date = new Date();
  8658. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8659. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8660. }
  8661. window.document.body.appendChild(a);
  8662. a.addEventListener("click", function () {
  8663. if (a.parentElement) {
  8664. a.parentElement.removeChild(a);
  8665. }
  8666. });
  8667. a.click();
  8668. }
  8669. else {
  8670. var newWindow = window.open("");
  8671. if (!newWindow)
  8672. return;
  8673. var img = newWindow.document.createElement("img");
  8674. img.onload = function () {
  8675. // no longer need to read the blob so it's revoked
  8676. URL.revokeObjectURL(url);
  8677. };
  8678. img.src = url;
  8679. newWindow.document.body.appendChild(img);
  8680. }
  8681. });
  8682. }
  8683. };
  8684. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8685. if (mimeType === void 0) { mimeType = "image/png"; }
  8686. var width;
  8687. var height;
  8688. // If a precision value is specified
  8689. if (size.precision) {
  8690. width = Math.round(engine.getRenderWidth() * size.precision);
  8691. height = Math.round(width / engine.getAspectRatio(camera));
  8692. }
  8693. else if (size.width && size.height) {
  8694. width = size.width;
  8695. height = size.height;
  8696. }
  8697. else if (size.width && !size.height) {
  8698. width = size.width;
  8699. height = Math.round(width / engine.getAspectRatio(camera));
  8700. }
  8701. else if (size.height && !size.width) {
  8702. height = size.height;
  8703. width = Math.round(height * engine.getAspectRatio(camera));
  8704. }
  8705. else if (!isNaN(size)) {
  8706. height = size;
  8707. width = size;
  8708. }
  8709. else {
  8710. Tools.Error("Invalid 'size' parameter !");
  8711. return;
  8712. }
  8713. if (!screenshotCanvas) {
  8714. screenshotCanvas = document.createElement('canvas');
  8715. }
  8716. screenshotCanvas.width = width;
  8717. screenshotCanvas.height = height;
  8718. var renderContext = screenshotCanvas.getContext("2d");
  8719. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8720. var newWidth = width;
  8721. var newHeight = newWidth / ratio;
  8722. if (newHeight > height) {
  8723. newHeight = height;
  8724. newWidth = newHeight * ratio;
  8725. }
  8726. var offsetX = Math.max(0, width - newWidth) / 2;
  8727. var offsetY = Math.max(0, height - newHeight) / 2;
  8728. var renderingCanvas = engine.getRenderingCanvas();
  8729. if (renderContext && renderingCanvas) {
  8730. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8731. }
  8732. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8733. };
  8734. /**
  8735. * Generates an image screenshot from the specified camera.
  8736. *
  8737. * @param engine The engine to use for rendering
  8738. * @param camera The camera to use for rendering
  8739. * @param size This parameter can be set to a single number or to an object with the
  8740. * following (optional) properties: precision, width, height. If a single number is passed,
  8741. * it will be used for both width and height. If an object is passed, the screenshot size
  8742. * will be derived from the parameters. The precision property is a multiplier allowing
  8743. * rendering at a higher or lower resolution.
  8744. * @param successCallback The callback receives a single parameter which contains the
  8745. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8746. * src parameter of an <img> to display it.
  8747. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8748. * Check your browser for supported MIME types.
  8749. * @param samples Texture samples (default: 1)
  8750. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8751. * @param fileName A name for for the downloaded file.
  8752. * @constructor
  8753. */
  8754. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8755. if (mimeType === void 0) { mimeType = "image/png"; }
  8756. if (samples === void 0) { samples = 1; }
  8757. if (antialiasing === void 0) { antialiasing = false; }
  8758. var width;
  8759. var height;
  8760. //If a precision value is specified
  8761. if (size.precision) {
  8762. width = Math.round(engine.getRenderWidth() * size.precision);
  8763. height = Math.round(width / engine.getAspectRatio(camera));
  8764. size = { width: width, height: height };
  8765. }
  8766. else if (size.width && size.height) {
  8767. width = size.width;
  8768. height = size.height;
  8769. }
  8770. else if (size.width && !size.height) {
  8771. width = size.width;
  8772. height = Math.round(width / engine.getAspectRatio(camera));
  8773. size = { width: width, height: height };
  8774. }
  8775. else if (size.height && !size.width) {
  8776. height = size.height;
  8777. width = Math.round(height * engine.getAspectRatio(camera));
  8778. size = { width: width, height: height };
  8779. }
  8780. else if (!isNaN(size)) {
  8781. height = size;
  8782. width = size;
  8783. }
  8784. else {
  8785. Tools.Error("Invalid 'size' parameter !");
  8786. return;
  8787. }
  8788. var scene = camera.getScene();
  8789. var previousCamera = null;
  8790. if (scene.activeCamera !== camera) {
  8791. previousCamera = scene.activeCamera;
  8792. scene.activeCamera = camera;
  8793. }
  8794. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8795. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8796. texture.renderList = null;
  8797. texture.samples = samples;
  8798. if (antialiasing) {
  8799. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8800. }
  8801. texture.onAfterRenderObservable.add(function () {
  8802. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8803. });
  8804. scene.incrementRenderId();
  8805. scene.resetCachedMaterial();
  8806. texture.render(true);
  8807. texture.dispose();
  8808. if (previousCamera) {
  8809. scene.activeCamera = previousCamera;
  8810. }
  8811. camera.getProjectionMatrix(true); // Force cache refresh;
  8812. };
  8813. // XHR response validator for local file scenario
  8814. Tools.ValidateXHRData = function (xhr, dataType) {
  8815. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8816. if (dataType === void 0) { dataType = 7; }
  8817. try {
  8818. if (dataType & 1) {
  8819. if (xhr.responseText && xhr.responseText.length > 0) {
  8820. return true;
  8821. }
  8822. else if (dataType === 1) {
  8823. return false;
  8824. }
  8825. }
  8826. if (dataType & 2) {
  8827. // Check header width and height since there is no "TGA" magic number
  8828. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8829. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8830. return true;
  8831. }
  8832. else if (dataType === 2) {
  8833. return false;
  8834. }
  8835. }
  8836. if (dataType & 4) {
  8837. // Check for the "DDS" magic number
  8838. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8839. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8840. return true;
  8841. }
  8842. else {
  8843. return false;
  8844. }
  8845. }
  8846. }
  8847. catch (e) {
  8848. // Global protection
  8849. }
  8850. return false;
  8851. };
  8852. /**
  8853. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8854. * Be aware Math.random() could cause collisions, but:
  8855. * "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"
  8856. */
  8857. Tools.RandomId = function () {
  8858. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8859. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8860. return v.toString(16);
  8861. });
  8862. };
  8863. /**
  8864. * Test if the given uri is a base64 string.
  8865. * @param uri The uri to test
  8866. * @return True if the uri is a base64 string or false otherwise.
  8867. */
  8868. Tools.IsBase64 = function (uri) {
  8869. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8870. };
  8871. /**
  8872. * Decode the given base64 uri.
  8873. * @param uri The uri to decode
  8874. * @return The decoded base64 data.
  8875. */
  8876. Tools.DecodeBase64 = function (uri) {
  8877. var decodedString = atob(uri.split(",")[1]);
  8878. var bufferLength = decodedString.length;
  8879. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8880. for (var i = 0; i < bufferLength; i++) {
  8881. bufferView[i] = decodedString.charCodeAt(i);
  8882. }
  8883. return bufferView.buffer;
  8884. };
  8885. Object.defineProperty(Tools, "NoneLogLevel", {
  8886. get: function () {
  8887. return Tools._NoneLogLevel;
  8888. },
  8889. enumerable: true,
  8890. configurable: true
  8891. });
  8892. Object.defineProperty(Tools, "MessageLogLevel", {
  8893. get: function () {
  8894. return Tools._MessageLogLevel;
  8895. },
  8896. enumerable: true,
  8897. configurable: true
  8898. });
  8899. Object.defineProperty(Tools, "WarningLogLevel", {
  8900. get: function () {
  8901. return Tools._WarningLogLevel;
  8902. },
  8903. enumerable: true,
  8904. configurable: true
  8905. });
  8906. Object.defineProperty(Tools, "ErrorLogLevel", {
  8907. get: function () {
  8908. return Tools._ErrorLogLevel;
  8909. },
  8910. enumerable: true,
  8911. configurable: true
  8912. });
  8913. Object.defineProperty(Tools, "AllLogLevel", {
  8914. get: function () {
  8915. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8916. },
  8917. enumerable: true,
  8918. configurable: true
  8919. });
  8920. Tools._AddLogEntry = function (entry) {
  8921. Tools._LogCache = entry + Tools._LogCache;
  8922. if (Tools.OnNewCacheEntry) {
  8923. Tools.OnNewCacheEntry(entry);
  8924. }
  8925. };
  8926. Tools._FormatMessage = function (message) {
  8927. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8928. var date = new Date();
  8929. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8930. };
  8931. Tools._LogDisabled = function (message) {
  8932. // nothing to do
  8933. };
  8934. Tools._LogEnabled = function (message) {
  8935. var formattedMessage = Tools._FormatMessage(message);
  8936. console.log("BJS - " + formattedMessage);
  8937. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8938. Tools._AddLogEntry(entry);
  8939. };
  8940. Tools._WarnDisabled = function (message) {
  8941. // nothing to do
  8942. };
  8943. Tools._WarnEnabled = function (message) {
  8944. var formattedMessage = Tools._FormatMessage(message);
  8945. console.warn("BJS - " + formattedMessage);
  8946. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8947. Tools._AddLogEntry(entry);
  8948. };
  8949. Tools._ErrorDisabled = function (message) {
  8950. // nothing to do
  8951. };
  8952. Tools._ErrorEnabled = function (message) {
  8953. Tools.errorsCount++;
  8954. var formattedMessage = Tools._FormatMessage(message);
  8955. console.error("BJS - " + formattedMessage);
  8956. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8957. Tools._AddLogEntry(entry);
  8958. };
  8959. Object.defineProperty(Tools, "LogCache", {
  8960. get: function () {
  8961. return Tools._LogCache;
  8962. },
  8963. enumerable: true,
  8964. configurable: true
  8965. });
  8966. Tools.ClearLogCache = function () {
  8967. Tools._LogCache = "";
  8968. Tools.errorsCount = 0;
  8969. };
  8970. Object.defineProperty(Tools, "LogLevels", {
  8971. set: function (level) {
  8972. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8973. Tools.Log = Tools._LogEnabled;
  8974. }
  8975. else {
  8976. Tools.Log = Tools._LogDisabled;
  8977. }
  8978. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8979. Tools.Warn = Tools._WarnEnabled;
  8980. }
  8981. else {
  8982. Tools.Warn = Tools._WarnDisabled;
  8983. }
  8984. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8985. Tools.Error = Tools._ErrorEnabled;
  8986. }
  8987. else {
  8988. Tools.Error = Tools._ErrorDisabled;
  8989. }
  8990. },
  8991. enumerable: true,
  8992. configurable: true
  8993. });
  8994. Tools.IsWindowObjectExist = function () {
  8995. return (typeof window) !== "undefined";
  8996. };
  8997. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8998. get: function () {
  8999. return Tools._PerformanceNoneLogLevel;
  9000. },
  9001. enumerable: true,
  9002. configurable: true
  9003. });
  9004. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9005. get: function () {
  9006. return Tools._PerformanceUserMarkLogLevel;
  9007. },
  9008. enumerable: true,
  9009. configurable: true
  9010. });
  9011. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9012. get: function () {
  9013. return Tools._PerformanceConsoleLogLevel;
  9014. },
  9015. enumerable: true,
  9016. configurable: true
  9017. });
  9018. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9019. set: function (level) {
  9020. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9021. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9022. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9023. return;
  9024. }
  9025. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9026. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9027. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9028. return;
  9029. }
  9030. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9031. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9037. };
  9038. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9039. };
  9040. Tools._StartUserMark = function (counterName, condition) {
  9041. if (condition === void 0) { condition = true; }
  9042. if (!Tools._performance) {
  9043. if (!Tools.IsWindowObjectExist()) {
  9044. return;
  9045. }
  9046. Tools._performance = window.performance;
  9047. }
  9048. if (!condition || !Tools._performance.mark) {
  9049. return;
  9050. }
  9051. Tools._performance.mark(counterName + "-Begin");
  9052. };
  9053. Tools._EndUserMark = function (counterName, condition) {
  9054. if (condition === void 0) { condition = true; }
  9055. if (!condition || !Tools._performance.mark) {
  9056. return;
  9057. }
  9058. Tools._performance.mark(counterName + "-End");
  9059. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9060. };
  9061. Tools._StartPerformanceConsole = function (counterName, condition) {
  9062. if (condition === void 0) { condition = true; }
  9063. if (!condition) {
  9064. return;
  9065. }
  9066. Tools._StartUserMark(counterName, condition);
  9067. if (console.time) {
  9068. console.time(counterName);
  9069. }
  9070. };
  9071. Tools._EndPerformanceConsole = function (counterName, condition) {
  9072. if (condition === void 0) { condition = true; }
  9073. if (!condition) {
  9074. return;
  9075. }
  9076. Tools._EndUserMark(counterName, condition);
  9077. if (console.time) {
  9078. console.timeEnd(counterName);
  9079. }
  9080. };
  9081. Object.defineProperty(Tools, "Now", {
  9082. get: function () {
  9083. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9084. return window.performance.now();
  9085. }
  9086. return new Date().getTime();
  9087. },
  9088. enumerable: true,
  9089. configurable: true
  9090. });
  9091. /**
  9092. * This method will return the name of the class used to create the instance of the given object.
  9093. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9094. * @param object the object to get the class name from
  9095. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9096. */
  9097. Tools.GetClassName = function (object, isType) {
  9098. if (isType === void 0) { isType = false; }
  9099. var name = null;
  9100. if (!isType && object.getClassName) {
  9101. name = object.getClassName();
  9102. }
  9103. else {
  9104. if (object instanceof Object) {
  9105. var classObj = isType ? object : Object.getPrototypeOf(object);
  9106. name = classObj.constructor["__bjsclassName__"];
  9107. }
  9108. if (!name) {
  9109. name = typeof object;
  9110. }
  9111. }
  9112. return name;
  9113. };
  9114. Tools.First = function (array, predicate) {
  9115. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9116. var el = array_1[_i];
  9117. if (predicate(el)) {
  9118. return el;
  9119. }
  9120. }
  9121. return null;
  9122. };
  9123. /**
  9124. * This method will return the name of the full name of the class, including its owning module (if any).
  9125. * 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).
  9126. * @param object the object to get the class name from
  9127. * @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.
  9128. */
  9129. Tools.getFullClassName = function (object, isType) {
  9130. if (isType === void 0) { isType = false; }
  9131. var className = null;
  9132. var moduleName = null;
  9133. if (!isType && object.getClassName) {
  9134. className = object.getClassName();
  9135. }
  9136. else {
  9137. if (object instanceof Object) {
  9138. var classObj = isType ? object : Object.getPrototypeOf(object);
  9139. className = classObj.constructor["__bjsclassName__"];
  9140. moduleName = classObj.constructor["__bjsmoduleName__"];
  9141. }
  9142. if (!className) {
  9143. className = typeof object;
  9144. }
  9145. }
  9146. if (!className) {
  9147. return null;
  9148. }
  9149. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9150. };
  9151. /**
  9152. * 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.
  9153. * @param array
  9154. */
  9155. Tools.arrayOrStringFeeder = function (array) {
  9156. return function (index) {
  9157. if (index >= array.length) {
  9158. return null;
  9159. }
  9160. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9161. if (val && val.getHashCode) {
  9162. val = val.getHashCode();
  9163. }
  9164. if (typeof val === "string") {
  9165. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9166. }
  9167. return val;
  9168. };
  9169. };
  9170. /**
  9171. * Compute the hashCode of a stream of number
  9172. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9173. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9174. * @return the hash code computed
  9175. */
  9176. Tools.hashCodeFromStream = function (feeder) {
  9177. // Based from here: http://stackoverflow.com/a/7616484/802124
  9178. var hash = 0;
  9179. var index = 0;
  9180. var chr = feeder(index++);
  9181. while (chr != null) {
  9182. hash = ((hash << 5) - hash) + chr;
  9183. hash |= 0; // Convert to 32bit integer
  9184. chr = feeder(index++);
  9185. }
  9186. return hash;
  9187. };
  9188. /**
  9189. * Returns a promise that resolves after the given amount of time.
  9190. * @param delay Number of milliseconds to delay
  9191. * @returns Promise that resolves after the given amount of time
  9192. */
  9193. Tools.DelayAsync = function (delay) {
  9194. return new Promise(function (resolve) {
  9195. setTimeout(function () {
  9196. resolve();
  9197. }, delay);
  9198. });
  9199. };
  9200. Tools.BaseUrl = "";
  9201. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9202. /**
  9203. * Default behaviour for cors in the application.
  9204. * It can be a string if the expected behavior is identical in the entire app.
  9205. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9206. */
  9207. Tools.CorsBehavior = "anonymous";
  9208. Tools.UseFallbackTexture = true;
  9209. /**
  9210. * Use this object to register external classes like custom textures or material
  9211. * to allow the laoders to instantiate them
  9212. */
  9213. Tools.RegisteredExternalClasses = {};
  9214. // Used in case of a texture loading problem
  9215. 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";
  9216. Tools.PreprocessUrl = function (url) {
  9217. return url;
  9218. };
  9219. // Logs
  9220. Tools._NoneLogLevel = 0;
  9221. Tools._MessageLogLevel = 1;
  9222. Tools._WarningLogLevel = 2;
  9223. Tools._ErrorLogLevel = 4;
  9224. Tools._LogCache = "";
  9225. Tools.errorsCount = 0;
  9226. Tools.Log = Tools._LogEnabled;
  9227. Tools.Warn = Tools._WarnEnabled;
  9228. Tools.Error = Tools._ErrorEnabled;
  9229. // Performances
  9230. Tools._PerformanceNoneLogLevel = 0;
  9231. Tools._PerformanceUserMarkLogLevel = 1;
  9232. Tools._PerformanceConsoleLogLevel = 2;
  9233. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9234. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9235. return Tools;
  9236. }());
  9237. BABYLON.Tools = Tools;
  9238. /**
  9239. * This class is used to track a performance counter which is number based.
  9240. * The user has access to many properties which give statistics of different nature
  9241. *
  9242. * The implementer can track two kinds of Performance Counter: time and count
  9243. * 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.
  9244. * 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.
  9245. */
  9246. var PerfCounter = /** @class */ (function () {
  9247. function PerfCounter() {
  9248. this._startMonitoringTime = 0;
  9249. this._min = 0;
  9250. this._max = 0;
  9251. this._average = 0;
  9252. this._lastSecAverage = 0;
  9253. this._current = 0;
  9254. this._totalValueCount = 0;
  9255. this._totalAccumulated = 0;
  9256. this._lastSecAccumulated = 0;
  9257. this._lastSecTime = 0;
  9258. this._lastSecValueCount = 0;
  9259. }
  9260. Object.defineProperty(PerfCounter.prototype, "min", {
  9261. /**
  9262. * Returns the smallest value ever
  9263. */
  9264. get: function () {
  9265. return this._min;
  9266. },
  9267. enumerable: true,
  9268. configurable: true
  9269. });
  9270. Object.defineProperty(PerfCounter.prototype, "max", {
  9271. /**
  9272. * Returns the biggest value ever
  9273. */
  9274. get: function () {
  9275. return this._max;
  9276. },
  9277. enumerable: true,
  9278. configurable: true
  9279. });
  9280. Object.defineProperty(PerfCounter.prototype, "average", {
  9281. /**
  9282. * Returns the average value since the performance counter is running
  9283. */
  9284. get: function () {
  9285. return this._average;
  9286. },
  9287. enumerable: true,
  9288. configurable: true
  9289. });
  9290. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9291. /**
  9292. * Returns the average value of the last second the counter was monitored
  9293. */
  9294. get: function () {
  9295. return this._lastSecAverage;
  9296. },
  9297. enumerable: true,
  9298. configurable: true
  9299. });
  9300. Object.defineProperty(PerfCounter.prototype, "current", {
  9301. /**
  9302. * Returns the current value
  9303. */
  9304. get: function () {
  9305. return this._current;
  9306. },
  9307. enumerable: true,
  9308. configurable: true
  9309. });
  9310. Object.defineProperty(PerfCounter.prototype, "total", {
  9311. get: function () {
  9312. return this._totalAccumulated;
  9313. },
  9314. enumerable: true,
  9315. configurable: true
  9316. });
  9317. Object.defineProperty(PerfCounter.prototype, "count", {
  9318. get: function () {
  9319. return this._totalValueCount;
  9320. },
  9321. enumerable: true,
  9322. configurable: true
  9323. });
  9324. /**
  9325. * Call this method to start monitoring a new frame.
  9326. * 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.
  9327. */
  9328. PerfCounter.prototype.fetchNewFrame = function () {
  9329. this._totalValueCount++;
  9330. this._current = 0;
  9331. this._lastSecValueCount++;
  9332. };
  9333. /**
  9334. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9335. * @param newCount the count value to add to the monitored count
  9336. * @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.
  9337. */
  9338. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9339. if (!PerfCounter.Enabled) {
  9340. return;
  9341. }
  9342. this._current += newCount;
  9343. if (fetchResult) {
  9344. this._fetchResult();
  9345. }
  9346. };
  9347. /**
  9348. * Start monitoring this performance counter
  9349. */
  9350. PerfCounter.prototype.beginMonitoring = function () {
  9351. if (!PerfCounter.Enabled) {
  9352. return;
  9353. }
  9354. this._startMonitoringTime = Tools.Now;
  9355. };
  9356. /**
  9357. * Compute the time lapsed since the previous beginMonitoring() call.
  9358. * @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
  9359. */
  9360. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9361. if (newFrame === void 0) { newFrame = true; }
  9362. if (!PerfCounter.Enabled) {
  9363. return;
  9364. }
  9365. if (newFrame) {
  9366. this.fetchNewFrame();
  9367. }
  9368. var currentTime = Tools.Now;
  9369. this._current = currentTime - this._startMonitoringTime;
  9370. if (newFrame) {
  9371. this._fetchResult();
  9372. }
  9373. };
  9374. PerfCounter.prototype._fetchResult = function () {
  9375. this._totalAccumulated += this._current;
  9376. this._lastSecAccumulated += this._current;
  9377. // Min/Max update
  9378. this._min = Math.min(this._min, this._current);
  9379. this._max = Math.max(this._max, this._current);
  9380. this._average = this._totalAccumulated / this._totalValueCount;
  9381. // Reset last sec?
  9382. var now = Tools.Now;
  9383. if ((now - this._lastSecTime) > 1000) {
  9384. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9385. this._lastSecTime = now;
  9386. this._lastSecAccumulated = 0;
  9387. this._lastSecValueCount = 0;
  9388. }
  9389. };
  9390. PerfCounter.Enabled = true;
  9391. return PerfCounter;
  9392. }());
  9393. BABYLON.PerfCounter = PerfCounter;
  9394. /**
  9395. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9396. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9397. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9398. * @param name The name of the class, case should be preserved
  9399. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9400. */
  9401. function className(name, module) {
  9402. return function (target) {
  9403. target["__bjsclassName__"] = name;
  9404. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9405. };
  9406. }
  9407. BABYLON.className = className;
  9408. /**
  9409. * An implementation of a loop for asynchronous functions.
  9410. */
  9411. var AsyncLoop = /** @class */ (function () {
  9412. /**
  9413. * Constroctor.
  9414. * @param iterations the number of iterations.
  9415. * @param _fn the function to run each iteration
  9416. * @param _successCallback the callback that will be called upon succesful execution
  9417. * @param offset starting offset.
  9418. */
  9419. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9420. if (offset === void 0) { offset = 0; }
  9421. this.iterations = iterations;
  9422. this._fn = _fn;
  9423. this._successCallback = _successCallback;
  9424. this.index = offset - 1;
  9425. this._done = false;
  9426. }
  9427. /**
  9428. * Execute the next iteration. Must be called after the last iteration was finished.
  9429. */
  9430. AsyncLoop.prototype.executeNext = function () {
  9431. if (!this._done) {
  9432. if (this.index + 1 < this.iterations) {
  9433. ++this.index;
  9434. this._fn(this);
  9435. }
  9436. else {
  9437. this.breakLoop();
  9438. }
  9439. }
  9440. };
  9441. /**
  9442. * Break the loop and run the success callback.
  9443. */
  9444. AsyncLoop.prototype.breakLoop = function () {
  9445. this._done = true;
  9446. this._successCallback();
  9447. };
  9448. /**
  9449. * Helper function
  9450. */
  9451. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9452. if (offset === void 0) { offset = 0; }
  9453. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9454. loop.executeNext();
  9455. return loop;
  9456. };
  9457. /**
  9458. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9459. * @param iterations total number of iterations
  9460. * @param syncedIterations number of synchronous iterations in each async iteration.
  9461. * @param fn the function to call each iteration.
  9462. * @param callback a success call back that will be called when iterating stops.
  9463. * @param breakFunction a break condition (optional)
  9464. * @param timeout timeout settings for the setTimeout function. default - 0.
  9465. * @constructor
  9466. */
  9467. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9468. if (timeout === void 0) { timeout = 0; }
  9469. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9470. if (breakFunction && breakFunction())
  9471. loop.breakLoop();
  9472. else {
  9473. setTimeout(function () {
  9474. for (var i = 0; i < syncedIterations; ++i) {
  9475. var iteration = (loop.index * syncedIterations) + i;
  9476. if (iteration >= iterations)
  9477. break;
  9478. fn(iteration);
  9479. if (breakFunction && breakFunction()) {
  9480. loop.breakLoop();
  9481. break;
  9482. }
  9483. }
  9484. loop.executeNext();
  9485. }, timeout);
  9486. }
  9487. }, callback);
  9488. };
  9489. return AsyncLoop;
  9490. }());
  9491. BABYLON.AsyncLoop = AsyncLoop;
  9492. })(BABYLON || (BABYLON = {}));
  9493. //# sourceMappingURL=babylon.tools.js.map
  9494. "use strict";
  9495. var BABYLON;
  9496. (function (BABYLON) {
  9497. var PromiseStates;
  9498. (function (PromiseStates) {
  9499. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9500. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9501. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9502. })(PromiseStates || (PromiseStates = {}));
  9503. var FulFillmentAgregator = /** @class */ (function () {
  9504. function FulFillmentAgregator() {
  9505. this.count = 0;
  9506. this.target = 0;
  9507. this.results = [];
  9508. }
  9509. return FulFillmentAgregator;
  9510. }());
  9511. var InternalPromise = /** @class */ (function () {
  9512. function InternalPromise(resolver) {
  9513. var _this = this;
  9514. this._state = PromiseStates.Pending;
  9515. this._children = new Array();
  9516. this._rejectWasConsumed = false;
  9517. if (!resolver) {
  9518. return;
  9519. }
  9520. try {
  9521. resolver(function (value) {
  9522. _this._resolve(value);
  9523. }, function (reason) {
  9524. _this._reject(reason);
  9525. });
  9526. }
  9527. catch (e) {
  9528. this._reject(e);
  9529. }
  9530. }
  9531. InternalPromise.prototype.catch = function (onRejected) {
  9532. return this.then(undefined, onRejected);
  9533. };
  9534. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9535. var _this = this;
  9536. var newPromise = new InternalPromise();
  9537. newPromise._onFulfilled = onFulfilled;
  9538. newPromise._onRejected = onRejected;
  9539. // Composition
  9540. this._children.push(newPromise);
  9541. if (this._state !== PromiseStates.Pending) {
  9542. BABYLON.Tools.SetImmediate(function () {
  9543. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9544. var returnedValue = newPromise._resolve(_this._result);
  9545. if (returnedValue !== undefined && returnedValue !== null) {
  9546. if (returnedValue._state !== undefined) {
  9547. var returnedPromise = returnedValue;
  9548. newPromise._children.push(returnedPromise);
  9549. newPromise = returnedPromise;
  9550. }
  9551. else {
  9552. newPromise._result = returnedValue;
  9553. }
  9554. }
  9555. }
  9556. else {
  9557. newPromise._reject(_this._reason);
  9558. }
  9559. });
  9560. }
  9561. return newPromise;
  9562. };
  9563. InternalPromise.prototype._moveChildren = function (children) {
  9564. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9565. if (this._state === PromiseStates.Fulfilled) {
  9566. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9567. var child = _b[_i];
  9568. child._resolve(this._result);
  9569. }
  9570. }
  9571. else if (this._state === PromiseStates.Rejected) {
  9572. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9573. var child = _d[_c];
  9574. child._reject(this._reason);
  9575. }
  9576. }
  9577. var _a;
  9578. };
  9579. InternalPromise.prototype._resolve = function (value) {
  9580. try {
  9581. this._state = PromiseStates.Fulfilled;
  9582. var returnedValue = null;
  9583. if (this._onFulfilled) {
  9584. returnedValue = this._onFulfilled(value);
  9585. }
  9586. if (returnedValue !== undefined && returnedValue !== null) {
  9587. if (returnedValue._state !== undefined) {
  9588. // Transmit children
  9589. var returnedPromise = returnedValue;
  9590. returnedPromise._moveChildren(this._children);
  9591. value = returnedPromise._result;
  9592. }
  9593. else {
  9594. value = returnedValue;
  9595. }
  9596. }
  9597. this._result = value;
  9598. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9599. var child = _a[_i];
  9600. child._resolve(value);
  9601. }
  9602. this._children.length = 0;
  9603. delete this._onFulfilled;
  9604. delete this._onRejected;
  9605. }
  9606. catch (e) {
  9607. this._reject(e, true);
  9608. }
  9609. };
  9610. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9611. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9612. this._state = PromiseStates.Rejected;
  9613. this._reason = reason;
  9614. if (this._onRejected && !onLocalThrow) {
  9615. try {
  9616. this._onRejected(reason);
  9617. this._rejectWasConsumed = true;
  9618. }
  9619. catch (e) {
  9620. reason = e;
  9621. }
  9622. }
  9623. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9624. var child = _a[_i];
  9625. if (this._rejectWasConsumed) {
  9626. child._resolve(null);
  9627. }
  9628. else {
  9629. child._reject(reason);
  9630. }
  9631. }
  9632. this._children.length = 0;
  9633. delete this._onFulfilled;
  9634. delete this._onRejected;
  9635. };
  9636. InternalPromise.resolve = function (value) {
  9637. var newPromise = new InternalPromise();
  9638. newPromise._resolve(value);
  9639. return newPromise;
  9640. };
  9641. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9642. promise.then(function (value) {
  9643. agregator.results[index] = value;
  9644. agregator.count++;
  9645. if (agregator.count === agregator.target) {
  9646. agregator.rootPromise._resolve(agregator.results);
  9647. }
  9648. return null;
  9649. }, function (reason) {
  9650. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9651. agregator.rootPromise._reject(reason);
  9652. }
  9653. });
  9654. };
  9655. InternalPromise.all = function (promises) {
  9656. var newPromise = new InternalPromise();
  9657. var agregator = new FulFillmentAgregator();
  9658. agregator.target = promises.length;
  9659. agregator.rootPromise = newPromise;
  9660. if (promises.length) {
  9661. for (var index = 0; index < promises.length; index++) {
  9662. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9663. }
  9664. }
  9665. else {
  9666. newPromise._resolve([]);
  9667. }
  9668. return newPromise;
  9669. };
  9670. InternalPromise.race = function (promises) {
  9671. var newPromise = new InternalPromise();
  9672. if (promises.length) {
  9673. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9674. var promise = promises_1[_i];
  9675. promise.then(function (value) {
  9676. if (newPromise) {
  9677. newPromise._resolve(value);
  9678. newPromise = null;
  9679. }
  9680. return null;
  9681. }, function (reason) {
  9682. if (newPromise) {
  9683. newPromise._reject(reason);
  9684. newPromise = null;
  9685. }
  9686. });
  9687. }
  9688. }
  9689. return newPromise;
  9690. };
  9691. return InternalPromise;
  9692. }());
  9693. /**
  9694. * Helper class that provides a small promise polyfill
  9695. */
  9696. var PromisePolyfill = /** @class */ (function () {
  9697. function PromisePolyfill() {
  9698. }
  9699. /**
  9700. * Static function used to check if the polyfill is required
  9701. * If this is the case then the function will inject the polyfill to window.Promise
  9702. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9703. */
  9704. PromisePolyfill.Apply = function (force) {
  9705. if (force === void 0) { force = false; }
  9706. if (force || typeof Promise === 'undefined') {
  9707. var root = window;
  9708. root.Promise = InternalPromise;
  9709. }
  9710. };
  9711. return PromisePolyfill;
  9712. }());
  9713. BABYLON.PromisePolyfill = PromisePolyfill;
  9714. })(BABYLON || (BABYLON = {}));
  9715. //# sourceMappingURL=babylon.promise.js.map
  9716. "use strict";
  9717. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9718. var BABYLON;
  9719. (function (BABYLON) {
  9720. /**
  9721. * Helper class to push actions to a pool of workers.
  9722. */
  9723. var WorkerPool = /** @class */ (function () {
  9724. /**
  9725. * Constructor
  9726. * @param workers Array of workers to use for actions
  9727. */
  9728. function WorkerPool(workers) {
  9729. this._pendingActions = new Array();
  9730. this._workerInfos = workers.map(function (worker) { return ({
  9731. worker: worker,
  9732. active: false
  9733. }); });
  9734. }
  9735. /**
  9736. * Terminates all workers and clears any pending actions.
  9737. */
  9738. WorkerPool.prototype.dispose = function () {
  9739. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9740. var workerInfo = _a[_i];
  9741. workerInfo.worker.terminate();
  9742. }
  9743. delete this._workerInfos;
  9744. delete this._pendingActions;
  9745. };
  9746. /**
  9747. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9748. * pended until a worker has completed its action.
  9749. * @param action The action to perform. Call onComplete when the action is complete.
  9750. */
  9751. WorkerPool.prototype.push = function (action) {
  9752. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9753. var workerInfo = _a[_i];
  9754. if (!workerInfo.active) {
  9755. this._execute(workerInfo, action);
  9756. return;
  9757. }
  9758. }
  9759. this._pendingActions.push(action);
  9760. };
  9761. WorkerPool.prototype._execute = function (workerInfo, action) {
  9762. var _this = this;
  9763. workerInfo.active = true;
  9764. action(workerInfo.worker, function () {
  9765. workerInfo.active = false;
  9766. var nextAction = _this._pendingActions.shift();
  9767. if (nextAction) {
  9768. _this._execute(workerInfo, nextAction);
  9769. }
  9770. });
  9771. };
  9772. return WorkerPool;
  9773. }());
  9774. BABYLON.WorkerPool = WorkerPool;
  9775. })(BABYLON || (BABYLON = {}));
  9776. //# sourceMappingURL=babylon.workerPool.js.map
  9777. "use strict";
  9778. var BABYLON;
  9779. (function (BABYLON) {
  9780. var _AlphaState = /** @class */ (function () {
  9781. /**
  9782. * Initializes the state.
  9783. */
  9784. function _AlphaState() {
  9785. this._isAlphaBlendDirty = false;
  9786. this._isBlendFunctionParametersDirty = false;
  9787. this._isBlendEquationParametersDirty = false;
  9788. this._isBlendConstantsDirty = false;
  9789. this._alphaBlend = false;
  9790. this._blendFunctionParameters = new Array(4);
  9791. this._blendEquationParameters = new Array(2);
  9792. this._blendConstants = new Array(4);
  9793. this.reset();
  9794. }
  9795. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9796. get: function () {
  9797. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9798. },
  9799. enumerable: true,
  9800. configurable: true
  9801. });
  9802. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9803. get: function () {
  9804. return this._alphaBlend;
  9805. },
  9806. set: function (value) {
  9807. if (this._alphaBlend === value) {
  9808. return;
  9809. }
  9810. this._alphaBlend = value;
  9811. this._isAlphaBlendDirty = true;
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9817. if (this._blendConstants[0] === r &&
  9818. this._blendConstants[1] === g &&
  9819. this._blendConstants[2] === b &&
  9820. this._blendConstants[3] === a) {
  9821. return;
  9822. }
  9823. this._blendConstants[0] = r;
  9824. this._blendConstants[1] = g;
  9825. this._blendConstants[2] = b;
  9826. this._blendConstants[3] = a;
  9827. this._isBlendConstantsDirty = true;
  9828. };
  9829. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9830. if (this._blendFunctionParameters[0] === value0 &&
  9831. this._blendFunctionParameters[1] === value1 &&
  9832. this._blendFunctionParameters[2] === value2 &&
  9833. this._blendFunctionParameters[3] === value3) {
  9834. return;
  9835. }
  9836. this._blendFunctionParameters[0] = value0;
  9837. this._blendFunctionParameters[1] = value1;
  9838. this._blendFunctionParameters[2] = value2;
  9839. this._blendFunctionParameters[3] = value3;
  9840. this._isBlendFunctionParametersDirty = true;
  9841. };
  9842. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9843. if (this._blendEquationParameters[0] === rgb &&
  9844. this._blendEquationParameters[1] === alpha) {
  9845. return;
  9846. }
  9847. this._blendEquationParameters[0] = rgb;
  9848. this._blendEquationParameters[1] = alpha;
  9849. this._isBlendEquationParametersDirty = true;
  9850. };
  9851. _AlphaState.prototype.reset = function () {
  9852. this._alphaBlend = false;
  9853. this._blendFunctionParameters[0] = null;
  9854. this._blendFunctionParameters[1] = null;
  9855. this._blendFunctionParameters[2] = null;
  9856. this._blendFunctionParameters[3] = null;
  9857. this._blendEquationParameters[0] = null;
  9858. this._blendEquationParameters[1] = null;
  9859. this._blendConstants[0] = null;
  9860. this._blendConstants[1] = null;
  9861. this._blendConstants[2] = null;
  9862. this._blendConstants[3] = null;
  9863. this._isAlphaBlendDirty = true;
  9864. this._isBlendFunctionParametersDirty = false;
  9865. this._isBlendEquationParametersDirty = false;
  9866. this._isBlendConstantsDirty = false;
  9867. };
  9868. _AlphaState.prototype.apply = function (gl) {
  9869. if (!this.isDirty) {
  9870. return;
  9871. }
  9872. // Alpha blend
  9873. if (this._isAlphaBlendDirty) {
  9874. if (this._alphaBlend) {
  9875. gl.enable(gl.BLEND);
  9876. }
  9877. else {
  9878. gl.disable(gl.BLEND);
  9879. }
  9880. this._isAlphaBlendDirty = false;
  9881. }
  9882. // Alpha function
  9883. if (this._isBlendFunctionParametersDirty) {
  9884. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9885. this._isBlendFunctionParametersDirty = false;
  9886. }
  9887. // Alpha equation
  9888. if (this._isBlendEquationParametersDirty) {
  9889. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9890. this._isBlendEquationParametersDirty = false;
  9891. }
  9892. // Constants
  9893. if (this._isBlendConstantsDirty) {
  9894. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9895. this._isBlendConstantsDirty = false;
  9896. }
  9897. };
  9898. return _AlphaState;
  9899. }());
  9900. BABYLON._AlphaState = _AlphaState;
  9901. })(BABYLON || (BABYLON = {}));
  9902. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9903. "use strict";
  9904. var BABYLON;
  9905. (function (BABYLON) {
  9906. var _DepthCullingState = /** @class */ (function () {
  9907. /**
  9908. * Initializes the state.
  9909. */
  9910. function _DepthCullingState() {
  9911. this._isDepthTestDirty = false;
  9912. this._isDepthMaskDirty = false;
  9913. this._isDepthFuncDirty = false;
  9914. this._isCullFaceDirty = false;
  9915. this._isCullDirty = false;
  9916. this._isZOffsetDirty = false;
  9917. this._isFrontFaceDirty = false;
  9918. this.reset();
  9919. }
  9920. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9921. get: function () {
  9922. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9923. },
  9924. enumerable: true,
  9925. configurable: true
  9926. });
  9927. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9928. get: function () {
  9929. return this._zOffset;
  9930. },
  9931. set: function (value) {
  9932. if (this._zOffset === value) {
  9933. return;
  9934. }
  9935. this._zOffset = value;
  9936. this._isZOffsetDirty = true;
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9942. get: function () {
  9943. return this._cullFace;
  9944. },
  9945. set: function (value) {
  9946. if (this._cullFace === value) {
  9947. return;
  9948. }
  9949. this._cullFace = value;
  9950. this._isCullFaceDirty = true;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9956. get: function () {
  9957. return this._cull;
  9958. },
  9959. set: function (value) {
  9960. if (this._cull === value) {
  9961. return;
  9962. }
  9963. this._cull = value;
  9964. this._isCullDirty = true;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9970. get: function () {
  9971. return this._depthFunc;
  9972. },
  9973. set: function (value) {
  9974. if (this._depthFunc === value) {
  9975. return;
  9976. }
  9977. this._depthFunc = value;
  9978. this._isDepthFuncDirty = true;
  9979. },
  9980. enumerable: true,
  9981. configurable: true
  9982. });
  9983. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9984. get: function () {
  9985. return this._depthMask;
  9986. },
  9987. set: function (value) {
  9988. if (this._depthMask === value) {
  9989. return;
  9990. }
  9991. this._depthMask = value;
  9992. this._isDepthMaskDirty = true;
  9993. },
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9998. get: function () {
  9999. return this._depthTest;
  10000. },
  10001. set: function (value) {
  10002. if (this._depthTest === value) {
  10003. return;
  10004. }
  10005. this._depthTest = value;
  10006. this._isDepthTestDirty = true;
  10007. },
  10008. enumerable: true,
  10009. configurable: true
  10010. });
  10011. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10012. get: function () {
  10013. return this._frontFace;
  10014. },
  10015. set: function (value) {
  10016. if (this._frontFace === value) {
  10017. return;
  10018. }
  10019. this._frontFace = value;
  10020. this._isFrontFaceDirty = true;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. _DepthCullingState.prototype.reset = function () {
  10026. this._depthMask = true;
  10027. this._depthTest = true;
  10028. this._depthFunc = null;
  10029. this._cullFace = null;
  10030. this._cull = null;
  10031. this._zOffset = 0;
  10032. this._frontFace = null;
  10033. this._isDepthTestDirty = true;
  10034. this._isDepthMaskDirty = true;
  10035. this._isDepthFuncDirty = false;
  10036. this._isCullFaceDirty = false;
  10037. this._isCullDirty = false;
  10038. this._isZOffsetDirty = false;
  10039. this._isFrontFaceDirty = false;
  10040. };
  10041. _DepthCullingState.prototype.apply = function (gl) {
  10042. if (!this.isDirty) {
  10043. return;
  10044. }
  10045. // Cull
  10046. if (this._isCullDirty) {
  10047. if (this.cull) {
  10048. gl.enable(gl.CULL_FACE);
  10049. }
  10050. else {
  10051. gl.disable(gl.CULL_FACE);
  10052. }
  10053. this._isCullDirty = false;
  10054. }
  10055. // Cull face
  10056. if (this._isCullFaceDirty) {
  10057. gl.cullFace(this.cullFace);
  10058. this._isCullFaceDirty = false;
  10059. }
  10060. // Depth mask
  10061. if (this._isDepthMaskDirty) {
  10062. gl.depthMask(this.depthMask);
  10063. this._isDepthMaskDirty = false;
  10064. }
  10065. // Depth test
  10066. if (this._isDepthTestDirty) {
  10067. if (this.depthTest) {
  10068. gl.enable(gl.DEPTH_TEST);
  10069. }
  10070. else {
  10071. gl.disable(gl.DEPTH_TEST);
  10072. }
  10073. this._isDepthTestDirty = false;
  10074. }
  10075. // Depth func
  10076. if (this._isDepthFuncDirty) {
  10077. gl.depthFunc(this.depthFunc);
  10078. this._isDepthFuncDirty = false;
  10079. }
  10080. // zOffset
  10081. if (this._isZOffsetDirty) {
  10082. if (this.zOffset) {
  10083. gl.enable(gl.POLYGON_OFFSET_FILL);
  10084. gl.polygonOffset(this.zOffset, 0);
  10085. }
  10086. else {
  10087. gl.disable(gl.POLYGON_OFFSET_FILL);
  10088. }
  10089. this._isZOffsetDirty = false;
  10090. }
  10091. // Front face
  10092. if (this._isFrontFaceDirty) {
  10093. gl.frontFace(this.frontFace);
  10094. this._isFrontFaceDirty = false;
  10095. }
  10096. };
  10097. return _DepthCullingState;
  10098. }());
  10099. BABYLON._DepthCullingState = _DepthCullingState;
  10100. })(BABYLON || (BABYLON = {}));
  10101. //# sourceMappingURL=babylon.depthCullingState.js.map
  10102. "use strict";
  10103. var BABYLON;
  10104. (function (BABYLON) {
  10105. var _StencilState = /** @class */ (function () {
  10106. function _StencilState() {
  10107. this._isStencilTestDirty = false;
  10108. this._isStencilMaskDirty = false;
  10109. this._isStencilFuncDirty = false;
  10110. this._isStencilOpDirty = false;
  10111. this.reset();
  10112. }
  10113. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10114. get: function () {
  10115. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10116. },
  10117. enumerable: true,
  10118. configurable: true
  10119. });
  10120. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10121. get: function () {
  10122. return this._stencilFunc;
  10123. },
  10124. set: function (value) {
  10125. if (this._stencilFunc === value) {
  10126. return;
  10127. }
  10128. this._stencilFunc = value;
  10129. this._isStencilFuncDirty = true;
  10130. },
  10131. enumerable: true,
  10132. configurable: true
  10133. });
  10134. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10135. get: function () {
  10136. return this._stencilFuncRef;
  10137. },
  10138. set: function (value) {
  10139. if (this._stencilFuncRef === value) {
  10140. return;
  10141. }
  10142. this._stencilFuncRef = value;
  10143. this._isStencilFuncDirty = true;
  10144. },
  10145. enumerable: true,
  10146. configurable: true
  10147. });
  10148. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10149. get: function () {
  10150. return this._stencilFuncMask;
  10151. },
  10152. set: function (value) {
  10153. if (this._stencilFuncMask === value) {
  10154. return;
  10155. }
  10156. this._stencilFuncMask = value;
  10157. this._isStencilFuncDirty = true;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10163. get: function () {
  10164. return this._stencilOpStencilFail;
  10165. },
  10166. set: function (value) {
  10167. if (this._stencilOpStencilFail === value) {
  10168. return;
  10169. }
  10170. this._stencilOpStencilFail = value;
  10171. this._isStencilOpDirty = true;
  10172. },
  10173. enumerable: true,
  10174. configurable: true
  10175. });
  10176. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10177. get: function () {
  10178. return this._stencilOpDepthFail;
  10179. },
  10180. set: function (value) {
  10181. if (this._stencilOpDepthFail === value) {
  10182. return;
  10183. }
  10184. this._stencilOpDepthFail = value;
  10185. this._isStencilOpDirty = true;
  10186. },
  10187. enumerable: true,
  10188. configurable: true
  10189. });
  10190. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10191. get: function () {
  10192. return this._stencilOpStencilDepthPass;
  10193. },
  10194. set: function (value) {
  10195. if (this._stencilOpStencilDepthPass === value) {
  10196. return;
  10197. }
  10198. this._stencilOpStencilDepthPass = value;
  10199. this._isStencilOpDirty = true;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10205. get: function () {
  10206. return this._stencilMask;
  10207. },
  10208. set: function (value) {
  10209. if (this._stencilMask === value) {
  10210. return;
  10211. }
  10212. this._stencilMask = value;
  10213. this._isStencilMaskDirty = true;
  10214. },
  10215. enumerable: true,
  10216. configurable: true
  10217. });
  10218. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10219. get: function () {
  10220. return this._stencilTest;
  10221. },
  10222. set: function (value) {
  10223. if (this._stencilTest === value) {
  10224. return;
  10225. }
  10226. this._stencilTest = value;
  10227. this._isStencilTestDirty = true;
  10228. },
  10229. enumerable: true,
  10230. configurable: true
  10231. });
  10232. _StencilState.prototype.reset = function () {
  10233. this._stencilTest = false;
  10234. this._stencilMask = 0xFF;
  10235. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10236. this._stencilFuncRef = 1;
  10237. this._stencilFuncMask = 0xFF;
  10238. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10239. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10240. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10241. this._isStencilTestDirty = true;
  10242. this._isStencilMaskDirty = true;
  10243. this._isStencilFuncDirty = true;
  10244. this._isStencilOpDirty = true;
  10245. };
  10246. _StencilState.prototype.apply = function (gl) {
  10247. if (!this.isDirty) {
  10248. return;
  10249. }
  10250. // Stencil test
  10251. if (this._isStencilTestDirty) {
  10252. if (this.stencilTest) {
  10253. gl.enable(gl.STENCIL_TEST);
  10254. }
  10255. else {
  10256. gl.disable(gl.STENCIL_TEST);
  10257. }
  10258. this._isStencilTestDirty = false;
  10259. }
  10260. // Stencil mask
  10261. if (this._isStencilMaskDirty) {
  10262. gl.stencilMask(this.stencilMask);
  10263. this._isStencilMaskDirty = false;
  10264. }
  10265. // Stencil func
  10266. if (this._isStencilFuncDirty) {
  10267. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10268. this._isStencilFuncDirty = false;
  10269. }
  10270. // Stencil op
  10271. if (this._isStencilOpDirty) {
  10272. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10273. this._isStencilOpDirty = false;
  10274. }
  10275. };
  10276. return _StencilState;
  10277. }());
  10278. BABYLON._StencilState = _StencilState;
  10279. })(BABYLON || (BABYLON = {}));
  10280. //# sourceMappingURL=babylon.stencilState.js.map
  10281. "use strict";
  10282. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10283. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10284. s = arguments[i];
  10285. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10286. t[p] = s[p];
  10287. }
  10288. return t;
  10289. };
  10290. var BABYLON;
  10291. (function (BABYLON) {
  10292. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10293. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10294. };
  10295. var compileRawShader = function (gl, source, type) {
  10296. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10297. gl.shaderSource(shader, source);
  10298. gl.compileShader(shader);
  10299. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10300. var log = gl.getShaderInfoLog(shader);
  10301. if (log) {
  10302. throw new Error(log);
  10303. }
  10304. }
  10305. if (!shader) {
  10306. throw new Error("Something went wrong while compile the shader.");
  10307. }
  10308. return shader;
  10309. };
  10310. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10311. var magFilter = gl.NEAREST;
  10312. var minFilter = gl.NEAREST;
  10313. switch (samplingMode) {
  10314. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10315. magFilter = gl.LINEAR;
  10316. if (generateMipMaps) {
  10317. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10318. }
  10319. else {
  10320. minFilter = gl.LINEAR;
  10321. }
  10322. break;
  10323. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10324. magFilter = gl.LINEAR;
  10325. if (generateMipMaps) {
  10326. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10327. }
  10328. else {
  10329. minFilter = gl.LINEAR;
  10330. }
  10331. break;
  10332. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10333. magFilter = gl.NEAREST;
  10334. if (generateMipMaps) {
  10335. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10336. }
  10337. else {
  10338. minFilter = gl.NEAREST;
  10339. }
  10340. break;
  10341. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10342. magFilter = gl.NEAREST;
  10343. if (generateMipMaps) {
  10344. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10345. }
  10346. else {
  10347. minFilter = gl.NEAREST;
  10348. }
  10349. break;
  10350. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10351. magFilter = gl.NEAREST;
  10352. if (generateMipMaps) {
  10353. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10354. }
  10355. else {
  10356. minFilter = gl.LINEAR;
  10357. }
  10358. break;
  10359. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10360. magFilter = gl.NEAREST;
  10361. if (generateMipMaps) {
  10362. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10363. }
  10364. else {
  10365. minFilter = gl.LINEAR;
  10366. }
  10367. break;
  10368. case BABYLON.Texture.NEAREST_LINEAR:
  10369. magFilter = gl.NEAREST;
  10370. minFilter = gl.LINEAR;
  10371. break;
  10372. case BABYLON.Texture.NEAREST_NEAREST:
  10373. magFilter = gl.NEAREST;
  10374. minFilter = gl.NEAREST;
  10375. break;
  10376. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10377. magFilter = gl.LINEAR;
  10378. if (generateMipMaps) {
  10379. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10380. }
  10381. else {
  10382. minFilter = gl.NEAREST;
  10383. }
  10384. break;
  10385. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10386. magFilter = gl.LINEAR;
  10387. if (generateMipMaps) {
  10388. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10389. }
  10390. else {
  10391. minFilter = gl.NEAREST;
  10392. }
  10393. break;
  10394. case BABYLON.Texture.LINEAR_LINEAR:
  10395. magFilter = gl.LINEAR;
  10396. minFilter = gl.LINEAR;
  10397. break;
  10398. case BABYLON.Texture.LINEAR_NEAREST:
  10399. magFilter = gl.LINEAR;
  10400. minFilter = gl.NEAREST;
  10401. break;
  10402. }
  10403. return {
  10404. min: minFilter,
  10405. mag: magFilter
  10406. };
  10407. };
  10408. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10409. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10410. var img;
  10411. var onload = function () {
  10412. loadedImages[index] = img;
  10413. loadedImages._internalCount++;
  10414. if (scene) {
  10415. scene._removePendingData(img);
  10416. }
  10417. if (loadedImages._internalCount === 6) {
  10418. onfinish(loadedImages);
  10419. }
  10420. };
  10421. var onerror = function (message, exception) {
  10422. if (scene) {
  10423. scene._removePendingData(img);
  10424. }
  10425. if (onErrorCallBack) {
  10426. onErrorCallBack(message, exception);
  10427. }
  10428. };
  10429. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10430. if (scene) {
  10431. scene._addPendingData(img);
  10432. }
  10433. };
  10434. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10435. if (onError === void 0) { onError = null; }
  10436. var loadedImages = [];
  10437. loadedImages._internalCount = 0;
  10438. for (var index = 0; index < 6; index++) {
  10439. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10440. }
  10441. };
  10442. var BufferPointer = /** @class */ (function () {
  10443. function BufferPointer() {
  10444. }
  10445. return BufferPointer;
  10446. }());
  10447. /**
  10448. * Interface for attribute information associated with buffer instanciation
  10449. */
  10450. var InstancingAttributeInfo = /** @class */ (function () {
  10451. function InstancingAttributeInfo() {
  10452. }
  10453. return InstancingAttributeInfo;
  10454. }());
  10455. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10456. /**
  10457. * Define options used to create a render target texture
  10458. */
  10459. var RenderTargetCreationOptions = /** @class */ (function () {
  10460. function RenderTargetCreationOptions() {
  10461. }
  10462. return RenderTargetCreationOptions;
  10463. }());
  10464. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10465. /**
  10466. * Define options used to create a depth texture
  10467. */
  10468. var DepthTextureCreationOptions = /** @class */ (function () {
  10469. function DepthTextureCreationOptions() {
  10470. }
  10471. return DepthTextureCreationOptions;
  10472. }());
  10473. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10474. /**
  10475. * Class used to describe the capabilities of the engine relatively to the current browser
  10476. */
  10477. var EngineCapabilities = /** @class */ (function () {
  10478. function EngineCapabilities() {
  10479. }
  10480. return EngineCapabilities;
  10481. }());
  10482. BABYLON.EngineCapabilities = EngineCapabilities;
  10483. /**
  10484. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10485. */
  10486. var Engine = /** @class */ (function () {
  10487. /**
  10488. * Creates a new engine
  10489. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10490. * @param antialias defines enable antialiasing (default: false)
  10491. * @param options defines further options to be sent to the getContext() function
  10492. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10493. */
  10494. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10495. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10496. var _this = this;
  10497. // Public members
  10498. /**
  10499. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10500. */
  10501. this.forcePOTTextures = false;
  10502. /**
  10503. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10504. */
  10505. this.isFullscreen = false;
  10506. /**
  10507. * Gets a boolean indicating if the pointer is currently locked
  10508. */
  10509. this.isPointerLock = false;
  10510. /**
  10511. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10512. */
  10513. this.cullBackFaces = true;
  10514. /**
  10515. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10516. */
  10517. this.renderEvenInBackground = true;
  10518. /**
  10519. * Gets or sets a boolean indicating that cache can be kept between frames
  10520. */
  10521. this.preventCacheWipeBetweenFrames = false;
  10522. /**
  10523. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10524. **/
  10525. this.enableOfflineSupport = false;
  10526. /**
  10527. * Gets the list of created scenes
  10528. */
  10529. this.scenes = new Array();
  10530. /**
  10531. * Gets the list of created postprocesses
  10532. */
  10533. this.postProcesses = new Array();
  10534. // Observables
  10535. /**
  10536. * Observable event triggered each time the rendering canvas is resized
  10537. */
  10538. this.onResizeObservable = new BABYLON.Observable();
  10539. /**
  10540. * Observable event triggered each time the canvas loses focus
  10541. */
  10542. this.onCanvasBlurObservable = new BABYLON.Observable();
  10543. /**
  10544. * Observable event triggered each time the canvas gains focus
  10545. */
  10546. this.onCanvasFocusObservable = new BABYLON.Observable();
  10547. /**
  10548. * Observable event triggered each time the canvas receives pointerout event
  10549. */
  10550. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10551. /**
  10552. * Observable event triggered before each texture is initialized
  10553. */
  10554. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10555. //WebVR
  10556. this._vrDisplay = undefined;
  10557. this._vrSupported = false;
  10558. this._vrExclusivePointerMode = false;
  10559. // Uniform buffers list
  10560. /**
  10561. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10562. */
  10563. this.disableUniformBuffers = false;
  10564. /** @ignore */
  10565. this._uniformBuffers = new Array();
  10566. // Observables
  10567. /**
  10568. * Observable raised when the engine begins a new frame
  10569. */
  10570. this.onBeginFrameObservable = new BABYLON.Observable();
  10571. /**
  10572. * Observable raised when the engine ends the current frame
  10573. */
  10574. this.onEndFrameObservable = new BABYLON.Observable();
  10575. /**
  10576. * Observable raised when the engine is about to compile a shader
  10577. */
  10578. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10579. /**
  10580. * Observable raised when the engine has jsut compiled a shader
  10581. */
  10582. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10583. this._windowIsBackground = false;
  10584. this._webGLVersion = 1.0;
  10585. /** @ignore */
  10586. this._badOS = false;
  10587. /** @ignore */
  10588. this._badDesktopOS = false;
  10589. /**
  10590. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10591. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  10592. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  10593. */
  10594. this.disableTextureBindingOptimization = false;
  10595. /**
  10596. * Observable signaled when VR display mode changes
  10597. */
  10598. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10599. /**
  10600. * Observable signaled when VR request present is complete
  10601. */
  10602. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10603. /**
  10604. * Observable signaled when VR request present starts
  10605. */
  10606. this.onVRRequestPresentStart = new BABYLON.Observable();
  10607. this._colorWrite = true;
  10608. /** @ignore */
  10609. this._drawCalls = new BABYLON.PerfCounter();
  10610. /** @ignore */
  10611. this._textureCollisions = new BABYLON.PerfCounter();
  10612. this._renderingQueueLaunched = false;
  10613. this._activeRenderLoops = new Array();
  10614. // Deterministic lockstepMaxSteps
  10615. this._deterministicLockstep = false;
  10616. this._lockstepMaxSteps = 4;
  10617. // Lost context
  10618. /**
  10619. * Observable signaled when a context lost event is raised
  10620. */
  10621. this.onContextLostObservable = new BABYLON.Observable();
  10622. /**
  10623. * Observable signaled when a context restored event is raised
  10624. */
  10625. this.onContextRestoredObservable = new BABYLON.Observable();
  10626. this._contextWasLost = false;
  10627. this._doNotHandleContextLost = false;
  10628. // FPS
  10629. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10630. this._fps = 60;
  10631. this._deltaTime = 0;
  10632. /**
  10633. * Turn this value on if you want to pause FPS computation when in background
  10634. */
  10635. this.disablePerformanceMonitorInBackground = false;
  10636. // States
  10637. /** @ignore */
  10638. this._depthCullingState = new BABYLON._DepthCullingState();
  10639. /** @ignore */
  10640. this._stencilState = new BABYLON._StencilState();
  10641. /** @ignore */
  10642. this._alphaState = new BABYLON._AlphaState();
  10643. /** @ignore */
  10644. this._alphaMode = Engine.ALPHA_DISABLE;
  10645. // Cache
  10646. this._internalTexturesCache = new Array();
  10647. /** @ignore */
  10648. this._activeChannel = 0;
  10649. this._currentTextureChannel = -1;
  10650. /** @ignore */
  10651. this._boundTexturesCache = {};
  10652. this._compiledEffects = {};
  10653. this._vertexAttribArraysEnabled = [];
  10654. this._uintIndicesCurrentlySet = false;
  10655. this._currentBoundBuffer = new Array();
  10656. this._currentBufferPointers = new Array();
  10657. this._currentInstanceLocations = new Array();
  10658. this._currentInstanceBuffers = new Array();
  10659. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10660. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10661. this._vaoRecordInProgress = false;
  10662. this._mustWipeVertexAttributes = false;
  10663. this._nextFreeTextureSlots = new Array();
  10664. this._maxSimultaneousTextures = 0;
  10665. this._activeRequests = new Array();
  10666. // Hardware supported Compressed Textures
  10667. this._texturesSupported = new Array();
  10668. this._onVRFullScreenTriggered = function () {
  10669. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10670. //get the old size before we change
  10671. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10672. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10673. //get the width and height, change the render size
  10674. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10675. _this.setHardwareScalingLevel(1);
  10676. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10677. }
  10678. else {
  10679. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10680. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10681. }
  10682. };
  10683. this._boundUniforms = {};
  10684. // Register promises
  10685. BABYLON.PromisePolyfill.Apply();
  10686. var canvas = null;
  10687. Engine.Instances.push(this);
  10688. if (!canvasOrContext) {
  10689. return;
  10690. }
  10691. options = options || {};
  10692. if (canvasOrContext.getContext) {
  10693. canvas = canvasOrContext;
  10694. this._renderingCanvas = canvas;
  10695. if (antialias != null) {
  10696. options.antialias = antialias;
  10697. }
  10698. if (options.deterministicLockstep === undefined) {
  10699. options.deterministicLockstep = false;
  10700. }
  10701. if (options.lockstepMaxSteps === undefined) {
  10702. options.lockstepMaxSteps = 4;
  10703. }
  10704. if (options.preserveDrawingBuffer === undefined) {
  10705. options.preserveDrawingBuffer = false;
  10706. }
  10707. if (options.audioEngine === undefined) {
  10708. options.audioEngine = true;
  10709. }
  10710. if (options.stencil === undefined) {
  10711. options.stencil = true;
  10712. }
  10713. this._deterministicLockstep = options.deterministicLockstep;
  10714. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10715. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10716. // Exceptions
  10717. if (navigator && navigator.userAgent) {
  10718. var ua = navigator.userAgent;
  10719. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10720. var exception = _a[_i];
  10721. var key = exception.key;
  10722. var targets = exception.targets;
  10723. if (ua.indexOf(key) > -1) {
  10724. if (exception.capture && exception.captureConstraint) {
  10725. var capture = exception.capture;
  10726. var constraint = exception.captureConstraint;
  10727. var regex = new RegExp(capture);
  10728. var matches = regex.exec(ua);
  10729. if (matches && matches.length > 0) {
  10730. var capturedValue = parseInt(matches[matches.length - 1]);
  10731. if (capturedValue >= constraint) {
  10732. continue;
  10733. }
  10734. }
  10735. }
  10736. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10737. var target = targets_1[_b];
  10738. switch (target) {
  10739. case "uniformBuffer":
  10740. this.disableUniformBuffers = true;
  10741. break;
  10742. case "textureBindingOptimization":
  10743. this.disableTextureBindingOptimization = true;
  10744. break;
  10745. }
  10746. }
  10747. }
  10748. }
  10749. }
  10750. // GL
  10751. if (!options.disableWebGL2Support) {
  10752. try {
  10753. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10754. if (this._gl) {
  10755. this._webGLVersion = 2.0;
  10756. }
  10757. }
  10758. catch (e) {
  10759. // Do nothing
  10760. }
  10761. }
  10762. if (!this._gl) {
  10763. if (!canvas) {
  10764. throw new Error("The provided canvas is null or undefined.");
  10765. }
  10766. try {
  10767. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10768. }
  10769. catch (e) {
  10770. throw new Error("WebGL not supported");
  10771. }
  10772. }
  10773. if (!this._gl) {
  10774. throw new Error("WebGL not supported");
  10775. }
  10776. this._onCanvasFocus = function () {
  10777. _this.onCanvasFocusObservable.notifyObservers(_this);
  10778. };
  10779. this._onCanvasBlur = function () {
  10780. _this.onCanvasBlurObservable.notifyObservers(_this);
  10781. };
  10782. canvas.addEventListener("focus", this._onCanvasFocus);
  10783. canvas.addEventListener("blur", this._onCanvasBlur);
  10784. this._onBlur = function () {
  10785. if (_this.disablePerformanceMonitorInBackground) {
  10786. _this._performanceMonitor.disable();
  10787. }
  10788. _this._windowIsBackground = true;
  10789. };
  10790. this._onFocus = function () {
  10791. if (_this.disablePerformanceMonitorInBackground) {
  10792. _this._performanceMonitor.enable();
  10793. }
  10794. _this._windowIsBackground = false;
  10795. };
  10796. this._onCanvasPointerOut = function (ev) {
  10797. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10798. };
  10799. window.addEventListener("blur", this._onBlur);
  10800. window.addEventListener("focus", this._onFocus);
  10801. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10802. // Context lost
  10803. if (!this._doNotHandleContextLost) {
  10804. this._onContextLost = function (evt) {
  10805. evt.preventDefault();
  10806. _this._contextWasLost = true;
  10807. BABYLON.Tools.Warn("WebGL context lost.");
  10808. _this.onContextLostObservable.notifyObservers(_this);
  10809. };
  10810. this._onContextRestored = function (evt) {
  10811. // Adding a timeout to avoid race condition at browser level
  10812. setTimeout(function () {
  10813. // Rebuild gl context
  10814. _this._initGLContext();
  10815. // Rebuild effects
  10816. _this._rebuildEffects();
  10817. // Rebuild textures
  10818. _this._rebuildInternalTextures();
  10819. // Rebuild buffers
  10820. _this._rebuildBuffers();
  10821. // Cache
  10822. _this.wipeCaches(true);
  10823. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10824. _this.onContextRestoredObservable.notifyObservers(_this);
  10825. _this._contextWasLost = false;
  10826. }, 0);
  10827. };
  10828. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10829. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10830. }
  10831. }
  10832. else {
  10833. this._gl = canvasOrContext;
  10834. this._renderingCanvas = this._gl.canvas;
  10835. if (this._gl.renderbufferStorageMultisample) {
  10836. this._webGLVersion = 2.0;
  10837. }
  10838. options.stencil = this._gl.getContextAttributes().stencil;
  10839. }
  10840. // Viewport
  10841. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10842. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10843. this.resize();
  10844. this._isStencilEnable = options.stencil ? true : false;
  10845. this._initGLContext();
  10846. if (canvas) {
  10847. // Fullscreen
  10848. this._onFullscreenChange = function () {
  10849. if (document.fullscreen !== undefined) {
  10850. _this.isFullscreen = document.fullscreen;
  10851. }
  10852. else if (document.mozFullScreen !== undefined) {
  10853. _this.isFullscreen = document.mozFullScreen;
  10854. }
  10855. else if (document.webkitIsFullScreen !== undefined) {
  10856. _this.isFullscreen = document.webkitIsFullScreen;
  10857. }
  10858. else if (document.msIsFullScreen !== undefined) {
  10859. _this.isFullscreen = document.msIsFullScreen;
  10860. }
  10861. // Pointer lock
  10862. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10863. canvas.requestPointerLock = canvas.requestPointerLock ||
  10864. canvas.msRequestPointerLock ||
  10865. canvas.mozRequestPointerLock ||
  10866. canvas.webkitRequestPointerLock;
  10867. if (canvas.requestPointerLock) {
  10868. canvas.requestPointerLock();
  10869. }
  10870. }
  10871. };
  10872. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10873. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10874. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10875. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10876. // Pointer lock
  10877. this._onPointerLockChange = function () {
  10878. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10879. document.webkitPointerLockElement === canvas ||
  10880. document.msPointerLockElement === canvas ||
  10881. document.pointerLockElement === canvas);
  10882. };
  10883. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10884. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10885. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10886. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10887. this._onVRDisplayPointerRestricted = function () {
  10888. if (canvas) {
  10889. canvas.requestPointerLock();
  10890. }
  10891. };
  10892. this._onVRDisplayPointerUnrestricted = function () {
  10893. document.exitPointerLock();
  10894. };
  10895. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10896. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10897. }
  10898. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10899. Engine.audioEngine = new BABYLON.AudioEngine();
  10900. }
  10901. // Prepare buffer pointers
  10902. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10903. this._currentBufferPointers[i] = new BufferPointer();
  10904. }
  10905. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10906. // Load WebVR Devices
  10907. if (options.autoEnableWebVR) {
  10908. this.initWebVR();
  10909. }
  10910. // Detect if we are running on a faulty buggy OS.
  10911. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10912. // Detect if we are running on a faulty buggy desktop OS.
  10913. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10914. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10915. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10916. }
  10917. Object.defineProperty(Engine, "LastCreatedEngine", {
  10918. /**
  10919. * Gets the latest created engine
  10920. */
  10921. get: function () {
  10922. if (Engine.Instances.length === 0) {
  10923. return null;
  10924. }
  10925. return Engine.Instances[Engine.Instances.length - 1];
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Engine, "LastCreatedScene", {
  10931. /**
  10932. * Gets the latest created scene
  10933. */
  10934. get: function () {
  10935. var lastCreatedEngine = Engine.LastCreatedEngine;
  10936. if (!lastCreatedEngine) {
  10937. return null;
  10938. }
  10939. if (lastCreatedEngine.scenes.length === 0) {
  10940. return null;
  10941. }
  10942. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. /**
  10948. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10949. * @param flag defines which part of the materials must be marked as dirty
  10950. * @param predicate defines a predicate used to filter which materials should be affected
  10951. */
  10952. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10953. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10954. var engine = Engine.Instances[engineIndex];
  10955. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10956. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10957. }
  10958. }
  10959. };
  10960. Object.defineProperty(Engine, "NEVER", {
  10961. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  10962. get: function () {
  10963. return Engine._NEVER;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "ALWAYS", {
  10969. /** 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 */
  10970. get: function () {
  10971. return Engine._ALWAYS;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine, "LESS", {
  10977. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  10978. get: function () {
  10979. return Engine._LESS;
  10980. },
  10981. enumerable: true,
  10982. configurable: true
  10983. });
  10984. Object.defineProperty(Engine, "EQUAL", {
  10985. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  10986. get: function () {
  10987. return Engine._EQUAL;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(Engine, "LEQUAL", {
  10993. /** 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 */
  10994. get: function () {
  10995. return Engine._LEQUAL;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine, "GREATER", {
  11001. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11002. get: function () {
  11003. return Engine._GREATER;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(Engine, "GEQUAL", {
  11009. /** 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 */
  11010. get: function () {
  11011. return Engine._GEQUAL;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(Engine, "NOTEQUAL", {
  11017. /** 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 */
  11018. get: function () {
  11019. return Engine._NOTEQUAL;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine, "KEEP", {
  11025. /** Passed to stencilOperation to specify that stencil value must be kept */
  11026. get: function () {
  11027. return Engine._KEEP;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "REPLACE", {
  11033. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11034. get: function () {
  11035. return Engine._REPLACE;
  11036. },
  11037. enumerable: true,
  11038. configurable: true
  11039. });
  11040. Object.defineProperty(Engine, "INCR", {
  11041. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11042. get: function () {
  11043. return Engine._INCR;
  11044. },
  11045. enumerable: true,
  11046. configurable: true
  11047. });
  11048. Object.defineProperty(Engine, "DECR", {
  11049. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11050. get: function () {
  11051. return Engine._DECR;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine, "INVERT", {
  11057. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11058. get: function () {
  11059. return Engine._INVERT;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(Engine, "INCR_WRAP", {
  11065. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11066. get: function () {
  11067. return Engine._INCR_WRAP;
  11068. },
  11069. enumerable: true,
  11070. configurable: true
  11071. });
  11072. Object.defineProperty(Engine, "DECR_WRAP", {
  11073. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11074. get: function () {
  11075. return Engine._DECR_WRAP;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11081. // Alpha
  11082. /** Defines that alpha blending is disabled */
  11083. get: function () {
  11084. return Engine._ALPHA_DISABLE;
  11085. },
  11086. enumerable: true,
  11087. configurable: true
  11088. });
  11089. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11090. /** Defines that alpha blending to SRC + DEST */
  11091. get: function () {
  11092. return Engine._ALPHA_ONEONE;
  11093. },
  11094. enumerable: true,
  11095. configurable: true
  11096. });
  11097. Object.defineProperty(Engine, "ALPHA_ADD", {
  11098. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11099. get: function () {
  11100. return Engine._ALPHA_ADD;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11106. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11107. get: function () {
  11108. return Engine._ALPHA_COMBINE;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11114. /** Defines that alpha blending to DEST - SRC * DEST */
  11115. get: function () {
  11116. return Engine._ALPHA_SUBTRACT;
  11117. },
  11118. enumerable: true,
  11119. configurable: true
  11120. });
  11121. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11122. /** Defines that alpha blending to SRC * DEST */
  11123. get: function () {
  11124. return Engine._ALPHA_MULTIPLY;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11130. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11131. get: function () {
  11132. return Engine._ALPHA_MAXIMIZED;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11138. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11139. get: function () {
  11140. return Engine._ALPHA_PREMULTIPLIED;
  11141. },
  11142. enumerable: true,
  11143. configurable: true
  11144. });
  11145. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11146. /**
  11147. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11148. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11149. */
  11150. get: function () {
  11151. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11157. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11158. get: function () {
  11159. return Engine._ALPHA_INTERPOLATE;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11165. /**
  11166. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11167. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11168. */
  11169. get: function () {
  11170. return Engine._ALPHA_SCREENMODE;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11176. // Delays
  11177. /** Defines that the ressource is not delayed*/
  11178. get: function () {
  11179. return Engine._DELAYLOADSTATE_NONE;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11185. /** Defines that the ressource was successfully delay loaded */
  11186. get: function () {
  11187. return Engine._DELAYLOADSTATE_LOADED;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11193. /** Defines that the ressource is currently delay loading */
  11194. get: function () {
  11195. return Engine._DELAYLOADSTATE_LOADING;
  11196. },
  11197. enumerable: true,
  11198. configurable: true
  11199. });
  11200. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11201. /** Defines that the ressource is delayed and has not started loading */
  11202. get: function () {
  11203. return Engine._DELAYLOADSTATE_NOTLOADED;
  11204. },
  11205. enumerable: true,
  11206. configurable: true
  11207. });
  11208. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11209. /** ALPHA */
  11210. get: function () {
  11211. return Engine._TEXTUREFORMAT_ALPHA;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11217. /** LUMINANCE */
  11218. get: function () {
  11219. return Engine._TEXTUREFORMAT_LUMINANCE;
  11220. },
  11221. enumerable: true,
  11222. configurable: true
  11223. });
  11224. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11225. /**
  11226. * R32F
  11227. */
  11228. get: function () {
  11229. return Engine._TEXTUREFORMAT_R32F;
  11230. },
  11231. enumerable: true,
  11232. configurable: true
  11233. });
  11234. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11235. /**
  11236. * RG32F
  11237. */
  11238. get: function () {
  11239. return Engine._TEXTUREFORMAT_RG32F;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11245. /**
  11246. * RGB32F
  11247. */
  11248. get: function () {
  11249. return Engine._TEXTUREFORMAT_RGB32F;
  11250. },
  11251. enumerable: true,
  11252. configurable: true
  11253. });
  11254. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11255. /**
  11256. * RGBA32F
  11257. */
  11258. get: function () {
  11259. return Engine._TEXTUREFORMAT_RGBA32F;
  11260. },
  11261. enumerable: true,
  11262. configurable: true
  11263. });
  11264. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11265. /** LUMINANCE_ALPHA */
  11266. get: function () {
  11267. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11273. /** RGB */
  11274. get: function () {
  11275. return Engine._TEXTUREFORMAT_RGB;
  11276. },
  11277. enumerable: true,
  11278. configurable: true
  11279. });
  11280. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11281. /** RGBA */
  11282. get: function () {
  11283. return Engine._TEXTUREFORMAT_RGBA;
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11289. /** UNSIGNED_INT */
  11290. get: function () {
  11291. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11292. },
  11293. enumerable: true,
  11294. configurable: true
  11295. });
  11296. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11297. /** FLOAT */
  11298. get: function () {
  11299. return Engine._TEXTURETYPE_FLOAT;
  11300. },
  11301. enumerable: true,
  11302. configurable: true
  11303. });
  11304. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11305. /** HALF_FLOAT */
  11306. get: function () {
  11307. return Engine._TEXTURETYPE_HALF_FLOAT;
  11308. },
  11309. enumerable: true,
  11310. configurable: true
  11311. });
  11312. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11313. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11314. get: function () {
  11315. return Engine._SCALEMODE_FLOOR;
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11321. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11322. get: function () {
  11323. return Engine._SCALEMODE_NEAREST;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11329. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11330. get: function () {
  11331. return Engine._SCALEMODE_CEILING;
  11332. },
  11333. enumerable: true,
  11334. configurable: true
  11335. });
  11336. Object.defineProperty(Engine, "Version", {
  11337. /**
  11338. * Returns the current version of the framework
  11339. */
  11340. get: function () {
  11341. return "3.2.0-beta.3";
  11342. },
  11343. enumerable: true,
  11344. configurable: true
  11345. });
  11346. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11347. /**
  11348. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11349. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11350. */
  11351. get: function () {
  11352. return this._vrExclusivePointerMode;
  11353. },
  11354. enumerable: true,
  11355. configurable: true
  11356. });
  11357. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11358. /**
  11359. * Gets a boolean indicating that the engine supports uniform buffers
  11360. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11361. */
  11362. get: function () {
  11363. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11364. },
  11365. enumerable: true,
  11366. configurable: true
  11367. });
  11368. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11369. /**
  11370. * Gets a boolean indicating that only power of 2 textures are supported
  11371. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11372. */
  11373. get: function () {
  11374. return this._webGLVersion < 2 || this.forcePOTTextures;
  11375. },
  11376. enumerable: true,
  11377. configurable: true
  11378. });
  11379. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11380. /**
  11381. * Gets the performance monitor attached to this engine
  11382. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11383. */
  11384. get: function () {
  11385. return this._performanceMonitor;
  11386. },
  11387. enumerable: true,
  11388. configurable: true
  11389. });
  11390. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11391. /**
  11392. * Gets the list of texture formats supported
  11393. */
  11394. get: function () {
  11395. return this._texturesSupported;
  11396. },
  11397. enumerable: true,
  11398. configurable: true
  11399. });
  11400. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11401. /**
  11402. * Gets the list of texture formats in use
  11403. */
  11404. get: function () {
  11405. return this._textureFormatInUse;
  11406. },
  11407. enumerable: true,
  11408. configurable: true
  11409. });
  11410. Object.defineProperty(Engine.prototype, "currentViewport", {
  11411. /**
  11412. * Gets the current viewport
  11413. */
  11414. get: function () {
  11415. return this._cachedViewport;
  11416. },
  11417. enumerable: true,
  11418. configurable: true
  11419. });
  11420. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11421. /**
  11422. * Gets the default empty texture
  11423. */
  11424. get: function () {
  11425. if (!this._emptyTexture) {
  11426. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11427. }
  11428. return this._emptyTexture;
  11429. },
  11430. enumerable: true,
  11431. configurable: true
  11432. });
  11433. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11434. /**
  11435. * Gets the default empty 3D texture
  11436. */
  11437. get: function () {
  11438. if (!this._emptyTexture3D) {
  11439. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11440. }
  11441. return this._emptyTexture3D;
  11442. },
  11443. enumerable: true,
  11444. configurable: true
  11445. });
  11446. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11447. /**
  11448. * Gets the default empty cube texture
  11449. */
  11450. get: function () {
  11451. if (!this._emptyCubeTexture) {
  11452. var faceData = new Uint8Array(4);
  11453. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11454. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11455. }
  11456. return this._emptyCubeTexture;
  11457. },
  11458. enumerable: true,
  11459. configurable: true
  11460. });
  11461. Engine.prototype._rebuildInternalTextures = function () {
  11462. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11463. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11464. var internalTexture = currentState_1[_i];
  11465. internalTexture._rebuild();
  11466. }
  11467. };
  11468. Engine.prototype._rebuildEffects = function () {
  11469. for (var key in this._compiledEffects) {
  11470. var effect = this._compiledEffects[key];
  11471. effect._prepareEffect();
  11472. }
  11473. BABYLON.Effect.ResetCache();
  11474. };
  11475. Engine.prototype._rebuildBuffers = function () {
  11476. // Index / Vertex
  11477. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11478. var scene = _a[_i];
  11479. scene.resetCachedMaterial();
  11480. scene._rebuildGeometries();
  11481. scene._rebuildTextures();
  11482. }
  11483. // Uniforms
  11484. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11485. var uniformBuffer = _c[_b];
  11486. uniformBuffer._rebuild();
  11487. }
  11488. };
  11489. Engine.prototype._initGLContext = function () {
  11490. // Caps
  11491. this._caps = new EngineCapabilities();
  11492. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11493. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11494. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11495. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11496. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11497. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11498. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11499. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11500. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11501. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11502. // Infos
  11503. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11504. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11505. if (rendererInfo != null) {
  11506. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11507. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11508. }
  11509. if (!this._glVendor) {
  11510. this._glVendor = "Unknown vendor";
  11511. }
  11512. if (!this._glRenderer) {
  11513. this._glRenderer = "Unknown renderer";
  11514. }
  11515. // Constants
  11516. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11517. if (this._gl.RGBA16F !== 0x881A) {
  11518. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11519. }
  11520. if (this._gl.RGBA32F !== 0x8814) {
  11521. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11522. }
  11523. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11524. this._gl.DEPTH24_STENCIL8 = 35056;
  11525. }
  11526. // Extensions
  11527. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11528. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11529. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11530. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11531. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11532. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11533. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11534. 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');
  11535. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11536. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11537. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11538. this._caps.highPrecisionShaderSupported = true;
  11539. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11540. if (this._caps.timerQuery) {
  11541. if (this._webGLVersion === 1) {
  11542. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11543. }
  11544. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11545. }
  11546. // Checks if some of the format renders first to allow the use of webgl inspector.
  11547. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11548. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11549. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11550. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11551. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11552. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11553. if (this._webGLVersion > 1) {
  11554. this._gl.HALF_FLOAT_OES = 0x140B;
  11555. }
  11556. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11557. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11558. // Draw buffers
  11559. if (this._webGLVersion > 1) {
  11560. this._caps.drawBuffersExtension = true;
  11561. }
  11562. else {
  11563. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11564. if (drawBuffersExtension !== null) {
  11565. this._caps.drawBuffersExtension = true;
  11566. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11567. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11568. for (var i = 0; i < 16; i++) {
  11569. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11570. }
  11571. }
  11572. else {
  11573. this._caps.drawBuffersExtension = false;
  11574. }
  11575. }
  11576. // Depth Texture
  11577. if (this._webGLVersion > 1) {
  11578. this._caps.depthTextureExtension = true;
  11579. }
  11580. else {
  11581. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11582. if (depthTextureExtension != null) {
  11583. this._caps.depthTextureExtension = true;
  11584. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11585. }
  11586. }
  11587. // Vertex array object
  11588. if (this._webGLVersion > 1) {
  11589. this._caps.vertexArrayObject = true;
  11590. }
  11591. else {
  11592. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11593. if (vertexArrayObjectExtension != null) {
  11594. this._caps.vertexArrayObject = true;
  11595. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11596. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11597. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11598. }
  11599. else {
  11600. this._caps.vertexArrayObject = false;
  11601. }
  11602. }
  11603. // Instances count
  11604. if (this._webGLVersion > 1) {
  11605. this._caps.instancedArrays = true;
  11606. }
  11607. else {
  11608. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11609. if (instanceExtension != null) {
  11610. this._caps.instancedArrays = true;
  11611. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11612. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11613. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11614. }
  11615. else {
  11616. this._caps.instancedArrays = false;
  11617. }
  11618. }
  11619. // Intelligently add supported compressed formats in order to check for.
  11620. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11621. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11622. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11623. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11624. if (this._caps.astc)
  11625. this.texturesSupported.push('-astc.ktx');
  11626. if (this._caps.s3tc)
  11627. this.texturesSupported.push('-dxt.ktx');
  11628. if (this._caps.pvrtc)
  11629. this.texturesSupported.push('-pvrtc.ktx');
  11630. if (this._caps.etc2)
  11631. this.texturesSupported.push('-etc2.ktx');
  11632. if (this._caps.etc1)
  11633. this.texturesSupported.push('-etc1.ktx');
  11634. if (this._gl.getShaderPrecisionFormat) {
  11635. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11636. if (highp) {
  11637. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11638. }
  11639. }
  11640. // Depth buffer
  11641. this.setDepthBuffer(true);
  11642. this.setDepthFunctionToLessOrEqual();
  11643. this.setDepthWrite(true);
  11644. // Texture maps
  11645. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11646. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11647. this._nextFreeTextureSlots.push(slot);
  11648. }
  11649. };
  11650. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11651. /**
  11652. * Gets version of the current webGL context
  11653. */
  11654. get: function () {
  11655. return this._webGLVersion;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11661. /**
  11662. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11663. */
  11664. get: function () {
  11665. return this._isStencilEnable;
  11666. },
  11667. enumerable: true,
  11668. configurable: true
  11669. });
  11670. Engine.prototype._prepareWorkingCanvas = function () {
  11671. if (this._workingCanvas) {
  11672. return;
  11673. }
  11674. this._workingCanvas = document.createElement("canvas");
  11675. var context = this._workingCanvas.getContext("2d");
  11676. if (context) {
  11677. this._workingContext = context;
  11678. }
  11679. };
  11680. /**
  11681. * Reset the texture cache to empty state
  11682. */
  11683. Engine.prototype.resetTextureCache = function () {
  11684. for (var key in this._boundTexturesCache) {
  11685. var boundTexture = this._boundTexturesCache[key];
  11686. if (boundTexture) {
  11687. this._removeDesignatedSlot(boundTexture);
  11688. }
  11689. this._boundTexturesCache[key] = null;
  11690. }
  11691. if (!this.disableTextureBindingOptimization) {
  11692. this._nextFreeTextureSlots = [];
  11693. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11694. this._nextFreeTextureSlots.push(slot);
  11695. }
  11696. }
  11697. this._currentTextureChannel = -1;
  11698. };
  11699. /**
  11700. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  11701. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11702. * @returns true if engine is in deterministic lock step mode
  11703. */
  11704. Engine.prototype.isDeterministicLockStep = function () {
  11705. return this._deterministicLockstep;
  11706. };
  11707. /**
  11708. * Gets the max steps when engine is running in deterministic lock step
  11709. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11710. * @returns the max steps
  11711. */
  11712. Engine.prototype.getLockstepMaxSteps = function () {
  11713. return this._lockstepMaxSteps;
  11714. };
  11715. /**
  11716. * Gets an object containing information about the current webGL context
  11717. * @returns an object containing the vender, the renderer and the version of the current webGL context
  11718. */
  11719. Engine.prototype.getGlInfo = function () {
  11720. return {
  11721. vendor: this._glVendor,
  11722. renderer: this._glRenderer,
  11723. version: this._glVersion
  11724. };
  11725. };
  11726. /**
  11727. * Gets current aspect ratio
  11728. * @param camera defines the camera to use to get the aspect ratio
  11729. * @param useScreen defines if screen size must be used (or the current render target if any)
  11730. * @returns a number defining the aspect ratio
  11731. */
  11732. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11733. if (useScreen === void 0) { useScreen = false; }
  11734. var viewport = camera.viewport;
  11735. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11736. };
  11737. /**
  11738. * Gets the current render width
  11739. * @param useScreen defines if screen size must be used (or the current render target if any)
  11740. * @returns a number defining the current render width
  11741. */
  11742. Engine.prototype.getRenderWidth = function (useScreen) {
  11743. if (useScreen === void 0) { useScreen = false; }
  11744. if (!useScreen && this._currentRenderTarget) {
  11745. return this._currentRenderTarget.width;
  11746. }
  11747. return this._gl.drawingBufferWidth;
  11748. };
  11749. /**
  11750. * Gets the current render height
  11751. * @param useScreen defines if screen size must be used (or the current render target if any)
  11752. * @returns a number defining the current render height
  11753. */
  11754. Engine.prototype.getRenderHeight = function (useScreen) {
  11755. if (useScreen === void 0) { useScreen = false; }
  11756. if (!useScreen && this._currentRenderTarget) {
  11757. return this._currentRenderTarget.height;
  11758. }
  11759. return this._gl.drawingBufferHeight;
  11760. };
  11761. /**
  11762. * Gets the HTML canvas attached with the current webGL context
  11763. * @returns a HTML canvas
  11764. */
  11765. Engine.prototype.getRenderingCanvas = function () {
  11766. return this._renderingCanvas;
  11767. };
  11768. /**
  11769. * Gets the client rect of the HTML canvas attached with the current webGL context
  11770. * @returns a client rectanglee
  11771. */
  11772. Engine.prototype.getRenderingCanvasClientRect = function () {
  11773. if (!this._renderingCanvas) {
  11774. return null;
  11775. }
  11776. return this._renderingCanvas.getBoundingClientRect();
  11777. };
  11778. /**
  11779. * Defines the hardware scaling level.
  11780. * By default the hardware scaling level is computed from the window device ratio.
  11781. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  11782. * @param level defines the level to use
  11783. */
  11784. Engine.prototype.setHardwareScalingLevel = function (level) {
  11785. this._hardwareScalingLevel = level;
  11786. this.resize();
  11787. };
  11788. /**
  11789. * Gets the current hardware scaling level.
  11790. * By default the hardware scaling level is computed from the window device ratio.
  11791. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  11792. * @returns a number indicating the current hardware scaling level
  11793. */
  11794. Engine.prototype.getHardwareScalingLevel = function () {
  11795. return this._hardwareScalingLevel;
  11796. };
  11797. /**
  11798. * Gets the list of loaded textures
  11799. * @returns an array containing all loaded textures
  11800. */
  11801. Engine.prototype.getLoadedTexturesCache = function () {
  11802. return this._internalTexturesCache;
  11803. };
  11804. /**
  11805. * Gets the object containing all engine capabilities
  11806. * @returns the EngineCapabilities object
  11807. */
  11808. Engine.prototype.getCaps = function () {
  11809. return this._caps;
  11810. };
  11811. Object.defineProperty(Engine.prototype, "drawCalls", {
  11812. /** @ignore */
  11813. get: function () {
  11814. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11815. return 0;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11821. /** @ignore */
  11822. get: function () {
  11823. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11824. return null;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. /**
  11830. * Gets the current depth function
  11831. * @returns a number defining the depth function
  11832. */
  11833. Engine.prototype.getDepthFunction = function () {
  11834. return this._depthCullingState.depthFunc;
  11835. };
  11836. /**
  11837. * Sets the current depth function
  11838. * @param depthFunc defines the function to use
  11839. */
  11840. Engine.prototype.setDepthFunction = function (depthFunc) {
  11841. this._depthCullingState.depthFunc = depthFunc;
  11842. };
  11843. /**
  11844. * Sets the current depth function to GREATER
  11845. */
  11846. Engine.prototype.setDepthFunctionToGreater = function () {
  11847. this._depthCullingState.depthFunc = this._gl.GREATER;
  11848. };
  11849. /**
  11850. * Sets the current depth function to GEQUAL
  11851. */
  11852. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11853. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11854. };
  11855. /**
  11856. * Sets the current depth function to LESS
  11857. */
  11858. Engine.prototype.setDepthFunctionToLess = function () {
  11859. this._depthCullingState.depthFunc = this._gl.LESS;
  11860. };
  11861. /**
  11862. * Sets the current depth function to LEQUAL
  11863. */
  11864. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11865. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11866. };
  11867. /**
  11868. * Gets a boolean indicating if stencil buffer is enabled
  11869. * @returns the current stencil buffer state
  11870. */
  11871. Engine.prototype.getStencilBuffer = function () {
  11872. return this._stencilState.stencilTest;
  11873. };
  11874. /**
  11875. * Enable or disable the stencil buffer
  11876. * @param enable defines if the stencil buffer must be enabled or disabled
  11877. */
  11878. Engine.prototype.setStencilBuffer = function (enable) {
  11879. this._stencilState.stencilTest = enable;
  11880. };
  11881. /**
  11882. * Gets the current stencil mask
  11883. * @returns a number defining the new stencil mask to use
  11884. */
  11885. Engine.prototype.getStencilMask = function () {
  11886. return this._stencilState.stencilMask;
  11887. };
  11888. /**
  11889. * Sets the current stencil mask
  11890. * @param mask defines the new stencil mask to use
  11891. */
  11892. Engine.prototype.setStencilMask = function (mask) {
  11893. this._stencilState.stencilMask = mask;
  11894. };
  11895. /**
  11896. * Gets the current stencil function
  11897. * @returns a number defining the stencil function to use
  11898. */
  11899. Engine.prototype.getStencilFunction = function () {
  11900. return this._stencilState.stencilFunc;
  11901. };
  11902. /**
  11903. * Gets the current stencil reference value
  11904. * @returns a number defining the stencil reference value to use
  11905. */
  11906. Engine.prototype.getStencilFunctionReference = function () {
  11907. return this._stencilState.stencilFuncRef;
  11908. };
  11909. /**
  11910. * Gets the current stencil mask
  11911. * @returns a number defining the stencil mask to use
  11912. */
  11913. Engine.prototype.getStencilFunctionMask = function () {
  11914. return this._stencilState.stencilFuncMask;
  11915. };
  11916. /**
  11917. * Sets the current stencil function
  11918. * @param stencilFunc defines the new stencil function to use
  11919. */
  11920. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11921. this._stencilState.stencilFunc = stencilFunc;
  11922. };
  11923. /**
  11924. * Sets the current stencil reference
  11925. * @param reference defines the new stencil reference to use
  11926. */
  11927. Engine.prototype.setStencilFunctionReference = function (reference) {
  11928. this._stencilState.stencilFuncRef = reference;
  11929. };
  11930. /**
  11931. * Sets the current stencil mask
  11932. * @param mask defines the new stencil mask to use
  11933. */
  11934. Engine.prototype.setStencilFunctionMask = function (mask) {
  11935. this._stencilState.stencilFuncMask = mask;
  11936. };
  11937. /**
  11938. * Gets the current stencil operation when stencil fails
  11939. * @returns a number defining stencil operation to use when stencil fails
  11940. */
  11941. Engine.prototype.getStencilOperationFail = function () {
  11942. return this._stencilState.stencilOpStencilFail;
  11943. };
  11944. /**
  11945. * Gets the current stencil operation when depth fails
  11946. * @returns a number defining stencil operation to use when depth fails
  11947. */
  11948. Engine.prototype.getStencilOperationDepthFail = function () {
  11949. return this._stencilState.stencilOpDepthFail;
  11950. };
  11951. /**
  11952. * Gets the current stencil operation when stencil passes
  11953. * @returns a number defining stencil operation to use when stencil passes
  11954. */
  11955. Engine.prototype.getStencilOperationPass = function () {
  11956. return this._stencilState.stencilOpStencilDepthPass;
  11957. };
  11958. /**
  11959. * Sets the stencil operation to use when stencil fails
  11960. * @param operation defines the stencil operation to use when stencil fails
  11961. */
  11962. Engine.prototype.setStencilOperationFail = function (operation) {
  11963. this._stencilState.stencilOpStencilFail = operation;
  11964. };
  11965. /**
  11966. * Sets the stencil operation to use when depth fails
  11967. * @param operation defines the stencil operation to use when depth fails
  11968. */
  11969. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11970. this._stencilState.stencilOpDepthFail = operation;
  11971. };
  11972. /**
  11973. * Sets the stencil operation to use when stencil passes
  11974. * @param operation defines the stencil operation to use when stencil passes
  11975. */
  11976. Engine.prototype.setStencilOperationPass = function (operation) {
  11977. this._stencilState.stencilOpStencilDepthPass = operation;
  11978. };
  11979. /**
  11980. * Sets a boolean indicating if the dithering state is enabled or disabled
  11981. * @param value defines the dithering state
  11982. */
  11983. Engine.prototype.setDitheringState = function (value) {
  11984. if (value) {
  11985. this._gl.enable(this._gl.DITHER);
  11986. }
  11987. else {
  11988. this._gl.disable(this._gl.DITHER);
  11989. }
  11990. };
  11991. /**
  11992. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  11993. * @param value defines the rasterizer state
  11994. */
  11995. Engine.prototype.setRasterizerState = function (value) {
  11996. if (value) {
  11997. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11998. }
  11999. else {
  12000. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12001. }
  12002. };
  12003. /**
  12004. * stop executing a render loop function and remove it from the execution array
  12005. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12006. */
  12007. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12008. if (!renderFunction) {
  12009. this._activeRenderLoops = [];
  12010. return;
  12011. }
  12012. var index = this._activeRenderLoops.indexOf(renderFunction);
  12013. if (index >= 0) {
  12014. this._activeRenderLoops.splice(index, 1);
  12015. }
  12016. };
  12017. /** @ignore */
  12018. Engine.prototype._renderLoop = function () {
  12019. if (!this._contextWasLost) {
  12020. var shouldRender = true;
  12021. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12022. shouldRender = false;
  12023. }
  12024. if (shouldRender) {
  12025. // Start new frame
  12026. this.beginFrame();
  12027. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12028. var renderFunction = this._activeRenderLoops[index];
  12029. renderFunction();
  12030. }
  12031. // Present
  12032. this.endFrame();
  12033. }
  12034. }
  12035. if (this._activeRenderLoops.length > 0) {
  12036. // Register new frame
  12037. var requester = null;
  12038. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12039. requester = this._vrDisplay;
  12040. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12041. }
  12042. else {
  12043. this._renderingQueueLaunched = false;
  12044. }
  12045. };
  12046. /**
  12047. * Register and execute a render loop. The engine can have more than one render function
  12048. * @param renderFunction defines the function to continuously execute
  12049. */
  12050. Engine.prototype.runRenderLoop = function (renderFunction) {
  12051. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12052. return;
  12053. }
  12054. this._activeRenderLoops.push(renderFunction);
  12055. if (!this._renderingQueueLaunched) {
  12056. this._renderingQueueLaunched = true;
  12057. this._bindedRenderFunction = this._renderLoop.bind(this);
  12058. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12059. }
  12060. };
  12061. /**
  12062. * Toggle full screen mode
  12063. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12064. * @param options defines an option object to be sent to the requestFullscreen function
  12065. */
  12066. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12067. if (this.isFullscreen) {
  12068. BABYLON.Tools.ExitFullscreen();
  12069. }
  12070. else {
  12071. this._pointerLockRequested = requestPointerLock;
  12072. if (this._renderingCanvas) {
  12073. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12074. }
  12075. }
  12076. };
  12077. /**
  12078. * Clear the current render buffer or the current render target (if any is set up)
  12079. * @param color defines the color to use
  12080. * @param backBuffer defines if the back buffer must be cleared
  12081. * @param depth defines if the depth buffer must be cleared
  12082. * @param stencil defines if the stencil buffer must be cleared
  12083. */
  12084. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12085. if (stencil === void 0) { stencil = false; }
  12086. this.applyStates();
  12087. var mode = 0;
  12088. if (backBuffer && color) {
  12089. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12090. mode |= this._gl.COLOR_BUFFER_BIT;
  12091. }
  12092. if (depth) {
  12093. this._gl.clearDepth(1.0);
  12094. mode |= this._gl.DEPTH_BUFFER_BIT;
  12095. }
  12096. if (stencil) {
  12097. this._gl.clearStencil(0);
  12098. mode |= this._gl.STENCIL_BUFFER_BIT;
  12099. }
  12100. this._gl.clear(mode);
  12101. };
  12102. /**
  12103. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12104. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12105. * @param y defines the y-coordinate of the corner of the clear rectangle
  12106. * @param width defines the width of the clear rectangle
  12107. * @param height defines the height of the clear rectangle
  12108. * @param clearColor defines the clear color
  12109. */
  12110. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12111. var gl = this._gl;
  12112. // Save state
  12113. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12114. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12115. // Change state
  12116. gl.enable(gl.SCISSOR_TEST);
  12117. gl.scissor(x, y, width, height);
  12118. // Clear
  12119. this.clear(clearColor, true, true, true);
  12120. // Restore state
  12121. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12122. if (curScissor === true) {
  12123. gl.enable(gl.SCISSOR_TEST);
  12124. }
  12125. else {
  12126. gl.disable(gl.SCISSOR_TEST);
  12127. }
  12128. };
  12129. /**
  12130. * Set the WebGL's viewport
  12131. * @param viewport defines the viewport element to be used
  12132. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12133. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12134. */
  12135. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12136. var width = requiredWidth || this.getRenderWidth();
  12137. var height = requiredHeight || this.getRenderHeight();
  12138. var x = viewport.x || 0;
  12139. var y = viewport.y || 0;
  12140. this._cachedViewport = viewport;
  12141. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12142. };
  12143. /**
  12144. * Directly set the WebGL Viewport
  12145. * @param x defines the x coordinate of the viewport (in screen space)
  12146. * @param y defines the y coordinate of the viewport (in screen space)
  12147. * @param width defines the width of the viewport (in screen space)
  12148. * @param height defines the height of the viewport (in screen space)
  12149. * @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
  12150. */
  12151. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12152. var currentViewport = this._cachedViewport;
  12153. this._cachedViewport = null;
  12154. this._gl.viewport(x, y, width, height);
  12155. return currentViewport;
  12156. };
  12157. /**
  12158. * Begin a new frame
  12159. */
  12160. Engine.prototype.beginFrame = function () {
  12161. this.onBeginFrameObservable.notifyObservers(this);
  12162. this._measureFps();
  12163. };
  12164. /**
  12165. * Enf the current frame
  12166. */
  12167. Engine.prototype.endFrame = function () {
  12168. // Force a flush in case we are using a bad OS.
  12169. if (this._badOS) {
  12170. this.flushFramebuffer();
  12171. }
  12172. // Submit frame to the vr device, if enabled
  12173. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12174. // TODO: We should only submit the frame if we read frameData successfully.
  12175. this._vrDisplay.submitFrame();
  12176. }
  12177. this.onEndFrameObservable.notifyObservers(this);
  12178. };
  12179. /**
  12180. * Resize the view according to the canvas' size
  12181. */
  12182. Engine.prototype.resize = function () {
  12183. // We're not resizing the size of the canvas while in VR mode & presenting
  12184. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12185. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12186. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12187. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12188. }
  12189. };
  12190. /**
  12191. * Force a specific size of the canvas
  12192. * @param width defines the new canvas' width
  12193. * @param height defines the new canvas' height
  12194. */
  12195. Engine.prototype.setSize = function (width, height) {
  12196. if (!this._renderingCanvas) {
  12197. return;
  12198. }
  12199. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12200. return;
  12201. }
  12202. this._renderingCanvas.width = width;
  12203. this._renderingCanvas.height = height;
  12204. for (var index = 0; index < this.scenes.length; index++) {
  12205. var scene = this.scenes[index];
  12206. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12207. var cam = scene.cameras[camIndex];
  12208. cam._currentRenderId = 0;
  12209. }
  12210. }
  12211. if (this.onResizeObservable.hasObservers) {
  12212. this.onResizeObservable.notifyObservers(this);
  12213. }
  12214. };
  12215. // WebVR functions
  12216. /**
  12217. * Gets a boolean indicating if a webVR device was detected
  12218. * @returns true if a webVR device was detected
  12219. */
  12220. Engine.prototype.isVRDevicePresent = function () {
  12221. return !!this._vrDisplay;
  12222. };
  12223. /**
  12224. * Gets the current webVR device
  12225. * @returns the current webVR device (or null)
  12226. */
  12227. Engine.prototype.getVRDevice = function () {
  12228. return this._vrDisplay;
  12229. };
  12230. /**
  12231. * Initializes a webVR display and starts listening to display change events
  12232. * The onVRDisplayChangedObservable will be notified upon these changes
  12233. * @returns The onVRDisplayChangedObservable
  12234. */
  12235. Engine.prototype.initWebVR = function () {
  12236. this.initWebVRAsync();
  12237. return this.onVRDisplayChangedObservable;
  12238. };
  12239. /**
  12240. * Initializes a webVR display and starts listening to display change events
  12241. * The onVRDisplayChangedObservable will be notified upon these changes
  12242. * @returns A promise containing a VRDisplay and if vr is supported
  12243. */
  12244. Engine.prototype.initWebVRAsync = function () {
  12245. var _this = this;
  12246. var notifyObservers = function () {
  12247. var eventArgs = {
  12248. vrDisplay: _this._vrDisplay,
  12249. vrSupported: _this._vrSupported
  12250. };
  12251. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12252. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12253. };
  12254. if (!this._onVrDisplayConnect) {
  12255. this._onVrDisplayConnect = function (event) {
  12256. _this._vrDisplay = event.display;
  12257. notifyObservers();
  12258. };
  12259. this._onVrDisplayDisconnect = function () {
  12260. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12261. _this._vrDisplay = undefined;
  12262. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12263. notifyObservers();
  12264. };
  12265. this._onVrDisplayPresentChange = function () {
  12266. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12267. };
  12268. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12269. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12270. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12271. }
  12272. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12273. this._webVRInitPromise.then(notifyObservers);
  12274. return this._webVRInitPromise;
  12275. };
  12276. /**
  12277. * Call this function to switch to webVR mode
  12278. * Will do nothing if webVR is not supported or if there is no webVR device
  12279. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12280. */
  12281. Engine.prototype.enableVR = function () {
  12282. var _this = this;
  12283. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12284. var onResolved = function () {
  12285. _this.onVRRequestPresentComplete.notifyObservers(true);
  12286. _this._onVRFullScreenTriggered();
  12287. };
  12288. var onRejected = function () {
  12289. _this.onVRRequestPresentComplete.notifyObservers(false);
  12290. };
  12291. this.onVRRequestPresentStart.notifyObservers(this);
  12292. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12293. }
  12294. };
  12295. /**
  12296. * Call this function to leave webVR mode
  12297. * Will do nothing if webVR is not supported or if there is no webVR device
  12298. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12299. */
  12300. Engine.prototype.disableVR = function () {
  12301. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12302. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12303. }
  12304. };
  12305. Engine.prototype._getVRDisplaysAsync = function () {
  12306. var _this = this;
  12307. return new Promise(function (res, rej) {
  12308. if (navigator.getVRDisplays) {
  12309. navigator.getVRDisplays().then(function (devices) {
  12310. _this._vrSupported = true;
  12311. // note that devices may actually be an empty array. This is fine;
  12312. // we expect this._vrDisplay to be undefined in this case.
  12313. _this._vrDisplay = devices[0];
  12314. res({
  12315. vrDisplay: _this._vrDisplay,
  12316. vrSupported: _this._vrSupported
  12317. });
  12318. });
  12319. }
  12320. else {
  12321. _this._vrDisplay = undefined;
  12322. _this._vrSupported = false;
  12323. res({
  12324. vrDisplay: _this._vrDisplay,
  12325. vrSupported: _this._vrSupported
  12326. });
  12327. }
  12328. });
  12329. };
  12330. /**
  12331. * Binds the frame buffer to the specified texture.
  12332. * @param texture The texture to render to or null for the default canvas
  12333. * @param faceIndex The face of the texture to render to in case of cube texture
  12334. * @param requiredWidth The width of the target to render to
  12335. * @param requiredHeight The height of the target to render to
  12336. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12337. * @param depthStencilTexture The depth stencil texture to use to render
  12338. */
  12339. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12340. if (this._currentRenderTarget) {
  12341. this.unBindFramebuffer(this._currentRenderTarget);
  12342. }
  12343. this._currentRenderTarget = texture;
  12344. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12345. var gl = this._gl;
  12346. if (texture.isCube) {
  12347. if (faceIndex === undefined) {
  12348. faceIndex = 0;
  12349. }
  12350. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12351. if (depthStencilTexture) {
  12352. if (depthStencilTexture._generateStencilBuffer) {
  12353. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12354. }
  12355. else {
  12356. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12357. }
  12358. }
  12359. }
  12360. if (this._cachedViewport && !forceFullscreenViewport) {
  12361. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12362. }
  12363. else {
  12364. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12365. }
  12366. this.wipeCaches();
  12367. };
  12368. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12369. if (this._currentFramebuffer !== framebuffer) {
  12370. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12371. this._currentFramebuffer = framebuffer;
  12372. }
  12373. };
  12374. /**
  12375. * Unbind the current render target texture from the webGL context
  12376. * @param texture defines the render target texture to unbind
  12377. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12378. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12379. */
  12380. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12381. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12382. this._currentRenderTarget = null;
  12383. // If MSAA, we need to bitblt back to main texture
  12384. var gl = this._gl;
  12385. if (texture._MSAAFramebuffer) {
  12386. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12387. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12388. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12389. }
  12390. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12391. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12392. gl.generateMipmap(gl.TEXTURE_2D);
  12393. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12394. }
  12395. if (onBeforeUnbind) {
  12396. if (texture._MSAAFramebuffer) {
  12397. // Bind the correct framebuffer
  12398. this.bindUnboundFramebuffer(texture._framebuffer);
  12399. }
  12400. onBeforeUnbind();
  12401. }
  12402. this.bindUnboundFramebuffer(null);
  12403. };
  12404. /**
  12405. * Unbind a list of render target textures from the webGL context
  12406. * This is used only when drawBuffer extension or webGL2 are active
  12407. * @param textures defines the render target textures to unbind
  12408. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12409. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12410. */
  12411. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12412. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12413. this._currentRenderTarget = null;
  12414. // If MSAA, we need to bitblt back to main texture
  12415. var gl = this._gl;
  12416. if (textures[0]._MSAAFramebuffer) {
  12417. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12418. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12419. var attachments = textures[0]._attachments;
  12420. if (!attachments) {
  12421. attachments = new Array(textures.length);
  12422. textures[0]._attachments = attachments;
  12423. }
  12424. for (var i = 0; i < textures.length; i++) {
  12425. var texture = textures[i];
  12426. for (var j = 0; j < attachments.length; j++) {
  12427. attachments[j] = gl.NONE;
  12428. }
  12429. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12430. gl.readBuffer(attachments[i]);
  12431. gl.drawBuffers(attachments);
  12432. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12433. }
  12434. for (var i = 0; i < attachments.length; i++) {
  12435. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12436. }
  12437. gl.drawBuffers(attachments);
  12438. }
  12439. for (var i = 0; i < textures.length; i++) {
  12440. var texture = textures[i];
  12441. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12442. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12443. gl.generateMipmap(gl.TEXTURE_2D);
  12444. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12445. }
  12446. }
  12447. if (onBeforeUnbind) {
  12448. if (textures[0]._MSAAFramebuffer) {
  12449. // Bind the correct framebuffer
  12450. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12451. }
  12452. onBeforeUnbind();
  12453. }
  12454. this.bindUnboundFramebuffer(null);
  12455. };
  12456. /**
  12457. * Force the mipmap generation for the given render target texture
  12458. * @param texture defines the render target texture to use
  12459. */
  12460. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12461. if (texture.generateMipMaps) {
  12462. var gl = this._gl;
  12463. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12464. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12465. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12466. }
  12467. };
  12468. /**
  12469. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12470. */
  12471. Engine.prototype.flushFramebuffer = function () {
  12472. this._gl.flush();
  12473. };
  12474. /**
  12475. * Unbind the current render target and bind the default framebuffer
  12476. */
  12477. Engine.prototype.restoreDefaultFramebuffer = function () {
  12478. if (this._currentRenderTarget) {
  12479. this.unBindFramebuffer(this._currentRenderTarget);
  12480. }
  12481. else {
  12482. this.bindUnboundFramebuffer(null);
  12483. }
  12484. if (this._cachedViewport) {
  12485. this.setViewport(this._cachedViewport);
  12486. }
  12487. this.wipeCaches();
  12488. };
  12489. // UBOs
  12490. /**
  12491. * Create an uniform buffer
  12492. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12493. * @param elements defines the content of the uniform buffer
  12494. * @returns the webGL uniform buffer
  12495. */
  12496. Engine.prototype.createUniformBuffer = function (elements) {
  12497. var ubo = this._gl.createBuffer();
  12498. if (!ubo) {
  12499. throw new Error("Unable to create uniform buffer");
  12500. }
  12501. this.bindUniformBuffer(ubo);
  12502. if (elements instanceof Float32Array) {
  12503. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12504. }
  12505. else {
  12506. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12507. }
  12508. this.bindUniformBuffer(null);
  12509. ubo.references = 1;
  12510. return ubo;
  12511. };
  12512. /**
  12513. * Create a dynamic uniform buffer
  12514. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12515. * @param elements defines the content of the uniform buffer
  12516. * @returns the webGL uniform buffer
  12517. */
  12518. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12519. var ubo = this._gl.createBuffer();
  12520. if (!ubo) {
  12521. throw new Error("Unable to create dynamic uniform buffer");
  12522. }
  12523. this.bindUniformBuffer(ubo);
  12524. if (elements instanceof Float32Array) {
  12525. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12526. }
  12527. else {
  12528. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12529. }
  12530. this.bindUniformBuffer(null);
  12531. ubo.references = 1;
  12532. return ubo;
  12533. };
  12534. /**
  12535. * Update an existing uniform buffer
  12536. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12537. * @param uniformBuffer defines the target uniform buffer
  12538. * @param elements defines the content to update
  12539. * @param offset defines the offset in the uniform buffer where update should start
  12540. * @param count defines the size of the data to update
  12541. */
  12542. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12543. this.bindUniformBuffer(uniformBuffer);
  12544. if (offset === undefined) {
  12545. offset = 0;
  12546. }
  12547. if (count === undefined) {
  12548. if (elements instanceof Float32Array) {
  12549. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12550. }
  12551. else {
  12552. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12553. }
  12554. }
  12555. else {
  12556. if (elements instanceof Float32Array) {
  12557. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12558. }
  12559. else {
  12560. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12561. }
  12562. }
  12563. this.bindUniformBuffer(null);
  12564. };
  12565. // VBOs
  12566. Engine.prototype._resetVertexBufferBinding = function () {
  12567. this.bindArrayBuffer(null);
  12568. this._cachedVertexBuffers = null;
  12569. };
  12570. /**
  12571. * Creates a vertex buffer
  12572. * @param data the data for the vertex buffer
  12573. * @returns the new WebGL static buffer
  12574. */
  12575. Engine.prototype.createVertexBuffer = function (data) {
  12576. var vbo = this._gl.createBuffer();
  12577. if (!vbo) {
  12578. throw new Error("Unable to create vertex buffer");
  12579. }
  12580. this.bindArrayBuffer(vbo);
  12581. if (data instanceof Array) {
  12582. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12583. }
  12584. else {
  12585. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12586. }
  12587. this._resetVertexBufferBinding();
  12588. vbo.references = 1;
  12589. return vbo;
  12590. };
  12591. /**
  12592. * Creates a dynamic vertex buffer
  12593. * @param data the data for the dynamic vertex buffer
  12594. * @returns the new WebGL dynamic buffer
  12595. */
  12596. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12597. var vbo = this._gl.createBuffer();
  12598. if (!vbo) {
  12599. throw new Error("Unable to create dynamic vertex buffer");
  12600. }
  12601. this.bindArrayBuffer(vbo);
  12602. if (data instanceof Array) {
  12603. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12604. }
  12605. else {
  12606. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12607. }
  12608. this._resetVertexBufferBinding();
  12609. vbo.references = 1;
  12610. return vbo;
  12611. };
  12612. /**
  12613. * Update a dynamic index buffer
  12614. * @param indexBuffer defines the target index buffer
  12615. * @param indices defines the data to update
  12616. * @param offset defines the offset in the target index buffer where update should start
  12617. */
  12618. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12619. if (offset === void 0) { offset = 0; }
  12620. // Force cache update
  12621. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12622. this.bindIndexBuffer(indexBuffer);
  12623. var arrayBuffer;
  12624. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12625. arrayBuffer = indices;
  12626. }
  12627. else {
  12628. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12629. }
  12630. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12631. this._resetIndexBufferBinding();
  12632. };
  12633. /**
  12634. * Updates a dynamic vertex buffer.
  12635. * @param vertexBuffer the vertex buffer to update
  12636. * @param data the data used to update the vertex buffer
  12637. * @param byteOffset the byte offset of the data
  12638. * @param byteLength the byte length of the data
  12639. */
  12640. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12641. this.bindArrayBuffer(vertexBuffer);
  12642. if (byteOffset === undefined) {
  12643. byteOffset = 0;
  12644. }
  12645. if (byteLength === undefined) {
  12646. if (data instanceof Array) {
  12647. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12648. }
  12649. else {
  12650. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12651. }
  12652. }
  12653. else {
  12654. if (data instanceof Array) {
  12655. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12656. }
  12657. else {
  12658. if (data instanceof ArrayBuffer) {
  12659. data = new Uint8Array(data, byteOffset, byteLength);
  12660. }
  12661. else {
  12662. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12663. }
  12664. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12665. }
  12666. }
  12667. this._resetVertexBufferBinding();
  12668. };
  12669. Engine.prototype._resetIndexBufferBinding = function () {
  12670. this.bindIndexBuffer(null);
  12671. this._cachedIndexBuffer = null;
  12672. };
  12673. /**
  12674. * Creates a new index buffer
  12675. * @param indices defines the content of the index buffer
  12676. * @param updatable defines if the index buffer must be updatable
  12677. * @returns a new webGL buffer
  12678. */
  12679. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12680. var vbo = this._gl.createBuffer();
  12681. if (!vbo) {
  12682. throw new Error("Unable to create index buffer");
  12683. }
  12684. this.bindIndexBuffer(vbo);
  12685. // Check for 32 bits indices
  12686. var arrayBuffer;
  12687. var need32Bits = false;
  12688. if (indices instanceof Uint16Array) {
  12689. arrayBuffer = indices;
  12690. }
  12691. else {
  12692. //check 32 bit support
  12693. if (this._caps.uintIndices) {
  12694. if (indices instanceof Uint32Array) {
  12695. arrayBuffer = indices;
  12696. need32Bits = true;
  12697. }
  12698. else {
  12699. //number[] or Int32Array, check if 32 bit is necessary
  12700. for (var index = 0; index < indices.length; index++) {
  12701. if (indices[index] > 65535) {
  12702. need32Bits = true;
  12703. break;
  12704. }
  12705. }
  12706. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12707. }
  12708. }
  12709. else {
  12710. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12711. arrayBuffer = new Uint16Array(indices);
  12712. }
  12713. }
  12714. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12715. this._resetIndexBufferBinding();
  12716. vbo.references = 1;
  12717. vbo.is32Bits = need32Bits;
  12718. return vbo;
  12719. };
  12720. /**
  12721. * Bind a webGL buffer to the webGL context
  12722. * @param buffer defines the buffer to bind
  12723. */
  12724. Engine.prototype.bindArrayBuffer = function (buffer) {
  12725. if (!this._vaoRecordInProgress) {
  12726. this._unbindVertexArrayObject();
  12727. }
  12728. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12729. };
  12730. /**
  12731. * Bind an uniform buffer to the current webGL context
  12732. * @param buffer defines the buffer to bind
  12733. */
  12734. Engine.prototype.bindUniformBuffer = function (buffer) {
  12735. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12736. };
  12737. /**
  12738. * Bind a buffer to the current webGL context at a given location
  12739. * @param buffer defines the buffer to bind
  12740. * @param location defines the index where to bind the buffer
  12741. */
  12742. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12743. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12744. };
  12745. /**
  12746. * Bind a specific block at a given index in a specific shader program
  12747. * @param shaderProgram defines the shader program
  12748. * @param blockName defines the block name
  12749. * @param index defines the index where to bind the block
  12750. */
  12751. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12752. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12753. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12754. };
  12755. ;
  12756. Engine.prototype.bindIndexBuffer = function (buffer) {
  12757. if (!this._vaoRecordInProgress) {
  12758. this._unbindVertexArrayObject();
  12759. }
  12760. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12761. };
  12762. Engine.prototype.bindBuffer = function (buffer, target) {
  12763. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12764. this._gl.bindBuffer(target, buffer);
  12765. this._currentBoundBuffer[target] = buffer;
  12766. }
  12767. };
  12768. /**
  12769. * update the bound buffer with the given data
  12770. * @param data defines the data to update
  12771. */
  12772. Engine.prototype.updateArrayBuffer = function (data) {
  12773. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12774. };
  12775. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12776. var pointer = this._currentBufferPointers[indx];
  12777. var changed = false;
  12778. if (!pointer.active) {
  12779. changed = true;
  12780. pointer.active = true;
  12781. pointer.index = indx;
  12782. pointer.size = size;
  12783. pointer.type = type;
  12784. pointer.normalized = normalized;
  12785. pointer.stride = stride;
  12786. pointer.offset = offset;
  12787. pointer.buffer = buffer;
  12788. }
  12789. else {
  12790. if (pointer.buffer !== buffer) {
  12791. pointer.buffer = buffer;
  12792. changed = true;
  12793. }
  12794. if (pointer.size !== size) {
  12795. pointer.size = size;
  12796. changed = true;
  12797. }
  12798. if (pointer.type !== type) {
  12799. pointer.type = type;
  12800. changed = true;
  12801. }
  12802. if (pointer.normalized !== normalized) {
  12803. pointer.normalized = normalized;
  12804. changed = true;
  12805. }
  12806. if (pointer.stride !== stride) {
  12807. pointer.stride = stride;
  12808. changed = true;
  12809. }
  12810. if (pointer.offset !== offset) {
  12811. pointer.offset = offset;
  12812. changed = true;
  12813. }
  12814. }
  12815. if (changed || this._vaoRecordInProgress) {
  12816. this.bindArrayBuffer(buffer);
  12817. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12818. }
  12819. };
  12820. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12821. if (indexBuffer == null) {
  12822. return;
  12823. }
  12824. if (this._cachedIndexBuffer !== indexBuffer) {
  12825. this._cachedIndexBuffer = indexBuffer;
  12826. this.bindIndexBuffer(indexBuffer);
  12827. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12828. }
  12829. };
  12830. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12831. var attributes = effect.getAttributesNames();
  12832. if (!this._vaoRecordInProgress) {
  12833. this._unbindVertexArrayObject();
  12834. }
  12835. this.unbindAllAttributes();
  12836. for (var index = 0; index < attributes.length; index++) {
  12837. var order = effect.getAttributeLocation(index);
  12838. if (order >= 0) {
  12839. var vertexBuffer = vertexBuffers[attributes[index]];
  12840. if (!vertexBuffer) {
  12841. continue;
  12842. }
  12843. this._gl.enableVertexAttribArray(order);
  12844. if (!this._vaoRecordInProgress) {
  12845. this._vertexAttribArraysEnabled[order] = true;
  12846. }
  12847. var buffer = vertexBuffer.getBuffer();
  12848. if (buffer) {
  12849. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  12850. if (vertexBuffer.getIsInstanced()) {
  12851. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12852. if (!this._vaoRecordInProgress) {
  12853. this._currentInstanceLocations.push(order);
  12854. this._currentInstanceBuffers.push(buffer);
  12855. }
  12856. }
  12857. }
  12858. }
  12859. }
  12860. };
  12861. /**
  12862. * Records a vertex array object
  12863. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  12864. * @param vertexBuffers defines the list of vertex buffers to store
  12865. * @param indexBuffer defines the index buffer to store
  12866. * @param effect defines the effect to store
  12867. * @returns the new vertex array object
  12868. */
  12869. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12870. var vao = this._gl.createVertexArray();
  12871. this._vaoRecordInProgress = true;
  12872. this._gl.bindVertexArray(vao);
  12873. this._mustWipeVertexAttributes = true;
  12874. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12875. this.bindIndexBuffer(indexBuffer);
  12876. this._vaoRecordInProgress = false;
  12877. this._gl.bindVertexArray(null);
  12878. return vao;
  12879. };
  12880. /**
  12881. * Bind a specific vertex array object
  12882. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  12883. * @param vertexArrayObject defines the vertex array object to bind
  12884. * @param indexBuffer defines the index buffer to bind
  12885. */
  12886. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12887. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12888. this._cachedVertexArrayObject = vertexArrayObject;
  12889. this._gl.bindVertexArray(vertexArrayObject);
  12890. this._cachedVertexBuffers = null;
  12891. this._cachedIndexBuffer = null;
  12892. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12893. this._mustWipeVertexAttributes = true;
  12894. }
  12895. };
  12896. /**
  12897. * Bind webGl buffers directly to the webGL context
  12898. * @param vertexBuffer defines the vertex buffer to bind
  12899. * @param indexBuffer defines the index buffer to bind
  12900. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  12901. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  12902. * @param effect defines the effect associated with the vertex buffer
  12903. */
  12904. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12905. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12906. this._cachedVertexBuffers = vertexBuffer;
  12907. this._cachedEffectForVertexBuffers = effect;
  12908. var attributesCount = effect.getAttributesCount();
  12909. this._unbindVertexArrayObject();
  12910. this.unbindAllAttributes();
  12911. var offset = 0;
  12912. for (var index = 0; index < attributesCount; index++) {
  12913. if (index < vertexDeclaration.length) {
  12914. var order = effect.getAttributeLocation(index);
  12915. if (order >= 0) {
  12916. this._gl.enableVertexAttribArray(order);
  12917. this._vertexAttribArraysEnabled[order] = true;
  12918. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12919. }
  12920. offset += vertexDeclaration[index] * 4;
  12921. }
  12922. }
  12923. }
  12924. this._bindIndexBufferWithCache(indexBuffer);
  12925. };
  12926. Engine.prototype._unbindVertexArrayObject = function () {
  12927. if (!this._cachedVertexArrayObject) {
  12928. return;
  12929. }
  12930. this._cachedVertexArrayObject = null;
  12931. this._gl.bindVertexArray(null);
  12932. };
  12933. /**
  12934. * Bind a list of vertex buffers to the webGL context
  12935. * @param vertexBuffers defines the list of vertex buffers to bind
  12936. * @param indexBuffer defines the index buffer to bind
  12937. * @param effect defines the effect associated with the vertex buffers
  12938. */
  12939. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12940. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12941. this._cachedVertexBuffers = vertexBuffers;
  12942. this._cachedEffectForVertexBuffers = effect;
  12943. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12944. }
  12945. this._bindIndexBufferWithCache(indexBuffer);
  12946. };
  12947. /**
  12948. * Unbind all instance attributes
  12949. */
  12950. Engine.prototype.unbindInstanceAttributes = function () {
  12951. var boundBuffer;
  12952. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12953. var instancesBuffer = this._currentInstanceBuffers[i];
  12954. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12955. boundBuffer = instancesBuffer;
  12956. this.bindArrayBuffer(instancesBuffer);
  12957. }
  12958. var offsetLocation = this._currentInstanceLocations[i];
  12959. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12960. }
  12961. this._currentInstanceBuffers.length = 0;
  12962. this._currentInstanceLocations.length = 0;
  12963. };
  12964. /**
  12965. * Release and free the memory of a vertex array object
  12966. * @param vao defines the vertex array object to delete
  12967. */
  12968. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12969. this._gl.deleteVertexArray(vao);
  12970. };
  12971. /** @ignore */
  12972. Engine.prototype._releaseBuffer = function (buffer) {
  12973. buffer.references--;
  12974. if (buffer.references === 0) {
  12975. this._gl.deleteBuffer(buffer);
  12976. return true;
  12977. }
  12978. return false;
  12979. };
  12980. /**
  12981. * Creates a webGL buffer to use with instanciation
  12982. * @param capacity defines the size of the buffer
  12983. * @returns the webGL buffer
  12984. */
  12985. Engine.prototype.createInstancesBuffer = function (capacity) {
  12986. var buffer = this._gl.createBuffer();
  12987. if (!buffer) {
  12988. throw new Error("Unable to create instance buffer");
  12989. }
  12990. buffer.capacity = capacity;
  12991. this.bindArrayBuffer(buffer);
  12992. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12993. return buffer;
  12994. };
  12995. /**
  12996. * Delete a webGL buffer used with instanciation
  12997. * @param buffer defines the webGL buffer to delete
  12998. */
  12999. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13000. this._gl.deleteBuffer(buffer);
  13001. };
  13002. /**
  13003. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13004. * @param instancesBuffer defines the webGL buffer to update and bind
  13005. * @param data defines the data to store in the buffer
  13006. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13007. */
  13008. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13009. this.bindArrayBuffer(instancesBuffer);
  13010. if (data) {
  13011. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13012. }
  13013. if (offsetLocations[0].index !== undefined) {
  13014. var stride = 0;
  13015. for (var i = 0; i < offsetLocations.length; i++) {
  13016. var ai = offsetLocations[i];
  13017. stride += ai.attributeSize * 4;
  13018. }
  13019. for (var i = 0; i < offsetLocations.length; i++) {
  13020. var ai = offsetLocations[i];
  13021. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13022. this._gl.enableVertexAttribArray(ai.index);
  13023. this._vertexAttribArraysEnabled[ai.index] = true;
  13024. }
  13025. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13026. this._gl.vertexAttribDivisor(ai.index, 1);
  13027. this._currentInstanceLocations.push(ai.index);
  13028. this._currentInstanceBuffers.push(instancesBuffer);
  13029. }
  13030. }
  13031. else {
  13032. for (var index = 0; index < 4; index++) {
  13033. var offsetLocation = offsetLocations[index];
  13034. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13035. this._gl.enableVertexAttribArray(offsetLocation);
  13036. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13037. }
  13038. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13039. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13040. this._currentInstanceLocations.push(offsetLocation);
  13041. this._currentInstanceBuffers.push(instancesBuffer);
  13042. }
  13043. }
  13044. };
  13045. /**
  13046. * Apply all cached states (depth, culling, stencil and alpha)
  13047. */
  13048. Engine.prototype.applyStates = function () {
  13049. this._depthCullingState.apply(this._gl);
  13050. this._stencilState.apply(this._gl);
  13051. this._alphaState.apply(this._gl);
  13052. };
  13053. /**
  13054. * Send a draw order
  13055. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13056. * @param indexStart defines the starting index
  13057. * @param indexCount defines the number of index to draw
  13058. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13059. */
  13060. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13061. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13062. };
  13063. /**
  13064. * Draw a list of points
  13065. * @param verticesStart defines the index of first vertex to draw
  13066. * @param verticesCount defines the count of vertices to draw
  13067. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13068. */
  13069. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13070. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13071. };
  13072. /**
  13073. * Draw a list of unindexed primitives
  13074. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13075. * @param verticesStart defines the index of first vertex to draw
  13076. * @param verticesCount defines the count of vertices to draw
  13077. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13078. */
  13079. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13080. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13081. };
  13082. /**
  13083. * Draw a list of indexed primitives
  13084. * @param fillMode defines the primitive to use
  13085. * @param indexStart defines the starting index
  13086. * @param indexCount defines the number of index to draw
  13087. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13088. */
  13089. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13090. // Apply states
  13091. this.applyStates();
  13092. this._drawCalls.addCount(1, false);
  13093. // Render
  13094. var drawMode = this._drawMode(fillMode);
  13095. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13096. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13097. if (instancesCount) {
  13098. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13099. }
  13100. else {
  13101. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13102. }
  13103. };
  13104. /**
  13105. * Draw a list of unindexed primitives
  13106. * @param fillMode defines the primitive to use
  13107. * @param verticesStart defines the index of first vertex to draw
  13108. * @param verticesCount defines the count of vertices to draw
  13109. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13110. */
  13111. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13112. // Apply states
  13113. this.applyStates();
  13114. this._drawCalls.addCount(1, false);
  13115. var drawMode = this._drawMode(fillMode);
  13116. if (instancesCount) {
  13117. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13118. }
  13119. else {
  13120. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13121. }
  13122. };
  13123. Engine.prototype._drawMode = function (fillMode) {
  13124. switch (fillMode) {
  13125. // Triangle views
  13126. case BABYLON.Material.TriangleFillMode:
  13127. return this._gl.TRIANGLES;
  13128. case BABYLON.Material.PointFillMode:
  13129. return this._gl.POINTS;
  13130. case BABYLON.Material.WireFrameFillMode:
  13131. return this._gl.LINES;
  13132. // Draw modes
  13133. case BABYLON.Material.PointListDrawMode:
  13134. return this._gl.POINTS;
  13135. case BABYLON.Material.LineListDrawMode:
  13136. return this._gl.LINES;
  13137. case BABYLON.Material.LineLoopDrawMode:
  13138. return this._gl.LINE_LOOP;
  13139. case BABYLON.Material.LineStripDrawMode:
  13140. return this._gl.LINE_STRIP;
  13141. case BABYLON.Material.TriangleStripDrawMode:
  13142. return this._gl.TRIANGLE_STRIP;
  13143. case BABYLON.Material.TriangleFanDrawMode:
  13144. return this._gl.TRIANGLE_FAN;
  13145. default:
  13146. return this._gl.TRIANGLES;
  13147. }
  13148. };
  13149. // Shaders
  13150. /** @ignore */
  13151. Engine.prototype._releaseEffect = function (effect) {
  13152. if (this._compiledEffects[effect._key]) {
  13153. delete this._compiledEffects[effect._key];
  13154. this._deleteProgram(effect.getProgram());
  13155. }
  13156. };
  13157. /** @ignore */
  13158. Engine.prototype._deleteProgram = function (program) {
  13159. if (program) {
  13160. program.__SPECTOR_rebuildProgram = null;
  13161. if (program.transformFeedback) {
  13162. this.deleteTransformFeedback(program.transformFeedback);
  13163. program.transformFeedback = null;
  13164. }
  13165. this._gl.deleteProgram(program);
  13166. }
  13167. };
  13168. /**
  13169. * Create a new effect (used to store vertex/fragment shaders)
  13170. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13171. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13172. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13173. * @param samplers defines an array of string used to represent textures
  13174. * @param defines defines the string containing the defines to use to compile the shaders
  13175. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13176. * @param onCompiled defines a function to call when the effect creation is successful
  13177. * @param onError defines a function to call when the effect creation has failed
  13178. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13179. * @returns the new Effect
  13180. */
  13181. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13182. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13183. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13184. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13185. if (this._compiledEffects[name]) {
  13186. var compiledEffect = this._compiledEffects[name];
  13187. if (onCompiled && compiledEffect.isReady()) {
  13188. onCompiled(compiledEffect);
  13189. }
  13190. return compiledEffect;
  13191. }
  13192. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13193. effect._key = name;
  13194. this._compiledEffects[name] = effect;
  13195. return effect;
  13196. };
  13197. /**
  13198. * Create an effect to use with particle systems
  13199. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13200. * @param uniformsNames defines a list of attribute names
  13201. * @param samplers defines an array of string used to represent textures
  13202. * @param defines defines the string containing the defines to use to compile the shaders
  13203. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13204. * @param onCompiled defines a function to call when the effect creation is successful
  13205. * @param onError defines a function to call when the effect creation has failed
  13206. * @returns the new Effect
  13207. */
  13208. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13209. if (uniformsNames === void 0) { uniformsNames = []; }
  13210. if (samplers === void 0) { samplers = []; }
  13211. if (defines === void 0) { defines = ""; }
  13212. return this.createEffect({
  13213. vertex: "particles",
  13214. fragmentElement: fragmentName
  13215. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13216. };
  13217. /**
  13218. * Directly creates a webGL program
  13219. * @param vertexCode defines the vertex shader code to use
  13220. * @param fragmentCode defines the fragment shader code to use
  13221. * @param context defines the webGL context to use (if not set, the current one will be used)
  13222. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13223. * @returns the new webGL program
  13224. */
  13225. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13226. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13227. context = context || this._gl;
  13228. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13229. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13230. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13231. };
  13232. /**
  13233. * Creates a webGL program
  13234. * @param vertexCode defines the vertex shader code to use
  13235. * @param fragmentCode defines the fragment shader code to use
  13236. * @param defines defines the string containing the defines to use to compile the shaders
  13237. * @param context defines the webGL context to use (if not set, the current one will be used)
  13238. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13239. * @returns the new webGL program
  13240. */
  13241. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13242. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13243. context = context || this._gl;
  13244. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13245. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13246. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13247. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13248. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13249. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13250. return program;
  13251. };
  13252. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13253. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13254. var shaderProgram = context.createProgram();
  13255. if (!shaderProgram) {
  13256. throw new Error("Unable to create program");
  13257. }
  13258. context.attachShader(shaderProgram, vertexShader);
  13259. context.attachShader(shaderProgram, fragmentShader);
  13260. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13261. var transformFeedback = this.createTransformFeedback();
  13262. this.bindTransformFeedback(transformFeedback);
  13263. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13264. shaderProgram.transformFeedback = transformFeedback;
  13265. }
  13266. context.linkProgram(shaderProgram);
  13267. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13268. this.bindTransformFeedback(null);
  13269. }
  13270. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13271. if (!linked) {
  13272. context.validateProgram(shaderProgram);
  13273. var error = context.getProgramInfoLog(shaderProgram);
  13274. if (error) {
  13275. throw new Error(error);
  13276. }
  13277. }
  13278. context.deleteShader(vertexShader);
  13279. context.deleteShader(fragmentShader);
  13280. return shaderProgram;
  13281. };
  13282. /**
  13283. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13284. * @param shaderProgram defines the webGL program to use
  13285. * @param uniformsNames defines the list of uniform names
  13286. * @returns an array of webGL uniform locations
  13287. */
  13288. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13289. var results = new Array();
  13290. for (var index = 0; index < uniformsNames.length; index++) {
  13291. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13292. }
  13293. return results;
  13294. };
  13295. /**
  13296. * Gets the lsit of active attributes for a given webGL program
  13297. * @param shaderProgram defines the webGL program to use
  13298. * @param attributesNames defines the list of attribute names to get
  13299. * @returns an array of indices indicating the offset of each attribute
  13300. */
  13301. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13302. var results = [];
  13303. for (var index = 0; index < attributesNames.length; index++) {
  13304. try {
  13305. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13306. }
  13307. catch (e) {
  13308. results.push(-1);
  13309. }
  13310. }
  13311. return results;
  13312. };
  13313. /**
  13314. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13315. * @param effect defines the effect to activate
  13316. */
  13317. Engine.prototype.enableEffect = function (effect) {
  13318. if (!effect) {
  13319. return;
  13320. }
  13321. // Use program
  13322. this.bindSamplers(effect);
  13323. this._currentEffect = effect;
  13324. if (effect.onBind) {
  13325. effect.onBind(effect);
  13326. }
  13327. effect.onBindObservable.notifyObservers(effect);
  13328. };
  13329. /**
  13330. * Set the value of an uniform to an array of int32
  13331. * @param uniform defines the webGL uniform location where to store the value
  13332. * @param array defines the array of int32 to store
  13333. */
  13334. Engine.prototype.setIntArray = function (uniform, array) {
  13335. if (!uniform)
  13336. return;
  13337. this._gl.uniform1iv(uniform, array);
  13338. };
  13339. /**
  13340. * Set the value of an uniform to an array of int32 (stored as vec2)
  13341. * @param uniform defines the webGL uniform location where to store the value
  13342. * @param array defines the array of int32 to store
  13343. */
  13344. Engine.prototype.setIntArray2 = function (uniform, array) {
  13345. if (!uniform || array.length % 2 !== 0)
  13346. return;
  13347. this._gl.uniform2iv(uniform, array);
  13348. };
  13349. /**
  13350. * Set the value of an uniform to an array of int32 (stored as vec3)
  13351. * @param uniform defines the webGL uniform location where to store the value
  13352. * @param array defines the array of int32 to store
  13353. */
  13354. Engine.prototype.setIntArray3 = function (uniform, array) {
  13355. if (!uniform || array.length % 3 !== 0)
  13356. return;
  13357. this._gl.uniform3iv(uniform, array);
  13358. };
  13359. /**
  13360. * Set the value of an uniform to an array of int32 (stored as vec4)
  13361. * @param uniform defines the webGL uniform location where to store the value
  13362. * @param array defines the array of int32 to store
  13363. */
  13364. Engine.prototype.setIntArray4 = function (uniform, array) {
  13365. if (!uniform || array.length % 4 !== 0)
  13366. return;
  13367. this._gl.uniform4iv(uniform, array);
  13368. };
  13369. /**
  13370. * Set the value of an uniform to an array of float32
  13371. * @param uniform defines the webGL uniform location where to store the value
  13372. * @param array defines the array of float32 to store
  13373. */
  13374. Engine.prototype.setFloatArray = function (uniform, array) {
  13375. if (!uniform)
  13376. return;
  13377. this._gl.uniform1fv(uniform, array);
  13378. };
  13379. /**
  13380. * Set the value of an uniform to an array of float32 (stored as vec2)
  13381. * @param uniform defines the webGL uniform location where to store the value
  13382. * @param array defines the array of float32 to store
  13383. */
  13384. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13385. if (!uniform || array.length % 2 !== 0)
  13386. return;
  13387. this._gl.uniform2fv(uniform, array);
  13388. };
  13389. /**
  13390. * Set the value of an uniform to an array of float32 (stored as vec3)
  13391. * @param uniform defines the webGL uniform location where to store the value
  13392. * @param array defines the array of float32 to store
  13393. */
  13394. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13395. if (!uniform || array.length % 3 !== 0)
  13396. return;
  13397. this._gl.uniform3fv(uniform, array);
  13398. };
  13399. /**
  13400. * Set the value of an uniform to an array of float32 (stored as vec4)
  13401. * @param uniform defines the webGL uniform location where to store the value
  13402. * @param array defines the array of float32 to store
  13403. */
  13404. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13405. if (!uniform || array.length % 4 !== 0)
  13406. return;
  13407. this._gl.uniform4fv(uniform, array);
  13408. };
  13409. /**
  13410. * Set the value of an uniform to an array of number
  13411. * @param uniform defines the webGL uniform location where to store the value
  13412. * @param array defines the array of number to store
  13413. */
  13414. Engine.prototype.setArray = function (uniform, array) {
  13415. if (!uniform)
  13416. return;
  13417. this._gl.uniform1fv(uniform, array);
  13418. };
  13419. /**
  13420. * Set the value of an uniform to an array of number (stored as vec2)
  13421. * @param uniform defines the webGL uniform location where to store the value
  13422. * @param array defines the array of number to store
  13423. */
  13424. Engine.prototype.setArray2 = function (uniform, array) {
  13425. if (!uniform || array.length % 2 !== 0)
  13426. return;
  13427. this._gl.uniform2fv(uniform, array);
  13428. };
  13429. /**
  13430. * Set the value of an uniform to an array of number (stored as vec3)
  13431. * @param uniform defines the webGL uniform location where to store the value
  13432. * @param array defines the array of number to store
  13433. */
  13434. Engine.prototype.setArray3 = function (uniform, array) {
  13435. if (!uniform || array.length % 3 !== 0)
  13436. return;
  13437. this._gl.uniform3fv(uniform, array);
  13438. };
  13439. /**
  13440. * Set the value of an uniform to an array of number (stored as vec4)
  13441. * @param uniform defines the webGL uniform location where to store the value
  13442. * @param array defines the array of number to store
  13443. */
  13444. Engine.prototype.setArray4 = function (uniform, array) {
  13445. if (!uniform || array.length % 4 !== 0)
  13446. return;
  13447. this._gl.uniform4fv(uniform, array);
  13448. };
  13449. /**
  13450. * Set the value of an uniform to an array of float32 (stored as matrices)
  13451. * @param uniform defines the webGL uniform location where to store the value
  13452. * @param matrices defines the array of float32 to store
  13453. */
  13454. Engine.prototype.setMatrices = function (uniform, matrices) {
  13455. if (!uniform)
  13456. return;
  13457. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13458. };
  13459. /**
  13460. * Set the value of an uniform to a matrix
  13461. * @param uniform defines the webGL uniform location where to store the value
  13462. * @param matrix defines the matrix to store
  13463. */
  13464. Engine.prototype.setMatrix = function (uniform, matrix) {
  13465. if (!uniform)
  13466. return;
  13467. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13468. };
  13469. /**
  13470. * Set the value of an uniform to a matrix (3x3)
  13471. * @param uniform defines the webGL uniform location where to store the value
  13472. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13473. */
  13474. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13475. if (!uniform)
  13476. return;
  13477. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13478. };
  13479. /**
  13480. * Set the value of an uniform to a matrix (2x2)
  13481. * @param uniform defines the webGL uniform location where to store the value
  13482. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13483. */
  13484. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13485. if (!uniform)
  13486. return;
  13487. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13488. };
  13489. /**
  13490. * Set the value of an uniform to a number (int)
  13491. * @param uniform defines the webGL uniform location where to store the value
  13492. * @param value defines the int number to store
  13493. */
  13494. Engine.prototype.setInt = function (uniform, value) {
  13495. if (!uniform)
  13496. return;
  13497. this._gl.uniform1i(uniform, value);
  13498. };
  13499. /**
  13500. * Set the value of an uniform to a number (float)
  13501. * @param uniform defines the webGL uniform location where to store the value
  13502. * @param value defines the float number to store
  13503. */
  13504. Engine.prototype.setFloat = function (uniform, value) {
  13505. if (!uniform)
  13506. return;
  13507. this._gl.uniform1f(uniform, value);
  13508. };
  13509. /**
  13510. * Set the value of an uniform to a vec2
  13511. * @param uniform defines the webGL uniform location where to store the value
  13512. * @param x defines the 1st component of the value
  13513. * @param y defines the 2nd component of the value
  13514. */
  13515. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13516. if (!uniform)
  13517. return;
  13518. this._gl.uniform2f(uniform, x, y);
  13519. };
  13520. /**
  13521. * Set the value of an uniform to a vec3
  13522. * @param uniform defines the webGL uniform location where to store the value
  13523. * @param x defines the 1st component of the value
  13524. * @param y defines the 2nd component of the value
  13525. * @param z defines the 3rd component of the value
  13526. */
  13527. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13528. if (!uniform)
  13529. return;
  13530. this._gl.uniform3f(uniform, x, y, z);
  13531. };
  13532. /**
  13533. * Set the value of an uniform to a boolean
  13534. * @param uniform defines the webGL uniform location where to store the value
  13535. * @param bool defines the boolean to store
  13536. */
  13537. Engine.prototype.setBool = function (uniform, bool) {
  13538. if (!uniform)
  13539. return;
  13540. this._gl.uniform1i(uniform, bool);
  13541. };
  13542. /**
  13543. * Set the value of an uniform to a vec4
  13544. * @param uniform defines the webGL uniform location where to store the value
  13545. * @param x defines the 1st component of the value
  13546. * @param y defines the 2nd component of the value
  13547. * @param z defines the 3rd component of the value
  13548. * @param w defines the 4th component of the value
  13549. */
  13550. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13551. if (!uniform)
  13552. return;
  13553. this._gl.uniform4f(uniform, x, y, z, w);
  13554. };
  13555. /**
  13556. * Set the value of an uniform to a Color3
  13557. * @param uniform defines the webGL uniform location where to store the value
  13558. * @param color3 defines the color to store
  13559. */
  13560. Engine.prototype.setColor3 = function (uniform, color3) {
  13561. if (!uniform)
  13562. return;
  13563. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13564. };
  13565. /**
  13566. * Set the value of an uniform to a Color3 and an alpha value
  13567. * @param uniform defines the webGL uniform location where to store the value
  13568. * @param color3 defines the color to store
  13569. * @param alpha defines the alpha component to store
  13570. */
  13571. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13572. if (!uniform)
  13573. return;
  13574. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13575. };
  13576. /**
  13577. * Sets a Color4 on a uniform variable
  13578. * @param uniform defines the uniform location
  13579. * @param color4 defines the value to be set
  13580. */
  13581. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13582. if (!uniform)
  13583. return;
  13584. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13585. };
  13586. // States
  13587. /**
  13588. * Set various states to the webGL context
  13589. * @param culling defines backface culling state
  13590. * @param zOffset defines the value to apply to zOffset (0 by default)
  13591. * @param force defines if states must be applied even if cache is up to date
  13592. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13593. */
  13594. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13595. if (zOffset === void 0) { zOffset = 0; }
  13596. if (reverseSide === void 0) { reverseSide = false; }
  13597. // Culling
  13598. if (this._depthCullingState.cull !== culling || force) {
  13599. this._depthCullingState.cull = culling;
  13600. }
  13601. // Cull face
  13602. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13603. if (this._depthCullingState.cullFace !== cullFace || force) {
  13604. this._depthCullingState.cullFace = cullFace;
  13605. }
  13606. // Z offset
  13607. this.setZOffset(zOffset);
  13608. // Front face
  13609. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13610. if (this._depthCullingState.frontFace !== frontFace || force) {
  13611. this._depthCullingState.frontFace = frontFace;
  13612. }
  13613. };
  13614. /**
  13615. * Set the z offset to apply to current rendering
  13616. * @param value defines the offset to apply
  13617. */
  13618. Engine.prototype.setZOffset = function (value) {
  13619. this._depthCullingState.zOffset = value;
  13620. };
  13621. /**
  13622. * Gets the current value of the zOffset
  13623. * @returns the current zOffset state
  13624. */
  13625. Engine.prototype.getZOffset = function () {
  13626. return this._depthCullingState.zOffset;
  13627. };
  13628. /**
  13629. * Enable or disable depth buffering
  13630. * @param enable defines the state to set
  13631. */
  13632. Engine.prototype.setDepthBuffer = function (enable) {
  13633. this._depthCullingState.depthTest = enable;
  13634. };
  13635. /**
  13636. * Gets a boolean indicating if depth writing is enabled
  13637. * @returns the current depth writing state
  13638. */
  13639. Engine.prototype.getDepthWrite = function () {
  13640. return this._depthCullingState.depthMask;
  13641. };
  13642. /**
  13643. * Enable or disable depth writing
  13644. * @param enable defines the state to set
  13645. */
  13646. Engine.prototype.setDepthWrite = function (enable) {
  13647. this._depthCullingState.depthMask = enable;
  13648. };
  13649. /**
  13650. * Enable or disable color writing
  13651. * @param enable defines the state to set
  13652. */
  13653. Engine.prototype.setColorWrite = function (enable) {
  13654. this._gl.colorMask(enable, enable, enable, enable);
  13655. this._colorWrite = enable;
  13656. };
  13657. /**
  13658. * Gets a boolean indicating if color writing is enabled
  13659. * @returns the current color writing state
  13660. */
  13661. Engine.prototype.getColorWrite = function () {
  13662. return this._colorWrite;
  13663. };
  13664. /**
  13665. * Sets alpha constants used by some alpha blending modes
  13666. * @param r defines the red component
  13667. * @param g defines the green component
  13668. * @param b defines the blue component
  13669. * @param a defines the alpha component
  13670. */
  13671. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13672. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13673. };
  13674. /**
  13675. * Sets the current alpha mode
  13676. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  13677. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  13678. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13679. */
  13680. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13681. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13682. if (this._alphaMode === mode) {
  13683. return;
  13684. }
  13685. switch (mode) {
  13686. case Engine.ALPHA_DISABLE:
  13687. this._alphaState.alphaBlend = false;
  13688. break;
  13689. case Engine.ALPHA_PREMULTIPLIED:
  13690. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13691. this._alphaState.alphaBlend = true;
  13692. break;
  13693. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13694. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13695. this._alphaState.alphaBlend = true;
  13696. break;
  13697. case Engine.ALPHA_COMBINE:
  13698. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13699. this._alphaState.alphaBlend = true;
  13700. break;
  13701. case Engine.ALPHA_ONEONE:
  13702. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13703. this._alphaState.alphaBlend = true;
  13704. break;
  13705. case Engine.ALPHA_ADD:
  13706. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13707. this._alphaState.alphaBlend = true;
  13708. break;
  13709. case Engine.ALPHA_SUBTRACT:
  13710. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13711. this._alphaState.alphaBlend = true;
  13712. break;
  13713. case Engine.ALPHA_MULTIPLY:
  13714. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13715. this._alphaState.alphaBlend = true;
  13716. break;
  13717. case Engine.ALPHA_MAXIMIZED:
  13718. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13719. this._alphaState.alphaBlend = true;
  13720. break;
  13721. case Engine.ALPHA_INTERPOLATE:
  13722. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13723. this._alphaState.alphaBlend = true;
  13724. break;
  13725. case Engine.ALPHA_SCREENMODE:
  13726. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13727. this._alphaState.alphaBlend = true;
  13728. break;
  13729. }
  13730. if (!noDepthWriteChange) {
  13731. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13732. }
  13733. this._alphaMode = mode;
  13734. };
  13735. /**
  13736. * Gets the current alpha mode
  13737. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13738. * @returns the current alpha mode
  13739. */
  13740. Engine.prototype.getAlphaMode = function () {
  13741. return this._alphaMode;
  13742. };
  13743. // Textures
  13744. /**
  13745. * Force the entire cache to be cleared
  13746. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  13747. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  13748. */
  13749. Engine.prototype.wipeCaches = function (bruteForce) {
  13750. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13751. return;
  13752. }
  13753. this._currentEffect = null;
  13754. if (bruteForce) {
  13755. this.resetTextureCache();
  13756. this._currentProgram = null;
  13757. this._stencilState.reset();
  13758. this._depthCullingState.reset();
  13759. this.setDepthFunctionToLessOrEqual();
  13760. this._alphaState.reset();
  13761. }
  13762. this._resetVertexBufferBinding();
  13763. this._cachedIndexBuffer = null;
  13764. this._cachedEffectForVertexBuffers = null;
  13765. this._unbindVertexArrayObject();
  13766. this.bindIndexBuffer(null);
  13767. };
  13768. /**
  13769. * Set the compressed texture format to use, based on the formats you have, and the formats
  13770. * supported by the hardware / browser.
  13771. *
  13772. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13773. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13774. * to API arguments needed to compressed textures. This puts the burden on the container
  13775. * generator to house the arcane code for determining these for current & future formats.
  13776. *
  13777. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13778. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13779. *
  13780. * Note: The result of this call is not taken into account when a texture is base64.
  13781. *
  13782. * @param formatsAvailable defines the list of those format families you have created
  13783. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13784. *
  13785. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13786. * @returns The extension selected.
  13787. */
  13788. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13789. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13790. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13791. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13792. return this._textureFormatInUse = this._texturesSupported[i];
  13793. }
  13794. }
  13795. }
  13796. // actively set format to nothing, to allow this to be called more than once
  13797. // and possibly fail the 2nd time
  13798. this._textureFormatInUse = null;
  13799. return null;
  13800. };
  13801. /** @ignore */
  13802. Engine.prototype._createTexture = function () {
  13803. var texture = this._gl.createTexture();
  13804. if (!texture) {
  13805. throw new Error("Unable to create texture");
  13806. }
  13807. return texture;
  13808. };
  13809. /**
  13810. * Usually called from BABYLON.Texture.ts.
  13811. * Passed information to create a WebGLTexture
  13812. * @param urlArg defines a value which contains one of the following:
  13813. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  13814. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13815. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13816. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  13817. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  13818. * @param scene needed for loading to the correct scene
  13819. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  13820. * @param onLoad optional callback to be called upon successful completion
  13821. * @param onError optional callback to be called upon failure
  13822. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13823. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  13824. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  13825. * @returns a InternalTexture for assignment back into BABYLON.Texture
  13826. */
  13827. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  13828. var _this = this;
  13829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13830. if (onLoad === void 0) { onLoad = null; }
  13831. if (onError === void 0) { onError = null; }
  13832. if (buffer === void 0) { buffer = null; }
  13833. if (fallback === void 0) { fallback = null; }
  13834. if (format === void 0) { format = null; }
  13835. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13836. var fromData = url.substr(0, 5) === "data:";
  13837. var fromBlob = url.substr(0, 5) === "blob:";
  13838. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13839. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13840. // establish the file extension, if possible
  13841. var lastDot = url.lastIndexOf('.');
  13842. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13843. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13844. var isTGA = (extension.indexOf(".tga") === 0);
  13845. // determine if a ktx file should be substituted
  13846. var isKTX = false;
  13847. if (this._textureFormatInUse && !isBase64 && !fallback) {
  13848. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13849. isKTX = true;
  13850. }
  13851. if (scene) {
  13852. scene._addPendingData(texture);
  13853. }
  13854. texture.url = url;
  13855. texture.generateMipMaps = !noMipmap;
  13856. texture.samplingMode = samplingMode;
  13857. texture.invertY = invertY;
  13858. if (!this._doNotHandleContextLost) {
  13859. // Keep a link to the buffer only if we plan to handle context lost
  13860. texture._buffer = buffer;
  13861. }
  13862. var onLoadObserver = null;
  13863. if (onLoad && !fallback) {
  13864. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13865. }
  13866. if (!fallback)
  13867. this._internalTexturesCache.push(texture);
  13868. var onerror = function (message, exception) {
  13869. if (scene) {
  13870. scene._removePendingData(texture);
  13871. }
  13872. if (onLoadObserver) {
  13873. texture.onLoadedObservable.remove(onLoadObserver);
  13874. }
  13875. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13876. if (isKTX) {
  13877. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13878. }
  13879. else if (BABYLON.Tools.UseFallbackTexture) {
  13880. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13881. }
  13882. if (onError) {
  13883. onError(message || "Unknown error", exception);
  13884. }
  13885. };
  13886. var callback = null;
  13887. // processing for non-image formats
  13888. if (isKTX || isTGA || isDDS) {
  13889. if (isKTX) {
  13890. callback = function (data) {
  13891. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13892. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13893. ktx.uploadLevels(_this._gl, !noMipmap);
  13894. return false;
  13895. }, samplingMode);
  13896. };
  13897. }
  13898. else if (isTGA) {
  13899. callback = function (arrayBuffer) {
  13900. var data = new Uint8Array(arrayBuffer);
  13901. var header = BABYLON.TGATools.GetTGAHeader(data);
  13902. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13903. BABYLON.TGATools.UploadContent(_this._gl, data);
  13904. return false;
  13905. }, samplingMode);
  13906. };
  13907. }
  13908. else if (isDDS) {
  13909. callback = function (data) {
  13910. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13911. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13912. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13913. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13914. return false;
  13915. }, samplingMode);
  13916. };
  13917. }
  13918. if (!buffer) {
  13919. this._loadFile(url, function (data) {
  13920. if (callback) {
  13921. callback(data);
  13922. }
  13923. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13924. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13925. });
  13926. }
  13927. else {
  13928. if (callback) {
  13929. callback(buffer);
  13930. }
  13931. }
  13932. // image format processing
  13933. }
  13934. else {
  13935. var onload = function (img) {
  13936. if (fromBlob && !_this._doNotHandleContextLost) {
  13937. // We need to store the image if we need to rebuild the texture
  13938. // in case of a webgl context lost
  13939. texture._buffer = img;
  13940. }
  13941. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13942. var gl = _this._gl;
  13943. var isPot = (img.width === potWidth && img.height === potHeight);
  13944. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13945. if (isPot) {
  13946. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13947. return false;
  13948. }
  13949. // Using shaders to rescale because canvas.drawImage is lossy
  13950. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13951. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13952. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13954. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13955. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13956. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13957. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13958. _this._releaseTexture(source);
  13959. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13960. continuationCallback();
  13961. });
  13962. return true;
  13963. }, samplingMode);
  13964. };
  13965. if (!fromData || isBase64)
  13966. if (buffer instanceof HTMLImageElement) {
  13967. onload(buffer);
  13968. }
  13969. else {
  13970. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13971. }
  13972. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13973. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13974. else
  13975. onload(buffer);
  13976. }
  13977. return texture;
  13978. };
  13979. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13980. var _this = this;
  13981. var rtt = this.createRenderTargetTexture({
  13982. width: destination.width,
  13983. height: destination.height,
  13984. }, {
  13985. generateMipMaps: false,
  13986. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13987. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13988. generateDepthBuffer: false,
  13989. generateStencilBuffer: false
  13990. });
  13991. if (!this._rescalePostProcess) {
  13992. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13993. }
  13994. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13995. _this._rescalePostProcess.onApply = function (effect) {
  13996. effect._bindTexture("textureSampler", source);
  13997. };
  13998. var hostingScene = scene;
  13999. if (!hostingScene) {
  14000. hostingScene = _this.scenes[_this.scenes.length - 1];
  14001. }
  14002. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14003. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14004. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14005. _this.unBindFramebuffer(rtt);
  14006. _this._releaseTexture(rtt);
  14007. if (onComplete) {
  14008. onComplete();
  14009. }
  14010. });
  14011. };
  14012. /**
  14013. * Update a raw texture
  14014. * @param texture defines the texture to update
  14015. * @param data defines the data to store in the texture
  14016. * @param format defines the format of the data
  14017. * @param invertY defines if data must be stored with Y axis inverted
  14018. * @param compression defines the compression used (null by default)
  14019. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14020. */
  14021. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14022. if (compression === void 0) { compression = null; }
  14023. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14024. if (!texture) {
  14025. return;
  14026. }
  14027. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14028. var internalFormat = this._getInternalFormat(format);
  14029. var textureType = this._getWebGLTextureType(type);
  14030. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14031. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14032. if (!this._doNotHandleContextLost) {
  14033. texture._bufferView = data;
  14034. texture.format = format;
  14035. texture.type = type;
  14036. texture.invertY = invertY;
  14037. texture._compression = compression;
  14038. }
  14039. if (texture.width % 4 !== 0) {
  14040. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14041. }
  14042. if (compression && data) {
  14043. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14044. }
  14045. else {
  14046. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14047. }
  14048. if (texture.generateMipMaps) {
  14049. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14050. }
  14051. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14052. // this.resetTextureCache();
  14053. texture.isReady = true;
  14054. };
  14055. /**
  14056. * Creates a raw texture
  14057. * @param data defines the data to store in the texture
  14058. * @param width defines the width of the texture
  14059. * @param height defines the height of the texture
  14060. * @param format defines the format of the data
  14061. * @param generateMipMaps defines if the engine should generate the mip levels
  14062. * @param invertY defines if data must be stored with Y axis inverted
  14063. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14064. * @param compression defines the compression used (null by default)
  14065. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14066. * @returns the raw texture inside an InternalTexture
  14067. */
  14068. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14069. if (compression === void 0) { compression = null; }
  14070. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14071. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14072. texture.baseWidth = width;
  14073. texture.baseHeight = height;
  14074. texture.width = width;
  14075. texture.height = height;
  14076. texture.format = format;
  14077. texture.generateMipMaps = generateMipMaps;
  14078. texture.samplingMode = samplingMode;
  14079. texture.invertY = invertY;
  14080. texture._compression = compression;
  14081. texture.type = type;
  14082. if (!this._doNotHandleContextLost) {
  14083. texture._bufferView = data;
  14084. }
  14085. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14086. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14087. // Filters
  14088. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14089. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14090. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14091. if (generateMipMaps) {
  14092. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14093. }
  14094. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14095. this._internalTexturesCache.push(texture);
  14096. return texture;
  14097. };
  14098. /**
  14099. * Creates a dynamic texture
  14100. * @param width defines the width of the texture
  14101. * @param height defines the height of the texture
  14102. * @param generateMipMaps defines if the engine should generate the mip levels
  14103. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14104. * @returns the dynamic texture inside an InternalTexture
  14105. */
  14106. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14107. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14108. texture.baseWidth = width;
  14109. texture.baseHeight = height;
  14110. if (generateMipMaps) {
  14111. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14112. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14113. }
  14114. // this.resetTextureCache();
  14115. texture.width = width;
  14116. texture.height = height;
  14117. texture.isReady = false;
  14118. texture.generateMipMaps = generateMipMaps;
  14119. texture.samplingMode = samplingMode;
  14120. this.updateTextureSamplingMode(samplingMode, texture);
  14121. this._internalTexturesCache.push(texture);
  14122. return texture;
  14123. };
  14124. /**
  14125. * Update the sampling mode of a given texture
  14126. * @param samplingMode defines the required sampling mode
  14127. * @param texture defines the texture to update
  14128. */
  14129. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14130. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14131. if (texture.isCube) {
  14132. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14133. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14134. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14135. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14136. }
  14137. else if (texture.is3D) {
  14138. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14139. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14140. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14141. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14142. }
  14143. else {
  14144. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14145. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14146. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14147. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14148. }
  14149. texture.samplingMode = samplingMode;
  14150. };
  14151. /**
  14152. * Update the content of a dynamic texture
  14153. * @param texture defines the texture to update
  14154. * @param canvas defines the canvas containing the source
  14155. * @param invertY defines if data must be stored with Y axis inverted
  14156. * @param premulAlpha defines if alpha is stored as premultiplied
  14157. * @param format defines the format of the data
  14158. */
  14159. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14160. if (premulAlpha === void 0) { premulAlpha = false; }
  14161. if (!texture) {
  14162. return;
  14163. }
  14164. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14165. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14166. if (premulAlpha) {
  14167. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14168. }
  14169. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14170. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14171. if (texture.generateMipMaps) {
  14172. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14173. }
  14174. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14175. if (premulAlpha) {
  14176. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14177. }
  14178. texture.isReady = true;
  14179. };
  14180. /**
  14181. * Update a video texture
  14182. * @param texture defines the texture to update
  14183. * @param video defines the video element to use
  14184. * @param invertY defines if data must be stored with Y axis inverted
  14185. */
  14186. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14187. if (!texture || texture._isDisabled) {
  14188. return;
  14189. }
  14190. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14191. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14192. try {
  14193. // Testing video texture support
  14194. if (this._videoTextureSupported === undefined) {
  14195. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14196. if (this._gl.getError() !== 0) {
  14197. this._videoTextureSupported = false;
  14198. }
  14199. else {
  14200. this._videoTextureSupported = true;
  14201. }
  14202. }
  14203. // Copy video through the current working canvas if video texture is not supported
  14204. if (!this._videoTextureSupported) {
  14205. if (!texture._workingCanvas) {
  14206. texture._workingCanvas = document.createElement("canvas");
  14207. var context = texture._workingCanvas.getContext("2d");
  14208. if (!context) {
  14209. throw new Error("Unable to get 2d context");
  14210. }
  14211. texture._workingContext = context;
  14212. texture._workingCanvas.width = texture.width;
  14213. texture._workingCanvas.height = texture.height;
  14214. }
  14215. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14216. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14217. }
  14218. else {
  14219. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14220. }
  14221. if (texture.generateMipMaps) {
  14222. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14223. }
  14224. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14225. // this.resetTextureCache();
  14226. texture.isReady = true;
  14227. }
  14228. catch (ex) {
  14229. // Something unexpected
  14230. // Let's disable the texture
  14231. texture._isDisabled = true;
  14232. }
  14233. };
  14234. /**
  14235. * Updates a depth texture Comparison Mode and Function.
  14236. * If the comparison Function is equal to 0, the mode will be set to none.
  14237. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14238. * @param texture The texture to set the comparison function for
  14239. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14240. */
  14241. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14242. if (this.webGLVersion === 1) {
  14243. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14244. return;
  14245. }
  14246. var gl = this._gl;
  14247. if (texture.isCube) {
  14248. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14249. if (comparisonFunction === 0) {
  14250. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14251. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14252. }
  14253. else {
  14254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14256. }
  14257. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14258. }
  14259. else {
  14260. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14261. if (comparisonFunction === 0) {
  14262. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14263. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14264. }
  14265. else {
  14266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14268. }
  14269. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14270. }
  14271. texture._comparisonFunction = comparisonFunction;
  14272. };
  14273. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14274. var width = size.width || size;
  14275. var height = size.height || size;
  14276. internalTexture.baseWidth = width;
  14277. internalTexture.baseHeight = height;
  14278. internalTexture.width = width;
  14279. internalTexture.height = height;
  14280. internalTexture.isReady = true;
  14281. internalTexture.samples = 1;
  14282. internalTexture.generateMipMaps = false;
  14283. internalTexture._generateDepthBuffer = true;
  14284. internalTexture._generateStencilBuffer = generateStencil;
  14285. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14286. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14287. internalTexture._comparisonFunction = comparisonFunction;
  14288. var gl = this._gl;
  14289. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14290. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14291. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14292. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14293. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14294. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14295. if (comparisonFunction === 0) {
  14296. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14297. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14298. }
  14299. else {
  14300. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14301. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14302. }
  14303. };
  14304. /**
  14305. * Creates a depth stencil texture.
  14306. * This is only available in WebGL 2 or with the depth texture extension available.
  14307. * @param size The size of face edge in the texture.
  14308. * @param options The options defining the texture.
  14309. * @returns The texture
  14310. */
  14311. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14312. if (options.isCube) {
  14313. var width = size.width || size;
  14314. return this._createDepthStencilCubeTexture(width, options);
  14315. }
  14316. else {
  14317. return this._createDepthStencilTexture(size, options);
  14318. }
  14319. };
  14320. /**
  14321. * Creates a depth stencil texture.
  14322. * This is only available in WebGL 2 or with the depth texture extension available.
  14323. * @param size The size of face edge in the texture.
  14324. * @param options The options defining the texture.
  14325. * @returns The texture
  14326. */
  14327. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14328. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14329. if (!this._caps.depthTextureExtension) {
  14330. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14331. return internalTexture;
  14332. }
  14333. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14334. var gl = this._gl;
  14335. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14336. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14337. if (this.webGLVersion > 1) {
  14338. if (internalOptions.generateStencil) {
  14339. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14340. }
  14341. else {
  14342. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14343. }
  14344. }
  14345. else {
  14346. if (internalOptions.generateStencil) {
  14347. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14348. }
  14349. else {
  14350. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14351. }
  14352. }
  14353. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14354. return internalTexture;
  14355. };
  14356. /**
  14357. * Creates a depth stencil cube texture.
  14358. * This is only available in WebGL 2.
  14359. * @param size The size of face edge in the cube texture.
  14360. * @param options The options defining the cube texture.
  14361. * @returns The cube texture
  14362. */
  14363. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14364. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14365. internalTexture.isCube = true;
  14366. if (this.webGLVersion === 1) {
  14367. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14368. return internalTexture;
  14369. }
  14370. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14371. var gl = this._gl;
  14372. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14373. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14374. // Create the depth/stencil buffer
  14375. for (var face = 0; face < 6; face++) {
  14376. if (internalOptions.generateStencil) {
  14377. 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);
  14378. }
  14379. else {
  14380. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14381. }
  14382. }
  14383. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14384. return internalTexture;
  14385. };
  14386. /**
  14387. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14388. * @param renderTarget The render target to set the frame buffer for
  14389. */
  14390. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14391. // Create the framebuffer
  14392. var internalTexture = renderTarget.getInternalTexture();
  14393. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14394. return;
  14395. }
  14396. var gl = this._gl;
  14397. var depthStencilTexture = renderTarget.depthStencilTexture;
  14398. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14399. if (depthStencilTexture.isCube) {
  14400. if (depthStencilTexture._generateStencilBuffer) {
  14401. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14402. }
  14403. else {
  14404. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14405. }
  14406. }
  14407. else {
  14408. if (depthStencilTexture._generateStencilBuffer) {
  14409. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14410. }
  14411. else {
  14412. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14413. }
  14414. }
  14415. this.bindUnboundFramebuffer(null);
  14416. };
  14417. /**
  14418. * Creates a new render target texture
  14419. * @param size defines the size of the texture
  14420. * @param options defines the options used to create the texture
  14421. * @returns a new render target texture stored in an InternalTexture
  14422. */
  14423. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14424. var fullOptions = new RenderTargetCreationOptions();
  14425. if (options !== undefined && typeof options === "object") {
  14426. fullOptions.generateMipMaps = options.generateMipMaps;
  14427. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14428. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14429. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14430. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14431. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14432. }
  14433. else {
  14434. fullOptions.generateMipMaps = options;
  14435. fullOptions.generateDepthBuffer = true;
  14436. fullOptions.generateStencilBuffer = false;
  14437. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14438. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14439. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14440. }
  14441. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14442. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14443. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14444. }
  14445. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14446. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14447. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14448. }
  14449. var gl = this._gl;
  14450. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14451. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14452. var width = size.width || size;
  14453. var height = size.height || size;
  14454. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14455. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14456. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14457. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14458. }
  14459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14461. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14462. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14463. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14464. // Create the framebuffer
  14465. var framebuffer = gl.createFramebuffer();
  14466. this.bindUnboundFramebuffer(framebuffer);
  14467. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14468. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14469. if (fullOptions.generateMipMaps) {
  14470. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14471. }
  14472. // Unbind
  14473. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14474. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14475. this.bindUnboundFramebuffer(null);
  14476. texture._framebuffer = framebuffer;
  14477. texture.baseWidth = width;
  14478. texture.baseHeight = height;
  14479. texture.width = width;
  14480. texture.height = height;
  14481. texture.isReady = true;
  14482. texture.samples = 1;
  14483. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14484. texture.samplingMode = fullOptions.samplingMode;
  14485. texture.type = fullOptions.type;
  14486. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14487. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14488. // this.resetTextureCache();
  14489. this._internalTexturesCache.push(texture);
  14490. return texture;
  14491. };
  14492. /**
  14493. * Create a multi render target texture
  14494. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14495. * @param size defines the size of the texture
  14496. * @param options defines the creation options
  14497. * @returns the cube texture as an InternalTexture
  14498. */
  14499. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14500. var generateMipMaps = false;
  14501. var generateDepthBuffer = true;
  14502. var generateStencilBuffer = false;
  14503. var generateDepthTexture = false;
  14504. var textureCount = 1;
  14505. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14506. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14507. var types = new Array();
  14508. var samplingModes = new Array();
  14509. if (options !== undefined) {
  14510. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14511. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14512. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14513. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14514. textureCount = options.textureCount || 1;
  14515. if (options.types) {
  14516. types = options.types;
  14517. }
  14518. if (options.samplingModes) {
  14519. samplingModes = options.samplingModes;
  14520. }
  14521. }
  14522. var gl = this._gl;
  14523. // Create the framebuffer
  14524. var framebuffer = gl.createFramebuffer();
  14525. this.bindUnboundFramebuffer(framebuffer);
  14526. var width = size.width || size;
  14527. var height = size.height || size;
  14528. var textures = [];
  14529. var attachments = [];
  14530. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14531. for (var i = 0; i < textureCount; i++) {
  14532. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14533. var type = types[i] || defaultType;
  14534. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14535. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14536. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14537. }
  14538. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14539. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14540. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14541. }
  14542. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14543. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14544. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14545. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14546. }
  14547. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14548. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14549. textures.push(texture);
  14550. attachments.push(attachment);
  14551. gl.activeTexture(gl["TEXTURE" + i]);
  14552. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14553. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14554. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14555. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14556. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14557. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14558. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14559. if (generateMipMaps) {
  14560. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14561. }
  14562. // Unbind
  14563. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14564. texture._framebuffer = framebuffer;
  14565. texture._depthStencilBuffer = depthStencilBuffer;
  14566. texture.baseWidth = width;
  14567. texture.baseHeight = height;
  14568. texture.width = width;
  14569. texture.height = height;
  14570. texture.isReady = true;
  14571. texture.samples = 1;
  14572. texture.generateMipMaps = generateMipMaps;
  14573. texture.samplingMode = samplingMode;
  14574. texture.type = type;
  14575. texture._generateDepthBuffer = generateDepthBuffer;
  14576. texture._generateStencilBuffer = generateStencilBuffer;
  14577. texture._attachments = attachments;
  14578. this._internalTexturesCache.push(texture);
  14579. }
  14580. if (generateDepthTexture && this._caps.depthTextureExtension) {
  14581. // Depth texture
  14582. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14583. gl.activeTexture(gl.TEXTURE0);
  14584. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  14585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14586. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14587. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14588. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14589. 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);
  14590. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  14591. depthTexture._framebuffer = framebuffer;
  14592. depthTexture.baseWidth = width;
  14593. depthTexture.baseHeight = height;
  14594. depthTexture.width = width;
  14595. depthTexture.height = height;
  14596. depthTexture.isReady = true;
  14597. depthTexture.samples = 1;
  14598. depthTexture.generateMipMaps = generateMipMaps;
  14599. depthTexture.samplingMode = gl.NEAREST;
  14600. depthTexture._generateDepthBuffer = generateDepthBuffer;
  14601. depthTexture._generateStencilBuffer = generateStencilBuffer;
  14602. textures.push(depthTexture);
  14603. this._internalTexturesCache.push(depthTexture);
  14604. }
  14605. gl.drawBuffers(attachments);
  14606. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14607. this.bindUnboundFramebuffer(null);
  14608. this.resetTextureCache();
  14609. return textures;
  14610. };
  14611. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  14612. if (samples === void 0) { samples = 1; }
  14613. var depthStencilBuffer = null;
  14614. var gl = this._gl;
  14615. // Create the depth/stencil buffer
  14616. if (generateStencilBuffer) {
  14617. depthStencilBuffer = gl.createRenderbuffer();
  14618. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14619. if (samples > 1) {
  14620. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  14621. }
  14622. else {
  14623. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  14624. }
  14625. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14626. }
  14627. else if (generateDepthBuffer) {
  14628. depthStencilBuffer = gl.createRenderbuffer();
  14629. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14630. if (samples > 1) {
  14631. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  14632. }
  14633. else {
  14634. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  14635. }
  14636. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14637. }
  14638. return depthStencilBuffer;
  14639. };
  14640. /**
  14641. * Updates the sample count of a render target texture
  14642. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14643. * @param texture defines the texture to update
  14644. * @param samples defines the sample count to set
  14645. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14646. */
  14647. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  14648. if (this.webGLVersion < 2 || !texture) {
  14649. return 1;
  14650. }
  14651. if (texture.samples === samples) {
  14652. return samples;
  14653. }
  14654. var gl = this._gl;
  14655. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14656. // Dispose previous render buffers
  14657. if (texture._depthStencilBuffer) {
  14658. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14659. texture._depthStencilBuffer = null;
  14660. }
  14661. if (texture._MSAAFramebuffer) {
  14662. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14663. texture._MSAAFramebuffer = null;
  14664. }
  14665. if (texture._MSAARenderBuffer) {
  14666. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14667. texture._MSAARenderBuffer = null;
  14668. }
  14669. if (samples > 1) {
  14670. var framebuffer = gl.createFramebuffer();
  14671. if (!framebuffer) {
  14672. throw new Error("Unable to create multi sampled framebuffer");
  14673. }
  14674. texture._MSAAFramebuffer = framebuffer;
  14675. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  14676. var colorRenderbuffer = gl.createRenderbuffer();
  14677. if (!colorRenderbuffer) {
  14678. throw new Error("Unable to create multi sampled framebuffer");
  14679. }
  14680. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14681. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14682. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  14683. texture._MSAARenderBuffer = colorRenderbuffer;
  14684. }
  14685. else {
  14686. this.bindUnboundFramebuffer(texture._framebuffer);
  14687. }
  14688. texture.samples = samples;
  14689. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  14690. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14691. this.bindUnboundFramebuffer(null);
  14692. return samples;
  14693. };
  14694. /**
  14695. * Update the sample count for a given multiple render target texture
  14696. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14697. * @param textures defines the textures to update
  14698. * @param samples defines the sample count to set
  14699. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14700. */
  14701. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  14702. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  14703. return 1;
  14704. }
  14705. if (textures[0].samples === samples) {
  14706. return samples;
  14707. }
  14708. var gl = this._gl;
  14709. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14710. // Dispose previous render buffers
  14711. if (textures[0]._depthStencilBuffer) {
  14712. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  14713. textures[0]._depthStencilBuffer = null;
  14714. }
  14715. if (textures[0]._MSAAFramebuffer) {
  14716. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  14717. textures[0]._MSAAFramebuffer = null;
  14718. }
  14719. for (var i = 0; i < textures.length; i++) {
  14720. if (textures[i]._MSAARenderBuffer) {
  14721. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  14722. textures[i]._MSAARenderBuffer = null;
  14723. }
  14724. }
  14725. if (samples > 1) {
  14726. var framebuffer = gl.createFramebuffer();
  14727. if (!framebuffer) {
  14728. throw new Error("Unable to create multi sampled framebuffer");
  14729. }
  14730. this.bindUnboundFramebuffer(framebuffer);
  14731. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  14732. var attachments = [];
  14733. for (var i = 0; i < textures.length; i++) {
  14734. var texture = textures[i];
  14735. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14736. var colorRenderbuffer = gl.createRenderbuffer();
  14737. if (!colorRenderbuffer) {
  14738. throw new Error("Unable to create multi sampled framebuffer");
  14739. }
  14740. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14741. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14742. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  14743. texture._MSAAFramebuffer = framebuffer;
  14744. texture._MSAARenderBuffer = colorRenderbuffer;
  14745. texture.samples = samples;
  14746. texture._depthStencilBuffer = depthStencilBuffer;
  14747. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14748. attachments.push(attachment);
  14749. }
  14750. gl.drawBuffers(attachments);
  14751. }
  14752. else {
  14753. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14754. }
  14755. this.bindUnboundFramebuffer(null);
  14756. return samples;
  14757. };
  14758. /** @ignore */
  14759. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14760. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14761. };
  14762. /** @ignore */
  14763. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14764. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14765. };
  14766. /**
  14767. * Creates a new render target cube texture
  14768. * @param size defines the size of the texture
  14769. * @param options defines the options used to create the texture
  14770. * @returns a new render target cube texture stored in an InternalTexture
  14771. */
  14772. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14773. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14774. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14775. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14776. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14777. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14778. }
  14779. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14780. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14781. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14782. }
  14783. var gl = this._gl;
  14784. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14785. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14786. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14787. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14788. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14789. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14790. }
  14791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14795. for (var face = 0; face < 6; face++) {
  14796. 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);
  14797. }
  14798. // Create the framebuffer
  14799. var framebuffer = gl.createFramebuffer();
  14800. this.bindUnboundFramebuffer(framebuffer);
  14801. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14802. // MipMaps
  14803. if (fullOptions.generateMipMaps) {
  14804. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14805. }
  14806. // Unbind
  14807. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14808. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14809. this.bindUnboundFramebuffer(null);
  14810. texture._framebuffer = framebuffer;
  14811. texture.width = size;
  14812. texture.height = size;
  14813. texture.isReady = true;
  14814. texture.isCube = true;
  14815. texture.samples = 1;
  14816. texture.generateMipMaps = fullOptions.generateMipMaps;
  14817. texture.samplingMode = fullOptions.samplingMode;
  14818. texture.type = fullOptions.type;
  14819. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14820. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14821. this._internalTexturesCache.push(texture);
  14822. return texture;
  14823. };
  14824. /**
  14825. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  14826. * @param rootUrl defines the url where the file to load is located
  14827. * @param scene defines the current scene
  14828. * @param scale defines scale to apply to the mip map selection
  14829. * @param offset defines offset to apply to the mip map selection
  14830. * @param onLoad defines an optional callback raised when the texture is loaded
  14831. * @param onError defines an optional callback raised if there is an issue to load the texture
  14832. * @param format defines the format of the data
  14833. * @param forcedExtension defines the extension to use to pick the right loader
  14834. * @returns the cube texture as an InternalTexture
  14835. */
  14836. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14837. var _this = this;
  14838. if (onLoad === void 0) { onLoad = null; }
  14839. if (onError === void 0) { onError = null; }
  14840. if (forcedExtension === void 0) { forcedExtension = null; }
  14841. var callback = function (loadData) {
  14842. if (!loadData) {
  14843. if (onLoad) {
  14844. onLoad(null);
  14845. }
  14846. return;
  14847. }
  14848. var texture = loadData.texture;
  14849. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14850. texture._lodGenerationScale = scale;
  14851. texture._lodGenerationOffset = offset;
  14852. if (_this._caps.textureLOD) {
  14853. // Do not add extra process if texture lod is supported.
  14854. if (onLoad) {
  14855. onLoad(texture);
  14856. }
  14857. return;
  14858. }
  14859. var mipSlices = 3;
  14860. var gl = _this._gl;
  14861. var width = loadData.width;
  14862. if (!width) {
  14863. return;
  14864. }
  14865. var textures = [];
  14866. for (var i = 0; i < mipSlices; i++) {
  14867. //compute LOD from even spacing in smoothness (matching shader calculation)
  14868. var smoothness = i / (mipSlices - 1);
  14869. var roughness = 1 - smoothness;
  14870. var minLODIndex = offset; // roughness = 0
  14871. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14872. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14873. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14874. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14875. glTextureFromLod.isCube = true;
  14876. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14881. if (loadData.isDDS) {
  14882. var info = loadData.info;
  14883. var data = loadData.data;
  14884. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14885. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14886. }
  14887. else {
  14888. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14889. }
  14890. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14891. // Wrap in a base texture for easy binding.
  14892. var lodTexture = new BABYLON.BaseTexture(scene);
  14893. lodTexture.isCube = true;
  14894. lodTexture._texture = glTextureFromLod;
  14895. glTextureFromLod.isReady = true;
  14896. textures.push(lodTexture);
  14897. }
  14898. texture._lodTextureHigh = textures[2];
  14899. texture._lodTextureMid = textures[1];
  14900. texture._lodTextureLow = textures[0];
  14901. if (onLoad) {
  14902. onLoad(texture);
  14903. }
  14904. };
  14905. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14906. };
  14907. /**
  14908. * Creates a cube texture
  14909. * @param rootUrl defines the url where the files to load is located
  14910. * @param scene defines the current scene
  14911. * @param files defines the list of files to load (1 per face)
  14912. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  14913. * @param onLoad defines an optional callback raised when the texture is loaded
  14914. * @param onError defines an optional callback raised if there is an issue to load the texture
  14915. * @param format defines the format of the data
  14916. * @param forcedExtension defines the extension to use to pick the right loader
  14917. * @returns the cube texture as an InternalTexture
  14918. */
  14919. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14920. var _this = this;
  14921. if (onLoad === void 0) { onLoad = null; }
  14922. if (onError === void 0) { onError = null; }
  14923. if (forcedExtension === void 0) { forcedExtension = null; }
  14924. var gl = this._gl;
  14925. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14926. texture.isCube = true;
  14927. texture.url = rootUrl;
  14928. texture.generateMipMaps = !noMipmap;
  14929. if (!this._doNotHandleContextLost) {
  14930. texture._extension = forcedExtension;
  14931. texture._files = files;
  14932. }
  14933. var isKTX = false;
  14934. var isDDS = false;
  14935. var lastDot = rootUrl.lastIndexOf('.');
  14936. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14937. if (this._textureFormatInUse) {
  14938. extension = this._textureFormatInUse;
  14939. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14940. isKTX = true;
  14941. }
  14942. else {
  14943. isDDS = (extension === ".dds");
  14944. }
  14945. var onerror = function (request, exception) {
  14946. if (onError && request) {
  14947. onError(request.status + " " + request.statusText, exception);
  14948. }
  14949. };
  14950. if (isKTX) {
  14951. this._loadFile(rootUrl, function (data) {
  14952. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14953. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14954. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14955. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14956. ktx.uploadLevels(_this._gl, !noMipmap);
  14957. _this.setCubeMapTextureParams(gl, loadMipmap);
  14958. texture.width = ktx.pixelWidth;
  14959. texture.height = ktx.pixelHeight;
  14960. texture.isReady = true;
  14961. }, undefined, undefined, true, onerror);
  14962. }
  14963. else if (isDDS) {
  14964. if (files && files.length === 6) {
  14965. this._cascadeLoadFiles(scene, function (imgs) {
  14966. var info;
  14967. var loadMipmap = false;
  14968. var width = 0;
  14969. for (var index = 0; index < imgs.length; index++) {
  14970. var data = imgs[index];
  14971. info = BABYLON.DDSTools.GetDDSInfo(data);
  14972. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14973. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14974. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14975. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14976. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14977. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14978. }
  14979. texture.width = info.width;
  14980. texture.height = info.height;
  14981. texture.type = info.textureType;
  14982. width = info.width;
  14983. }
  14984. _this.setCubeMapTextureParams(gl, loadMipmap);
  14985. texture.isReady = true;
  14986. if (onLoad) {
  14987. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14988. }
  14989. }, files, onError);
  14990. }
  14991. else {
  14992. this._loadFile(rootUrl, function (data) {
  14993. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14994. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14995. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14996. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14997. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14998. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14999. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15000. }
  15001. _this.setCubeMapTextureParams(gl, loadMipmap);
  15002. texture.width = info.width;
  15003. texture.height = info.height;
  15004. texture.isReady = true;
  15005. texture.type = info.textureType;
  15006. if (onLoad) {
  15007. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15008. }
  15009. }, undefined, undefined, true, onerror);
  15010. }
  15011. }
  15012. else {
  15013. if (!files) {
  15014. throw new Error("Cannot load cubemap because files were not defined");
  15015. }
  15016. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15017. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15018. var height = width;
  15019. _this._prepareWorkingCanvas();
  15020. if (!_this._workingCanvas || !_this._workingContext) {
  15021. return;
  15022. }
  15023. _this._workingCanvas.width = width;
  15024. _this._workingCanvas.height = height;
  15025. var faces = [
  15026. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15027. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15028. ];
  15029. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15030. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15031. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15032. for (var index = 0; index < faces.length; index++) {
  15033. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15034. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15035. }
  15036. if (!noMipmap) {
  15037. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15038. }
  15039. _this.setCubeMapTextureParams(gl, !noMipmap);
  15040. texture.width = width;
  15041. texture.height = height;
  15042. texture.isReady = true;
  15043. if (format) {
  15044. texture.format = format;
  15045. }
  15046. texture.onLoadedObservable.notifyObservers(texture);
  15047. texture.onLoadedObservable.clear();
  15048. if (onLoad) {
  15049. onLoad();
  15050. }
  15051. }, files, onError);
  15052. }
  15053. this._internalTexturesCache.push(texture);
  15054. return texture;
  15055. };
  15056. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15061. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15062. // this.resetTextureCache();
  15063. };
  15064. /**
  15065. * Update a raw cube texture
  15066. * @param texture defines the texture to udpdate
  15067. * @param data defines the data to store
  15068. * @param format defines the data format
  15069. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15070. * @param invertY defines if data must be stored with Y axis inverted
  15071. * @param compression defines the compression used (null by default)
  15072. * @param level defines which level of the texture to update
  15073. */
  15074. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15075. if (compression === void 0) { compression = null; }
  15076. if (level === void 0) { level = 0; }
  15077. texture._bufferViewArray = data;
  15078. texture.format = format;
  15079. texture.type = type;
  15080. texture.invertY = invertY;
  15081. texture._compression = compression;
  15082. var gl = this._gl;
  15083. var textureType = this._getWebGLTextureType(type);
  15084. var internalFormat = this._getInternalFormat(format);
  15085. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15086. var needConversion = false;
  15087. if (internalFormat === gl.RGB) {
  15088. internalFormat = gl.RGBA;
  15089. needConversion = true;
  15090. }
  15091. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15092. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15093. if (texture.width % 4 !== 0) {
  15094. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15095. }
  15096. // Data are known to be in +X +Y +Z -X -Y -Z
  15097. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15098. var faceData = data[faceIndex];
  15099. if (compression) {
  15100. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15101. }
  15102. else {
  15103. if (needConversion) {
  15104. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15105. }
  15106. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15107. }
  15108. }
  15109. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15110. if (isPot && texture.generateMipMaps && level === 0) {
  15111. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15112. }
  15113. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15114. // this.resetTextureCache();
  15115. texture.isReady = true;
  15116. };
  15117. /**
  15118. * Creates a new raw cube texture
  15119. * @param data defines the array of data to use to create each face
  15120. * @param size defines the size of the textures
  15121. * @param format defines the format of the data
  15122. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15123. * @param generateMipMaps defines if the engine should generate the mip levels
  15124. * @param invertY defines if data must be stored with Y axis inverted
  15125. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15126. * @param compression defines the compression used (null by default)
  15127. * @returns the cube texture as an InternalTexture
  15128. */
  15129. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15130. if (compression === void 0) { compression = null; }
  15131. var gl = this._gl;
  15132. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15133. texture.isCube = true;
  15134. texture.generateMipMaps = generateMipMaps;
  15135. texture.format = format;
  15136. texture.type = type;
  15137. if (!this._doNotHandleContextLost) {
  15138. texture._bufferViewArray = data;
  15139. }
  15140. var textureType = this._getWebGLTextureType(type);
  15141. var internalFormat = this._getInternalFormat(format);
  15142. if (internalFormat === gl.RGB) {
  15143. internalFormat = gl.RGBA;
  15144. }
  15145. var width = size;
  15146. var height = width;
  15147. texture.width = width;
  15148. texture.height = height;
  15149. // Double check on POT to generate Mips.
  15150. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15151. if (!isPot) {
  15152. generateMipMaps = false;
  15153. }
  15154. // Upload data if needed. The texture won't be ready until then.
  15155. if (data) {
  15156. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15157. }
  15158. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15159. // Filters
  15160. if (data && generateMipMaps) {
  15161. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15162. }
  15163. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15164. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15166. }
  15167. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15170. }
  15171. else {
  15172. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15173. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15174. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15175. }
  15176. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15177. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15178. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15179. return texture;
  15180. };
  15181. /**
  15182. * Creates a new raw cube texture from a specified url
  15183. * @param url defines the url where the data is located
  15184. * @param scene defines the current scene
  15185. * @param size defines the size of the textures
  15186. * @param format defines the format of the data
  15187. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15188. * @param noMipmap defines if the engine should avoid generating the mip levels
  15189. * @param callback defines a callback used to extract texture data from loaded data
  15190. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15191. * @param onLoad defines a callback called when texture is loaded
  15192. * @param onError defines a callback called if there is an error
  15193. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15194. * @param invertY defines if data must be stored with Y axis inverted
  15195. * @returns the cube texture as an InternalTexture
  15196. */
  15197. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15198. var _this = this;
  15199. if (onLoad === void 0) { onLoad = null; }
  15200. if (onError === void 0) { onError = null; }
  15201. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15202. if (invertY === void 0) { invertY = false; }
  15203. var gl = this._gl;
  15204. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15205. scene._addPendingData(texture);
  15206. texture.url = url;
  15207. this._internalTexturesCache.push(texture);
  15208. var onerror = function (request, exception) {
  15209. scene._removePendingData(texture);
  15210. if (onError && request) {
  15211. onError(request.status + " " + request.statusText, exception);
  15212. }
  15213. };
  15214. var internalCallback = function (data) {
  15215. var width = texture.width;
  15216. var faceDataArrays = callback(data);
  15217. if (!faceDataArrays) {
  15218. return;
  15219. }
  15220. if (mipmapGenerator) {
  15221. var textureType = _this._getWebGLTextureType(type);
  15222. var internalFormat = _this._getInternalFormat(format);
  15223. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15224. var needConversion = false;
  15225. if (internalFormat === gl.RGB) {
  15226. internalFormat = gl.RGBA;
  15227. needConversion = true;
  15228. }
  15229. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15230. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15231. var mipData = mipmapGenerator(faceDataArrays);
  15232. for (var level = 0; level < mipData.length; level++) {
  15233. var mipSize = width >> level;
  15234. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15235. var mipFaceData = mipData[level][faceIndex];
  15236. if (needConversion) {
  15237. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15238. }
  15239. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15240. }
  15241. }
  15242. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15243. }
  15244. else {
  15245. texture.generateMipMaps = !noMipmap;
  15246. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15247. }
  15248. texture.isReady = true;
  15249. // this.resetTextureCache();
  15250. scene._removePendingData(texture);
  15251. if (onLoad) {
  15252. onLoad();
  15253. }
  15254. };
  15255. this._loadFile(url, function (data) {
  15256. internalCallback(data);
  15257. }, undefined, scene.database, true, onerror);
  15258. return texture;
  15259. };
  15260. ;
  15261. /**
  15262. * Update a raw 3D texture
  15263. * @param texture defines the texture to update
  15264. * @param data defines the data to store
  15265. * @param format defines the data format
  15266. * @param invertY defines if data must be stored with Y axis inverted
  15267. * @param compression defines the used compression (can be null)
  15268. */
  15269. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15270. if (compression === void 0) { compression = null; }
  15271. var internalFormat = this._getInternalFormat(format);
  15272. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15273. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15274. if (!this._doNotHandleContextLost) {
  15275. texture._bufferView = data;
  15276. texture.format = format;
  15277. texture.invertY = invertY;
  15278. texture._compression = compression;
  15279. }
  15280. if (texture.width % 4 !== 0) {
  15281. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15282. }
  15283. if (compression && data) {
  15284. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15285. }
  15286. else {
  15287. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15288. }
  15289. if (texture.generateMipMaps) {
  15290. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15291. }
  15292. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15293. // this.resetTextureCache();
  15294. texture.isReady = true;
  15295. };
  15296. /**
  15297. * Creates a new raw 3D texture
  15298. * @param data defines the data used to create the texture
  15299. * @param width defines the width of the texture
  15300. * @param height defines the height of the texture
  15301. * @param depth defines the depth of the texture
  15302. * @param format defines the format of the texture
  15303. * @param generateMipMaps defines if the engine must generate mip levels
  15304. * @param invertY defines if data must be stored with Y axis inverted
  15305. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15306. * @param compression defines the compressed used (can be null)
  15307. * @returns a new raw 3D texture (stored in an InternalTexture)
  15308. */
  15309. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15310. if (compression === void 0) { compression = null; }
  15311. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15312. texture.baseWidth = width;
  15313. texture.baseHeight = height;
  15314. texture.baseDepth = depth;
  15315. texture.width = width;
  15316. texture.height = height;
  15317. texture.depth = depth;
  15318. texture.format = format;
  15319. texture.generateMipMaps = generateMipMaps;
  15320. texture.samplingMode = samplingMode;
  15321. texture.is3D = true;
  15322. if (!this._doNotHandleContextLost) {
  15323. texture._bufferView = data;
  15324. }
  15325. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15326. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15327. // Filters
  15328. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15329. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15330. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15331. if (generateMipMaps) {
  15332. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15333. }
  15334. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15335. this._internalTexturesCache.push(texture);
  15336. return texture;
  15337. };
  15338. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15339. var gl = this._gl;
  15340. if (!gl) {
  15341. return;
  15342. }
  15343. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15344. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15346. if (!noMipmap && !isCompressed) {
  15347. gl.generateMipmap(gl.TEXTURE_2D);
  15348. }
  15349. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15350. // this.resetTextureCache();
  15351. if (scene) {
  15352. scene._removePendingData(texture);
  15353. }
  15354. texture.onLoadedObservable.notifyObservers(texture);
  15355. texture.onLoadedObservable.clear();
  15356. };
  15357. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15358. var _this = this;
  15359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15360. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15361. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15362. var gl = this._gl;
  15363. if (!gl) {
  15364. return;
  15365. }
  15366. if (!texture._webGLTexture) {
  15367. // this.resetTextureCache();
  15368. if (scene) {
  15369. scene._removePendingData(texture);
  15370. }
  15371. return;
  15372. }
  15373. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15374. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15375. texture.baseWidth = width;
  15376. texture.baseHeight = height;
  15377. texture.width = potWidth;
  15378. texture.height = potHeight;
  15379. texture.isReady = true;
  15380. if (processFunction(potWidth, potHeight, function () {
  15381. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15382. })) {
  15383. // Returning as texture needs extra async steps
  15384. return;
  15385. }
  15386. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15387. };
  15388. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15389. // Create new RGBA data container.
  15390. var rgbaData;
  15391. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15392. rgbaData = new Float32Array(width * height * 4);
  15393. }
  15394. else {
  15395. rgbaData = new Uint32Array(width * height * 4);
  15396. }
  15397. // Convert each pixel.
  15398. for (var x = 0; x < width; x++) {
  15399. for (var y = 0; y < height; y++) {
  15400. var index = (y * width + x) * 3;
  15401. var newIndex = (y * width + x) * 4;
  15402. // Map Old Value to new value.
  15403. rgbaData[newIndex + 0] = rgbData[index + 0];
  15404. rgbaData[newIndex + 1] = rgbData[index + 1];
  15405. rgbaData[newIndex + 2] = rgbData[index + 2];
  15406. // Add fully opaque alpha channel.
  15407. rgbaData[newIndex + 3] = 1;
  15408. }
  15409. }
  15410. return rgbaData;
  15411. };
  15412. /** @ignore */
  15413. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15414. var gl = this._gl;
  15415. if (texture._framebuffer) {
  15416. gl.deleteFramebuffer(texture._framebuffer);
  15417. texture._framebuffer = null;
  15418. }
  15419. if (texture._depthStencilBuffer) {
  15420. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15421. texture._depthStencilBuffer = null;
  15422. }
  15423. if (texture._MSAAFramebuffer) {
  15424. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15425. texture._MSAAFramebuffer = null;
  15426. }
  15427. if (texture._MSAARenderBuffer) {
  15428. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15429. texture._MSAARenderBuffer = null;
  15430. }
  15431. };
  15432. /** @ignore */
  15433. Engine.prototype._releaseTexture = function (texture) {
  15434. var gl = this._gl;
  15435. this._releaseFramebufferObjects(texture);
  15436. gl.deleteTexture(texture._webGLTexture);
  15437. // Unbind channels
  15438. this.unbindAllTextures();
  15439. var index = this._internalTexturesCache.indexOf(texture);
  15440. if (index !== -1) {
  15441. this._internalTexturesCache.splice(index, 1);
  15442. }
  15443. // Integrated fixed lod samplers.
  15444. if (texture._lodTextureHigh) {
  15445. texture._lodTextureHigh.dispose();
  15446. }
  15447. if (texture._lodTextureMid) {
  15448. texture._lodTextureMid.dispose();
  15449. }
  15450. if (texture._lodTextureLow) {
  15451. texture._lodTextureLow.dispose();
  15452. }
  15453. // Set output texture of post process to null if the texture has been released/disposed
  15454. this.scenes.forEach(function (scene) {
  15455. scene.postProcesses.forEach(function (postProcess) {
  15456. if (postProcess._outputTexture == texture) {
  15457. postProcess._outputTexture = null;
  15458. }
  15459. });
  15460. scene.cameras.forEach(function (camera) {
  15461. camera._postProcesses.forEach(function (postProcess) {
  15462. if (postProcess) {
  15463. if (postProcess._outputTexture == texture) {
  15464. postProcess._outputTexture = null;
  15465. }
  15466. }
  15467. });
  15468. });
  15469. });
  15470. };
  15471. Engine.prototype.setProgram = function (program) {
  15472. if (this._currentProgram !== program) {
  15473. this._gl.useProgram(program);
  15474. this._currentProgram = program;
  15475. }
  15476. };
  15477. /**
  15478. * Binds an effect to the webGL context
  15479. * @param effect defines the effect to bind
  15480. */
  15481. Engine.prototype.bindSamplers = function (effect) {
  15482. this.setProgram(effect.getProgram());
  15483. var samplers = effect.getSamplers();
  15484. for (var index = 0; index < samplers.length; index++) {
  15485. var uniform = effect.getUniform(samplers[index]);
  15486. if (uniform) {
  15487. this._boundUniforms[index] = uniform;
  15488. }
  15489. }
  15490. this._currentEffect = null;
  15491. };
  15492. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15493. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15494. return;
  15495. }
  15496. // Remove
  15497. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15498. // Bind last to it
  15499. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15500. // Bind to dummy
  15501. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15502. };
  15503. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15504. if (!internalTexture) {
  15505. return -1;
  15506. }
  15507. internalTexture._initialSlot = channel;
  15508. if (this.disableTextureBindingOptimization) {
  15509. if (channel !== internalTexture._designatedSlot) {
  15510. this._textureCollisions.addCount(1, false);
  15511. }
  15512. }
  15513. else {
  15514. if (channel !== internalTexture._designatedSlot) {
  15515. if (internalTexture._designatedSlot > -1) {
  15516. return internalTexture._designatedSlot;
  15517. }
  15518. else {
  15519. // No slot for this texture, let's pick a new one (if we find a free slot)
  15520. if (this._nextFreeTextureSlots.length) {
  15521. return this._nextFreeTextureSlots[0];
  15522. }
  15523. // We need to recycle the oldest bound texture, sorry.
  15524. this._textureCollisions.addCount(1, false);
  15525. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15526. }
  15527. }
  15528. }
  15529. return channel;
  15530. };
  15531. Engine.prototype._linkTrackers = function (previous, next) {
  15532. previous.next = next;
  15533. next.previous = previous;
  15534. };
  15535. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15536. var currentSlot = internalTexture._designatedSlot;
  15537. if (currentSlot === -1) {
  15538. return -1;
  15539. }
  15540. internalTexture._designatedSlot = -1;
  15541. if (this.disableTextureBindingOptimization) {
  15542. return -1;
  15543. }
  15544. // Remove from bound list
  15545. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15546. // Free the slot
  15547. this._boundTexturesCache[currentSlot] = null;
  15548. this._nextFreeTextureSlots.push(currentSlot);
  15549. return currentSlot;
  15550. };
  15551. Engine.prototype._activateCurrentTexture = function () {
  15552. if (this._currentTextureChannel !== this._activeChannel) {
  15553. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15554. this._currentTextureChannel = this._activeChannel;
  15555. }
  15556. };
  15557. /** @ignore */
  15558. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  15559. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15560. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15561. this._activeChannel = texture._designatedSlot;
  15562. }
  15563. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15564. var isTextureForRendering = texture && texture._initialSlot > -1;
  15565. if (currentTextureBound !== texture) {
  15566. if (currentTextureBound) {
  15567. this._removeDesignatedSlot(currentTextureBound);
  15568. }
  15569. this._activateCurrentTexture();
  15570. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  15571. this._boundTexturesCache[this._activeChannel] = texture;
  15572. if (texture) {
  15573. if (!this.disableTextureBindingOptimization) {
  15574. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  15575. if (slotIndex > -1) {
  15576. this._nextFreeTextureSlots.splice(slotIndex, 1);
  15577. }
  15578. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  15579. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  15580. }
  15581. texture._designatedSlot = this._activeChannel;
  15582. }
  15583. }
  15584. else if (forTextureDataUpdate) {
  15585. this._activateCurrentTexture();
  15586. }
  15587. if (isTextureForRendering && !forTextureDataUpdate) {
  15588. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  15589. }
  15590. };
  15591. /** @ignore */
  15592. Engine.prototype._bindTexture = function (channel, texture) {
  15593. if (channel < 0) {
  15594. return;
  15595. }
  15596. if (texture) {
  15597. channel = this._getCorrectTextureChannel(channel, texture);
  15598. }
  15599. this._activeChannel = channel;
  15600. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  15601. };
  15602. /**
  15603. * Sets a texture to the webGL context from a postprocess
  15604. * @param channel defines the channel to use
  15605. * @param postProcess defines the source postprocess
  15606. */
  15607. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  15608. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  15609. };
  15610. /**
  15611. * Binds the output of the passed in post process to the texture channel specified
  15612. * @param channel The channel the texture should be bound to
  15613. * @param postProcess The post process which's output should be bound
  15614. */
  15615. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  15616. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  15617. };
  15618. /**
  15619. * Unbind all textures from the webGL context
  15620. */
  15621. Engine.prototype.unbindAllTextures = function () {
  15622. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  15623. this._activeChannel = channel;
  15624. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15625. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15626. if (this.webGLVersion > 1) {
  15627. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15628. }
  15629. }
  15630. };
  15631. /**
  15632. * Sets a texture to the according uniform.
  15633. * @param channel The texture channel
  15634. * @param uniform The uniform to set
  15635. * @param texture The texture to apply
  15636. */
  15637. Engine.prototype.setTexture = function (channel, uniform, texture) {
  15638. if (channel < 0) {
  15639. return;
  15640. }
  15641. if (uniform) {
  15642. this._boundUniforms[channel] = uniform;
  15643. }
  15644. this._setTexture(channel, texture);
  15645. };
  15646. /**
  15647. * Sets a depth stencil texture from a render target to the according uniform.
  15648. * @param channel The texture channel
  15649. * @param uniform The uniform to set
  15650. * @param texture The render target texture containing the depth stencil texture to apply
  15651. */
  15652. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  15653. if (channel < 0) {
  15654. return;
  15655. }
  15656. if (uniform) {
  15657. this._boundUniforms[channel] = uniform;
  15658. }
  15659. if (!texture || !texture.depthStencilTexture) {
  15660. this._setTexture(channel, null);
  15661. }
  15662. else {
  15663. this._setTexture(channel, texture, false, true);
  15664. }
  15665. };
  15666. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  15667. var uniform = this._boundUniforms[sourceSlot];
  15668. if (uniform._currentState === destination) {
  15669. return;
  15670. }
  15671. this._gl.uniform1i(uniform, destination);
  15672. uniform._currentState = destination;
  15673. };
  15674. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  15675. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  15676. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  15677. // Not ready?
  15678. if (!texture) {
  15679. if (this._boundTexturesCache[channel] != null) {
  15680. this._activeChannel = channel;
  15681. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15683. if (this.webGLVersion > 1) {
  15684. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15685. }
  15686. }
  15687. return false;
  15688. }
  15689. // Video
  15690. if (texture.video) {
  15691. this._activeChannel = channel;
  15692. texture.update();
  15693. }
  15694. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  15695. texture.delayLoad();
  15696. return false;
  15697. }
  15698. var internalTexture;
  15699. if (depthStencilTexture) {
  15700. internalTexture = texture.depthStencilTexture;
  15701. }
  15702. else if (texture.isReady()) {
  15703. internalTexture = texture.getInternalTexture();
  15704. }
  15705. else if (texture.isCube) {
  15706. internalTexture = this.emptyCubeTexture;
  15707. }
  15708. else if (texture.is3D) {
  15709. internalTexture = this.emptyTexture3D;
  15710. }
  15711. else {
  15712. internalTexture = this.emptyTexture;
  15713. }
  15714. if (!isPartOfTextureArray) {
  15715. channel = this._getCorrectTextureChannel(channel, internalTexture);
  15716. }
  15717. if (this._boundTexturesCache[channel] === internalTexture) {
  15718. this._moveBoundTextureOnTop(internalTexture);
  15719. if (!isPartOfTextureArray) {
  15720. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  15721. }
  15722. return false;
  15723. }
  15724. this._activeChannel = channel;
  15725. if (internalTexture && internalTexture.is3D) {
  15726. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  15727. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  15728. internalTexture._cachedWrapU = texture.wrapU;
  15729. switch (texture.wrapU) {
  15730. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15731. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  15732. break;
  15733. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15734. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  15735. break;
  15736. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15737. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  15738. break;
  15739. }
  15740. }
  15741. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  15742. internalTexture._cachedWrapV = texture.wrapV;
  15743. switch (texture.wrapV) {
  15744. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15745. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  15746. break;
  15747. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15748. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  15749. break;
  15750. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15751. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  15752. break;
  15753. }
  15754. }
  15755. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  15756. internalTexture._cachedWrapR = texture.wrapR;
  15757. switch (texture.wrapR) {
  15758. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15759. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  15760. break;
  15761. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15762. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  15763. break;
  15764. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15765. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  15766. break;
  15767. }
  15768. }
  15769. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  15770. }
  15771. else if (internalTexture && internalTexture.isCube) {
  15772. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  15773. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  15774. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  15775. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  15776. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  15777. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  15778. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  15779. }
  15780. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  15781. }
  15782. else {
  15783. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  15784. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  15785. internalTexture._cachedWrapU = texture.wrapU;
  15786. switch (texture.wrapU) {
  15787. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15788. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  15789. break;
  15790. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15791. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  15792. break;
  15793. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15794. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  15795. break;
  15796. }
  15797. }
  15798. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  15799. internalTexture._cachedWrapV = texture.wrapV;
  15800. switch (texture.wrapV) {
  15801. case BABYLON.Texture.WRAP_ADDRESSMODE:
  15802. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  15803. break;
  15804. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  15805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  15806. break;
  15807. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  15808. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  15809. break;
  15810. }
  15811. }
  15812. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  15813. }
  15814. return true;
  15815. };
  15816. /**
  15817. * Sets an array of texture to the webGL context
  15818. * @param channel defines the channel where the texture array must be set
  15819. * @param uniform defines the associated uniform location
  15820. * @param textures defines the array of textures to bind
  15821. */
  15822. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  15823. if (channel < 0 || !uniform) {
  15824. return;
  15825. }
  15826. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  15827. this._textureUnits = new Int32Array(textures.length);
  15828. }
  15829. for (var i = 0; i < textures.length; i++) {
  15830. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  15831. }
  15832. this._gl.uniform1iv(uniform, this._textureUnits);
  15833. for (var index = 0; index < textures.length; index++) {
  15834. this._setTexture(this._textureUnits[index], textures[index], true);
  15835. }
  15836. };
  15837. /** @ignore */
  15838. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  15839. var internalTexture = texture.getInternalTexture();
  15840. if (!internalTexture) {
  15841. return;
  15842. }
  15843. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  15844. var value = texture.anisotropicFilteringLevel;
  15845. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  15846. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  15847. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  15848. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  15849. }
  15850. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  15851. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  15852. internalTexture._cachedAnisotropicFilteringLevel = value;
  15853. }
  15854. };
  15855. /**
  15856. * Reads pixels from the current frame buffer. Please note that this function can be slow
  15857. * @param x defines the x coordinate of the rectangle where pixels must be read
  15858. * @param y defines the y coordinate of the rectangle where pixels must be read
  15859. * @param width defines the width of the rectangle where pixels must be read
  15860. * @param height defines the height of the rectangle where pixels must be read
  15861. * @returns a Uint8Array containing RGBA colors
  15862. */
  15863. Engine.prototype.readPixels = function (x, y, width, height) {
  15864. var data = new Uint8Array(height * width * 4);
  15865. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  15866. return data;
  15867. };
  15868. /**
  15869. * Add an externaly attached data from its key.
  15870. * This method call will fail and return false, if such key already exists.
  15871. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  15872. * @param key the unique key that identifies the data
  15873. * @param data the data object to associate to the key for this Engine instance
  15874. * @return true if no such key were already present and the data was added successfully, false otherwise
  15875. */
  15876. Engine.prototype.addExternalData = function (key, data) {
  15877. if (!this._externalData) {
  15878. this._externalData = new BABYLON.StringDictionary();
  15879. }
  15880. return this._externalData.add(key, data);
  15881. };
  15882. /**
  15883. * Get an externaly attached data from its key
  15884. * @param key the unique key that identifies the data
  15885. * @return the associated data, if present (can be null), or undefined if not present
  15886. */
  15887. Engine.prototype.getExternalData = function (key) {
  15888. if (!this._externalData) {
  15889. this._externalData = new BABYLON.StringDictionary();
  15890. }
  15891. return this._externalData.get(key);
  15892. };
  15893. /**
  15894. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15895. * @param key the unique key that identifies the data
  15896. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15897. * @return the associated data, can be null if the factory returned null.
  15898. */
  15899. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15900. if (!this._externalData) {
  15901. this._externalData = new BABYLON.StringDictionary();
  15902. }
  15903. return this._externalData.getOrAddWithFactory(key, factory);
  15904. };
  15905. /**
  15906. * Remove an externaly attached data from the Engine instance
  15907. * @param key the unique key that identifies the data
  15908. * @return true if the data was successfully removed, false if it doesn't exist
  15909. */
  15910. Engine.prototype.removeExternalData = function (key) {
  15911. if (!this._externalData) {
  15912. this._externalData = new BABYLON.StringDictionary();
  15913. }
  15914. return this._externalData.remove(key);
  15915. };
  15916. /**
  15917. * Unbind all vertex attributes from the webGL context
  15918. */
  15919. Engine.prototype.unbindAllAttributes = function () {
  15920. if (this._mustWipeVertexAttributes) {
  15921. this._mustWipeVertexAttributes = false;
  15922. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15923. this._gl.disableVertexAttribArray(i);
  15924. this._vertexAttribArraysEnabled[i] = false;
  15925. this._currentBufferPointers[i].active = false;
  15926. }
  15927. return;
  15928. }
  15929. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15930. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15931. continue;
  15932. }
  15933. this._gl.disableVertexAttribArray(i);
  15934. this._vertexAttribArraysEnabled[i] = false;
  15935. this._currentBufferPointers[i].active = false;
  15936. }
  15937. };
  15938. /**
  15939. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  15940. */
  15941. Engine.prototype.releaseEffects = function () {
  15942. for (var name in this._compiledEffects) {
  15943. this._deleteProgram(this._compiledEffects[name]._program);
  15944. }
  15945. this._compiledEffects = {};
  15946. };
  15947. /**
  15948. * Dispose and release all associated resources
  15949. */
  15950. Engine.prototype.dispose = function () {
  15951. this.hideLoadingUI();
  15952. this.stopRenderLoop();
  15953. // Release postProcesses
  15954. while (this.postProcesses.length) {
  15955. this.postProcesses[0].dispose();
  15956. }
  15957. // Empty texture
  15958. if (this._emptyTexture) {
  15959. this._releaseTexture(this._emptyTexture);
  15960. this._emptyTexture = null;
  15961. }
  15962. if (this._emptyCubeTexture) {
  15963. this._releaseTexture(this._emptyCubeTexture);
  15964. this._emptyCubeTexture = null;
  15965. }
  15966. // Rescale PP
  15967. if (this._rescalePostProcess) {
  15968. this._rescalePostProcess.dispose();
  15969. }
  15970. // Release scenes
  15971. while (this.scenes.length) {
  15972. this.scenes[0].dispose();
  15973. }
  15974. // Release audio engine
  15975. if (Engine.audioEngine) {
  15976. Engine.audioEngine.dispose();
  15977. }
  15978. // Release effects
  15979. this.releaseEffects();
  15980. // Unbind
  15981. this.unbindAllAttributes();
  15982. this._boundUniforms = [];
  15983. if (this._dummyFramebuffer) {
  15984. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15985. }
  15986. //WebVR
  15987. this.disableVR();
  15988. // Events
  15989. if (BABYLON.Tools.IsWindowObjectExist()) {
  15990. window.removeEventListener("blur", this._onBlur);
  15991. window.removeEventListener("focus", this._onFocus);
  15992. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15993. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15994. if (this._renderingCanvas) {
  15995. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15996. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15997. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15998. if (!this._doNotHandleContextLost) {
  15999. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16000. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16001. }
  16002. }
  16003. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16004. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16005. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16006. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16007. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16008. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16009. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16010. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16011. if (this._onVrDisplayConnect) {
  16012. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16013. if (this._onVrDisplayDisconnect) {
  16014. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16015. }
  16016. if (this._onVrDisplayPresentChange) {
  16017. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16018. }
  16019. this._onVrDisplayConnect = null;
  16020. this._onVrDisplayDisconnect = null;
  16021. }
  16022. }
  16023. // Remove from Instances
  16024. var index = Engine.Instances.indexOf(this);
  16025. if (index >= 0) {
  16026. Engine.Instances.splice(index, 1);
  16027. }
  16028. this._workingCanvas = null;
  16029. this._workingContext = null;
  16030. this._currentBufferPointers = [];
  16031. this._renderingCanvas = null;
  16032. this._currentProgram = null;
  16033. this._bindedRenderFunction = null;
  16034. this.onResizeObservable.clear();
  16035. this.onCanvasBlurObservable.clear();
  16036. this.onCanvasFocusObservable.clear();
  16037. this.onCanvasPointerOutObservable.clear();
  16038. this.onBeginFrameObservable.clear();
  16039. this.onEndFrameObservable.clear();
  16040. BABYLON.Effect.ResetCache();
  16041. // Abort active requests
  16042. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16043. var request = _a[_i];
  16044. request.abort();
  16045. }
  16046. };
  16047. // Loading screen
  16048. /**
  16049. * Display the loading screen
  16050. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16051. */
  16052. Engine.prototype.displayLoadingUI = function () {
  16053. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16054. return;
  16055. }
  16056. var loadingScreen = this.loadingScreen;
  16057. if (loadingScreen) {
  16058. loadingScreen.displayLoadingUI();
  16059. }
  16060. };
  16061. /**
  16062. * Hide the loading screen
  16063. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16064. */
  16065. Engine.prototype.hideLoadingUI = function () {
  16066. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16067. return;
  16068. }
  16069. var loadingScreen = this.loadingScreen;
  16070. if (loadingScreen) {
  16071. loadingScreen.hideLoadingUI();
  16072. }
  16073. };
  16074. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16075. /**
  16076. * Gets the current loading screen object
  16077. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16078. */
  16079. get: function () {
  16080. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16081. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16082. return this._loadingScreen;
  16083. },
  16084. /**
  16085. * Sets the current loading screen object
  16086. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16087. */
  16088. set: function (loadingScreen) {
  16089. this._loadingScreen = loadingScreen;
  16090. },
  16091. enumerable: true,
  16092. configurable: true
  16093. });
  16094. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16095. /**
  16096. * Sets the current loading screen text
  16097. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16098. */
  16099. set: function (text) {
  16100. this.loadingScreen.loadingUIText = text;
  16101. },
  16102. enumerable: true,
  16103. configurable: true
  16104. });
  16105. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16106. /**
  16107. * Sets the current loading screen background color
  16108. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16109. */
  16110. set: function (color) {
  16111. this.loadingScreen.loadingUIBackgroundColor = color;
  16112. },
  16113. enumerable: true,
  16114. configurable: true
  16115. });
  16116. /**
  16117. * Attach a new callback raised when context lost event is fired
  16118. * @param callback defines the callback to call
  16119. */
  16120. Engine.prototype.attachContextLostEvent = function (callback) {
  16121. if (this._renderingCanvas) {
  16122. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16123. }
  16124. };
  16125. /**
  16126. * Attach a new callback raised when context restored event is fired
  16127. * @param callback defines the callback to call
  16128. */
  16129. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16130. if (this._renderingCanvas) {
  16131. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16132. }
  16133. };
  16134. /**
  16135. * Gets the source code of the vertex shader associated with a specific webGL program
  16136. * @param program defines the program to use
  16137. * @returns a string containing the source code of the vertex shader associated with the program
  16138. */
  16139. Engine.prototype.getVertexShaderSource = function (program) {
  16140. var shaders = this._gl.getAttachedShaders(program);
  16141. if (!shaders) {
  16142. return null;
  16143. }
  16144. return this._gl.getShaderSource(shaders[0]);
  16145. };
  16146. /**
  16147. * Gets the source code of the fragment shader associated with a specific webGL program
  16148. * @param program defines the program to use
  16149. * @returns a string containing the source code of the fragment shader associated with the program
  16150. */
  16151. Engine.prototype.getFragmentShaderSource = function (program) {
  16152. var shaders = this._gl.getAttachedShaders(program);
  16153. if (!shaders) {
  16154. return null;
  16155. }
  16156. return this._gl.getShaderSource(shaders[1]);
  16157. };
  16158. /**
  16159. * Get the current error code of the webGL context
  16160. * @returns the error code
  16161. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16162. */
  16163. Engine.prototype.getError = function () {
  16164. return this._gl.getError();
  16165. };
  16166. // FPS
  16167. /**
  16168. * Gets the current framerate
  16169. * @returns a number representing the framerate
  16170. */
  16171. Engine.prototype.getFps = function () {
  16172. return this._fps;
  16173. };
  16174. /**
  16175. * Gets the time spent between current and previous frame
  16176. * @returns a number representing the delta time in ms
  16177. */
  16178. Engine.prototype.getDeltaTime = function () {
  16179. return this._deltaTime;
  16180. };
  16181. Engine.prototype._measureFps = function () {
  16182. this._performanceMonitor.sampleFrame();
  16183. this._fps = this._performanceMonitor.averageFPS;
  16184. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16185. };
  16186. /** @ignore */
  16187. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16188. if (faceIndex === void 0) { faceIndex = -1; }
  16189. var gl = this._gl;
  16190. if (!this._dummyFramebuffer) {
  16191. var dummy = gl.createFramebuffer();
  16192. if (!dummy) {
  16193. throw new Error("Unable to create dummy framebuffer");
  16194. }
  16195. this._dummyFramebuffer = dummy;
  16196. }
  16197. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16198. if (faceIndex > -1) {
  16199. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16200. }
  16201. else {
  16202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16203. }
  16204. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16205. var buffer;
  16206. switch (readType) {
  16207. case gl.UNSIGNED_BYTE:
  16208. buffer = new Uint8Array(4 * width * height);
  16209. readType = gl.UNSIGNED_BYTE;
  16210. break;
  16211. default:
  16212. buffer = new Float32Array(4 * width * height);
  16213. readType = gl.FLOAT;
  16214. break;
  16215. }
  16216. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16217. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16218. return buffer;
  16219. };
  16220. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16221. if (this._webGLVersion > 1) {
  16222. return this._caps.colorBufferFloat;
  16223. }
  16224. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16225. };
  16226. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16227. if (this._webGLVersion > 1) {
  16228. return this._caps.colorBufferFloat;
  16229. }
  16230. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16231. };
  16232. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16233. Engine.prototype._canRenderToFramebuffer = function (type) {
  16234. var gl = this._gl;
  16235. //clear existing errors
  16236. while (gl.getError() !== gl.NO_ERROR) { }
  16237. var successful = true;
  16238. var texture = gl.createTexture();
  16239. gl.bindTexture(gl.TEXTURE_2D, texture);
  16240. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16243. var fb = gl.createFramebuffer();
  16244. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16245. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16246. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16247. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16248. successful = successful && (gl.getError() === gl.NO_ERROR);
  16249. //try render by clearing frame buffer's color buffer
  16250. if (successful) {
  16251. gl.clear(gl.COLOR_BUFFER_BIT);
  16252. successful = successful && (gl.getError() === gl.NO_ERROR);
  16253. }
  16254. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16255. if (successful) {
  16256. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16257. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16258. var readFormat = gl.RGBA;
  16259. var readType = gl.UNSIGNED_BYTE;
  16260. var buffer = new Uint8Array(4);
  16261. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16262. successful = successful && (gl.getError() === gl.NO_ERROR);
  16263. }
  16264. //clean up
  16265. gl.deleteTexture(texture);
  16266. gl.deleteFramebuffer(fb);
  16267. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16268. //clear accumulated errors
  16269. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16270. return successful;
  16271. };
  16272. /** @ignore */
  16273. Engine.prototype._getWebGLTextureType = function (type) {
  16274. if (type === Engine.TEXTURETYPE_FLOAT) {
  16275. return this._gl.FLOAT;
  16276. }
  16277. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16278. // Add Half Float Constant.
  16279. return this._gl.HALF_FLOAT_OES;
  16280. }
  16281. return this._gl.UNSIGNED_BYTE;
  16282. };
  16283. ;
  16284. Engine.prototype._getInternalFormat = function (format) {
  16285. var internalFormat = this._gl.RGBA;
  16286. switch (format) {
  16287. case Engine.TEXTUREFORMAT_ALPHA:
  16288. internalFormat = this._gl.ALPHA;
  16289. break;
  16290. case Engine.TEXTUREFORMAT_LUMINANCE:
  16291. internalFormat = this._gl.LUMINANCE;
  16292. break;
  16293. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16294. internalFormat = this._gl.LUMINANCE_ALPHA;
  16295. break;
  16296. case Engine.TEXTUREFORMAT_RGB:
  16297. case Engine.TEXTUREFORMAT_RGB32F:
  16298. internalFormat = this._gl.RGB;
  16299. break;
  16300. case Engine.TEXTUREFORMAT_RGBA:
  16301. case Engine.TEXTUREFORMAT_RGBA32F:
  16302. internalFormat = this._gl.RGBA;
  16303. break;
  16304. case Engine.TEXTUREFORMAT_R32F:
  16305. internalFormat = this._gl.RED;
  16306. break;
  16307. case Engine.TEXTUREFORMAT_RG32F:
  16308. internalFormat = this._gl.RG;
  16309. break;
  16310. }
  16311. return internalFormat;
  16312. };
  16313. /** @ignore */
  16314. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16315. if (this._webGLVersion === 1) {
  16316. if (format) {
  16317. switch (format) {
  16318. case Engine.TEXTUREFORMAT_LUMINANCE:
  16319. return this._gl.LUMINANCE;
  16320. }
  16321. }
  16322. return this._gl.RGBA;
  16323. }
  16324. if (type === Engine.TEXTURETYPE_FLOAT) {
  16325. if (format) {
  16326. switch (format) {
  16327. case Engine.TEXTUREFORMAT_R32F:
  16328. return this._gl.R32F;
  16329. case Engine.TEXTUREFORMAT_RG32F:
  16330. return this._gl.RG32F;
  16331. case Engine.TEXTUREFORMAT_RGB32F:
  16332. return this._gl.RGB32F;
  16333. }
  16334. }
  16335. return this._gl.RGBA32F;
  16336. }
  16337. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16338. return this._gl.RGBA16F;
  16339. }
  16340. if (format) {
  16341. switch (format) {
  16342. case Engine.TEXTUREFORMAT_LUMINANCE:
  16343. return this._gl.LUMINANCE;
  16344. }
  16345. }
  16346. return this._gl.RGBA;
  16347. };
  16348. ;
  16349. /** @ignore */
  16350. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16351. if (type === Engine.TEXTURETYPE_FLOAT) {
  16352. return this._gl.RGBA32F;
  16353. }
  16354. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16355. return this._gl.RGBA16F;
  16356. }
  16357. return this._gl.RGBA8;
  16358. };
  16359. ;
  16360. /**
  16361. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16362. * @return the new query
  16363. */
  16364. Engine.prototype.createQuery = function () {
  16365. return this._gl.createQuery();
  16366. };
  16367. /**
  16368. * Delete and release a webGL query
  16369. * @param query defines the query to delete
  16370. * @return the current engine
  16371. */
  16372. Engine.prototype.deleteQuery = function (query) {
  16373. this._gl.deleteQuery(query);
  16374. return this;
  16375. };
  16376. /**
  16377. * Check if a given query has resolved and got its value
  16378. * @param query defines the query to check
  16379. * @returns true if the query got its value
  16380. */
  16381. Engine.prototype.isQueryResultAvailable = function (query) {
  16382. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16383. };
  16384. /**
  16385. * Gets the value of a given query
  16386. * @param query defines the query to check
  16387. * @returns the value of the query
  16388. */
  16389. Engine.prototype.getQueryResult = function (query) {
  16390. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16391. };
  16392. /**
  16393. * Initiates an occlusion query
  16394. * @param algorithmType defines the algorithm to use
  16395. * @param query defines the query to use
  16396. * @returns the current engine
  16397. * @see http://doc.babylonjs.com/features/occlusionquery
  16398. */
  16399. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16400. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16401. this._gl.beginQuery(glAlgorithm, query);
  16402. return this;
  16403. };
  16404. /**
  16405. * Ends an occlusion query
  16406. * @see http://doc.babylonjs.com/features/occlusionquery
  16407. * @param algorithmType defines the algorithm to use
  16408. * @returns the current engine
  16409. */
  16410. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16411. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16412. this._gl.endQuery(glAlgorithm);
  16413. return this;
  16414. };
  16415. /* Time queries */
  16416. Engine.prototype._createTimeQuery = function () {
  16417. var timerQuery = this._caps.timerQuery;
  16418. if (timerQuery.createQueryEXT) {
  16419. return timerQuery.createQueryEXT();
  16420. }
  16421. return this.createQuery();
  16422. };
  16423. Engine.prototype._deleteTimeQuery = function (query) {
  16424. var timerQuery = this._caps.timerQuery;
  16425. if (timerQuery.deleteQueryEXT) {
  16426. timerQuery.deleteQueryEXT(query);
  16427. return;
  16428. }
  16429. this.deleteQuery(query);
  16430. };
  16431. Engine.prototype._getTimeQueryResult = function (query) {
  16432. var timerQuery = this._caps.timerQuery;
  16433. if (timerQuery.getQueryObjectEXT) {
  16434. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16435. }
  16436. return this.getQueryResult(query);
  16437. };
  16438. Engine.prototype._getTimeQueryAvailability = function (query) {
  16439. var timerQuery = this._caps.timerQuery;
  16440. if (timerQuery.getQueryObjectEXT) {
  16441. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16442. }
  16443. return this.isQueryResultAvailable(query);
  16444. };
  16445. /**
  16446. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16447. * Please note that only one query can be issued at a time
  16448. * @returns a time token used to track the time span
  16449. */
  16450. Engine.prototype.startTimeQuery = function () {
  16451. var timerQuery = this._caps.timerQuery;
  16452. if (!timerQuery) {
  16453. return null;
  16454. }
  16455. var token = new BABYLON._TimeToken();
  16456. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16457. if (this._caps.canUseTimestampForTimerQuery) {
  16458. token._startTimeQuery = this._createTimeQuery();
  16459. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16460. }
  16461. else {
  16462. if (this._currentNonTimestampToken) {
  16463. return this._currentNonTimestampToken;
  16464. }
  16465. token._timeElapsedQuery = this._createTimeQuery();
  16466. if (timerQuery.beginQueryEXT) {
  16467. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16468. }
  16469. else {
  16470. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16471. }
  16472. this._currentNonTimestampToken = token;
  16473. }
  16474. return token;
  16475. };
  16476. /**
  16477. * Ends a time query
  16478. * @param token defines the token used to measure the time span
  16479. * @returns the time spent (in ns)
  16480. */
  16481. Engine.prototype.endTimeQuery = function (token) {
  16482. var timerQuery = this._caps.timerQuery;
  16483. if (!timerQuery || !token) {
  16484. return -1;
  16485. }
  16486. if (this._caps.canUseTimestampForTimerQuery) {
  16487. if (!token._startTimeQuery) {
  16488. return -1;
  16489. }
  16490. if (!token._endTimeQuery) {
  16491. token._endTimeQuery = this._createTimeQuery();
  16492. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16493. }
  16494. }
  16495. else if (!token._timeElapsedQueryEnded) {
  16496. if (!token._timeElapsedQuery) {
  16497. return -1;
  16498. }
  16499. if (timerQuery.endQueryEXT) {
  16500. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16501. }
  16502. else {
  16503. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16504. }
  16505. token._timeElapsedQueryEnded = true;
  16506. }
  16507. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16508. var available = false;
  16509. if (token._endTimeQuery) {
  16510. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16511. }
  16512. else if (token._timeElapsedQuery) {
  16513. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16514. }
  16515. if (available && !disjoint) {
  16516. var result = 0;
  16517. if (this._caps.canUseTimestampForTimerQuery) {
  16518. if (!token._startTimeQuery || !token._endTimeQuery) {
  16519. return -1;
  16520. }
  16521. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16522. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16523. result = timeEnd - timeStart;
  16524. this._deleteTimeQuery(token._startTimeQuery);
  16525. this._deleteTimeQuery(token._endTimeQuery);
  16526. token._startTimeQuery = null;
  16527. token._endTimeQuery = null;
  16528. }
  16529. else {
  16530. if (!token._timeElapsedQuery) {
  16531. return -1;
  16532. }
  16533. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16534. this._deleteTimeQuery(token._timeElapsedQuery);
  16535. token._timeElapsedQuery = null;
  16536. token._timeElapsedQueryEnded = false;
  16537. this._currentNonTimestampToken = null;
  16538. }
  16539. return result;
  16540. }
  16541. return -1;
  16542. };
  16543. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16544. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16545. };
  16546. // Transform feedback
  16547. /**
  16548. * Creates a webGL transform feedback object
  16549. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16550. * @returns the webGL transform feedback object
  16551. */
  16552. Engine.prototype.createTransformFeedback = function () {
  16553. return this._gl.createTransformFeedback();
  16554. };
  16555. /**
  16556. * Delete a webGL transform feedback object
  16557. * @param value defines the webGL transform feedback object to delete
  16558. */
  16559. Engine.prototype.deleteTransformFeedback = function (value) {
  16560. this._gl.deleteTransformFeedback(value);
  16561. };
  16562. /**
  16563. * Bind a webGL transform feedback object to the webgl context
  16564. * @param value defines the webGL transform feedback object to bind
  16565. */
  16566. Engine.prototype.bindTransformFeedback = function (value) {
  16567. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16568. };
  16569. /**
  16570. * Begins a transform feedback operation
  16571. * @param usePoints defines if points or triangles must be used
  16572. */
  16573. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16574. if (usePoints === void 0) { usePoints = true; }
  16575. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16576. };
  16577. /**
  16578. * Ends a transform feedback operation
  16579. */
  16580. Engine.prototype.endTransformFeedback = function () {
  16581. this._gl.endTransformFeedback();
  16582. };
  16583. /**
  16584. * Specify the varyings to use with transform feedback
  16585. * @param program defines the associated webGL program
  16586. * @param value defines the list of strings representing the varying names
  16587. */
  16588. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  16589. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  16590. };
  16591. /**
  16592. * Bind a webGL buffer for a transform feedback operation
  16593. * @param value defines the webGL buffer to bind
  16594. */
  16595. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  16596. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  16597. };
  16598. /** @ignore */
  16599. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16600. var _this = this;
  16601. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16602. this._activeRequests.push(request);
  16603. request.onCompleteObservable.add(function (request) {
  16604. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16605. });
  16606. return request;
  16607. };
  16608. /** @ignore */
  16609. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16610. var _this = this;
  16611. return new Promise(function (resolve, reject) {
  16612. _this._loadFile(url, function (data) {
  16613. resolve(data);
  16614. }, undefined, database, useArrayBuffer, function (request, exception) {
  16615. reject(exception);
  16616. });
  16617. });
  16618. };
  16619. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16620. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16621. var onload = function (data) {
  16622. loadedFiles[index] = data;
  16623. loadedFiles._internalCount++;
  16624. if (loadedFiles._internalCount === 6) {
  16625. onfinish(loadedFiles);
  16626. }
  16627. };
  16628. var onerror = function (request, exception) {
  16629. if (onErrorCallBack && request) {
  16630. onErrorCallBack(request.status + " " + request.statusText, exception);
  16631. }
  16632. };
  16633. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16634. };
  16635. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16636. if (onError === void 0) { onError = null; }
  16637. var loadedFiles = [];
  16638. loadedFiles._internalCount = 0;
  16639. for (var index = 0; index < 6; index++) {
  16640. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16641. }
  16642. };
  16643. // Statics
  16644. /**
  16645. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16646. * @returns true if the engine can be created
  16647. * @ignoreNaming
  16648. */
  16649. Engine.isSupported = function () {
  16650. try {
  16651. var tempcanvas = document.createElement("canvas");
  16652. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  16653. return gl != null && !!window.WebGLRenderingContext;
  16654. }
  16655. catch (e) {
  16656. return false;
  16657. }
  16658. };
  16659. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  16660. Engine.ExceptionList = [
  16661. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  16662. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16663. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16664. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16665. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16666. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  16667. ];
  16668. /** Gets the list of created engines */
  16669. Engine.Instances = new Array();
  16670. // Const statics
  16671. Engine._ALPHA_DISABLE = 0;
  16672. Engine._ALPHA_ADD = 1;
  16673. Engine._ALPHA_COMBINE = 2;
  16674. Engine._ALPHA_SUBTRACT = 3;
  16675. Engine._ALPHA_MULTIPLY = 4;
  16676. Engine._ALPHA_MAXIMIZED = 5;
  16677. Engine._ALPHA_ONEONE = 6;
  16678. Engine._ALPHA_PREMULTIPLIED = 7;
  16679. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  16680. Engine._ALPHA_INTERPOLATE = 9;
  16681. Engine._ALPHA_SCREENMODE = 10;
  16682. Engine._DELAYLOADSTATE_NONE = 0;
  16683. Engine._DELAYLOADSTATE_LOADED = 1;
  16684. Engine._DELAYLOADSTATE_LOADING = 2;
  16685. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  16686. Engine._TEXTUREFORMAT_ALPHA = 0;
  16687. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  16688. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  16689. Engine._TEXTUREFORMAT_RGB = 4;
  16690. Engine._TEXTUREFORMAT_RGBA = 5;
  16691. Engine._TEXTUREFORMAT_R32F = 6;
  16692. Engine._TEXTUREFORMAT_RG32F = 7;
  16693. Engine._TEXTUREFORMAT_RGB32F = 8;
  16694. Engine._TEXTUREFORMAT_RGBA32F = 9;
  16695. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  16696. Engine._TEXTURETYPE_FLOAT = 1;
  16697. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  16698. // Depht or Stencil test Constants.
  16699. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  16700. 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.
  16701. 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.
  16702. 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.
  16703. 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.
  16704. 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.
  16705. 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.
  16706. 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.
  16707. // Stencil Actions Constants.
  16708. Engine._KEEP = 0x1E00;
  16709. Engine._REPLACE = 0x1E01;
  16710. Engine._INCR = 0x1E02;
  16711. Engine._DECR = 0x1E03;
  16712. Engine._INVERT = 0x150A;
  16713. Engine._INCR_WRAP = 0x8507;
  16714. Engine._DECR_WRAP = 0x8508;
  16715. // Texture rescaling mode
  16716. Engine._SCALEMODE_FLOOR = 1;
  16717. Engine._SCALEMODE_NEAREST = 2;
  16718. Engine._SCALEMODE_CEILING = 3;
  16719. // Updatable statics so stick with vars here
  16720. /**
  16721. * Gets or sets the epsilon value used by collision engine
  16722. */
  16723. Engine.CollisionsEpsilon = 0.001;
  16724. /**
  16725. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  16726. */
  16727. Engine.CodeRepository = "src/";
  16728. /**
  16729. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  16730. */
  16731. Engine.ShadersRepository = "src/Shaders/";
  16732. return Engine;
  16733. }());
  16734. BABYLON.Engine = Engine;
  16735. })(BABYLON || (BABYLON = {}));
  16736. //# sourceMappingURL=babylon.engine.js.map
  16737. "use strict";
  16738. var BABYLON;
  16739. (function (BABYLON) {
  16740. /**
  16741. * Node is the basic class for all scene objects (Mesh, Light Camera).
  16742. */
  16743. var Node = /** @class */ (function () {
  16744. /**
  16745. * Creates a new Node
  16746. * @param {string} name - the name and id to be given to this node
  16747. * @param {BABYLON.Scene} the scene this node will be added to
  16748. */
  16749. function Node(name, scene) {
  16750. if (scene === void 0) { scene = null; }
  16751. /**
  16752. * Gets or sets a string used to store user defined state for the node
  16753. */
  16754. this.state = "";
  16755. /**
  16756. * Gets or sets an object used to store user defined information for the node
  16757. */
  16758. this.metadata = null;
  16759. /**
  16760. * Gets or sets a boolean used to define if the node must be serialized
  16761. */
  16762. this.doNotSerialize = false;
  16763. /** @ignore */
  16764. this._isDisposed = false;
  16765. /**
  16766. * Gets a list of Animations associated with the node
  16767. */
  16768. this.animations = new Array();
  16769. this._ranges = {};
  16770. this._isEnabled = true;
  16771. this._isReady = true;
  16772. /** @ignore */
  16773. this._currentRenderId = -1;
  16774. this._parentRenderId = -1;
  16775. this._childRenderId = -1;
  16776. this._animationPropertiesOverride = null;
  16777. /**
  16778. * An event triggered when the mesh is disposed
  16779. */
  16780. this.onDisposeObservable = new BABYLON.Observable();
  16781. // Behaviors
  16782. this._behaviors = new Array();
  16783. this.name = name;
  16784. this.id = name;
  16785. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  16786. this.uniqueId = this._scene.getUniqueId();
  16787. this._initCache();
  16788. }
  16789. /**
  16790. * Gets a boolean indicating if the node has been disposed
  16791. * @returns true if the node was disposed
  16792. */
  16793. Node.prototype.isDisposed = function () {
  16794. return this._isDisposed;
  16795. };
  16796. Object.defineProperty(Node.prototype, "parent", {
  16797. get: function () {
  16798. return this._parentNode;
  16799. },
  16800. /**
  16801. * Gets or sets the parent of the node
  16802. */
  16803. set: function (parent) {
  16804. if (this._parentNode === parent) {
  16805. return;
  16806. }
  16807. // Remove self from list of children of parent
  16808. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  16809. var index = this._parentNode._children.indexOf(this);
  16810. if (index !== -1) {
  16811. this._parentNode._children.splice(index, 1);
  16812. }
  16813. }
  16814. // Store new parent
  16815. this._parentNode = parent;
  16816. // Add as child to new parent
  16817. if (this._parentNode) {
  16818. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  16819. this._parentNode._children = new Array();
  16820. }
  16821. this._parentNode._children.push(this);
  16822. }
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  16828. /**
  16829. * Gets or sets the animation properties override
  16830. */
  16831. get: function () {
  16832. return this._animationPropertiesOverride;
  16833. },
  16834. set: function (value) {
  16835. this._animationPropertiesOverride = value;
  16836. },
  16837. enumerable: true,
  16838. configurable: true
  16839. });
  16840. /**
  16841. * Gets a string idenfifying the name of the class
  16842. * @returns "Node" string
  16843. */
  16844. Node.prototype.getClassName = function () {
  16845. return "Node";
  16846. };
  16847. Object.defineProperty(Node.prototype, "onDispose", {
  16848. /**
  16849. * Sets a callback that will be raised when the node will be disposed
  16850. */
  16851. set: function (callback) {
  16852. if (this._onDisposeObserver) {
  16853. this.onDisposeObservable.remove(this._onDisposeObserver);
  16854. }
  16855. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16856. },
  16857. enumerable: true,
  16858. configurable: true
  16859. });
  16860. /**
  16861. * Gets the scene of the node
  16862. * @returns a {BABYLON.Scene}
  16863. */
  16864. Node.prototype.getScene = function () {
  16865. return this._scene;
  16866. };
  16867. /**
  16868. * Gets the engine of the node
  16869. * @returns a {BABYLON.Engine}
  16870. */
  16871. Node.prototype.getEngine = function () {
  16872. return this._scene.getEngine();
  16873. };
  16874. /**
  16875. * Attach a behavior to the node
  16876. * @see http://doc.babylonjs.com/features/behaviour
  16877. * @param behavior defines the behavior to attach
  16878. * @returns the current Node
  16879. */
  16880. Node.prototype.addBehavior = function (behavior) {
  16881. var _this = this;
  16882. var index = this._behaviors.indexOf(behavior);
  16883. if (index !== -1) {
  16884. return this;
  16885. }
  16886. behavior.init();
  16887. if (this._scene.isLoading) {
  16888. // We defer the attach when the scene will be loaded
  16889. var observer = this._scene.onDataLoadedObservable.add(function () {
  16890. behavior.attach(_this);
  16891. setTimeout(function () {
  16892. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  16893. _this._scene.onDataLoadedObservable.remove(observer);
  16894. }, 0);
  16895. });
  16896. }
  16897. else {
  16898. behavior.attach(this);
  16899. }
  16900. this._behaviors.push(behavior);
  16901. return this;
  16902. };
  16903. /**
  16904. * Remove an attached behavior
  16905. * @see http://doc.babylonjs.com/features/behaviour
  16906. * @param behavior defines the behavior to attach
  16907. * @returns the current Node
  16908. */
  16909. Node.prototype.removeBehavior = function (behavior) {
  16910. var index = this._behaviors.indexOf(behavior);
  16911. if (index === -1) {
  16912. return this;
  16913. }
  16914. this._behaviors[index].detach();
  16915. this._behaviors.splice(index, 1);
  16916. return this;
  16917. };
  16918. Object.defineProperty(Node.prototype, "behaviors", {
  16919. /**
  16920. * Gets the list of attached behaviors
  16921. * @see http://doc.babylonjs.com/features/behaviour
  16922. */
  16923. get: function () {
  16924. return this._behaviors;
  16925. },
  16926. enumerable: true,
  16927. configurable: true
  16928. });
  16929. /**
  16930. * Gets an attached behavior by name
  16931. * @param name defines the name of the behavior to look for
  16932. * @see http://doc.babylonjs.com/features/behaviour
  16933. * @returns null if behavior was not found else the requested behavior
  16934. */
  16935. Node.prototype.getBehaviorByName = function (name) {
  16936. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  16937. var behavior = _a[_i];
  16938. if (behavior.name === name) {
  16939. return behavior;
  16940. }
  16941. }
  16942. return null;
  16943. };
  16944. /**
  16945. * Returns the world matrix of the node
  16946. * @returns a matrix containing the node's world matrix
  16947. */
  16948. Node.prototype.getWorldMatrix = function () {
  16949. return BABYLON.Matrix.Identity();
  16950. };
  16951. // override it in derived class if you add new variables to the cache
  16952. // and call the parent class method
  16953. /** @ignore */
  16954. Node.prototype._initCache = function () {
  16955. this._cache = {};
  16956. this._cache.parent = undefined;
  16957. };
  16958. /** @ignore */
  16959. Node.prototype.updateCache = function (force) {
  16960. if (!force && this.isSynchronized())
  16961. return;
  16962. this._cache.parent = this.parent;
  16963. this._updateCache();
  16964. };
  16965. // override it in derived class if you add new variables to the cache
  16966. // and call the parent class method if !ignoreParentClass
  16967. /** @ignore */
  16968. Node.prototype._updateCache = function (ignoreParentClass) {
  16969. };
  16970. // override it in derived class if you add new variables to the cache
  16971. /** @ignore */
  16972. Node.prototype._isSynchronized = function () {
  16973. return true;
  16974. };
  16975. /** @ignore */
  16976. Node.prototype._markSyncedWithParent = function () {
  16977. if (this.parent) {
  16978. this._parentRenderId = this.parent._childRenderId;
  16979. }
  16980. };
  16981. /** @ignore */
  16982. Node.prototype.isSynchronizedWithParent = function () {
  16983. if (!this.parent) {
  16984. return true;
  16985. }
  16986. if (this._parentRenderId !== this.parent._childRenderId) {
  16987. return false;
  16988. }
  16989. return this.parent.isSynchronized();
  16990. };
  16991. /** @ignore */
  16992. Node.prototype.isSynchronized = function (updateCache) {
  16993. var check = this.hasNewParent();
  16994. check = check || !this.isSynchronizedWithParent();
  16995. check = check || !this._isSynchronized();
  16996. if (updateCache)
  16997. this.updateCache(true);
  16998. return !check;
  16999. };
  17000. /** @ignore */
  17001. Node.prototype.hasNewParent = function (update) {
  17002. if (this._cache.parent === this.parent)
  17003. return false;
  17004. if (update)
  17005. this._cache.parent = this.parent;
  17006. return true;
  17007. };
  17008. /**
  17009. * Is this node ready to be used/rendered
  17010. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17011. * @return true if the node is ready
  17012. */
  17013. Node.prototype.isReady = function (completeCheck) {
  17014. if (completeCheck === void 0) { completeCheck = false; }
  17015. return this._isReady;
  17016. };
  17017. /**
  17018. * Is this node enabled?
  17019. * 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
  17020. * @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
  17021. * @return whether this node (and its parent) is enabled
  17022. */
  17023. Node.prototype.isEnabled = function (checkAncestors) {
  17024. if (checkAncestors === void 0) { checkAncestors = true; }
  17025. if (checkAncestors === false) {
  17026. return this._isEnabled;
  17027. }
  17028. if (this._isEnabled === false) {
  17029. return false;
  17030. }
  17031. if (this.parent !== undefined && this.parent !== null) {
  17032. return this.parent.isEnabled(checkAncestors);
  17033. }
  17034. return true;
  17035. };
  17036. /**
  17037. * Set the enabled state of this node
  17038. * @param value defines the new enabled state
  17039. */
  17040. Node.prototype.setEnabled = function (value) {
  17041. this._isEnabled = value;
  17042. };
  17043. /**
  17044. * Is this node a descendant of the given node?
  17045. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17046. * @param ancestor defines the parent node to inspect
  17047. * @returns a boolean indicating if this node is a descendant of the given node
  17048. */
  17049. Node.prototype.isDescendantOf = function (ancestor) {
  17050. if (this.parent) {
  17051. if (this.parent === ancestor) {
  17052. return true;
  17053. }
  17054. return this.parent.isDescendantOf(ancestor);
  17055. }
  17056. return false;
  17057. };
  17058. /** @ignore */
  17059. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17060. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17061. if (!this._children) {
  17062. return;
  17063. }
  17064. for (var index = 0; index < this._children.length; index++) {
  17065. var item = this._children[index];
  17066. if (!predicate || predicate(item)) {
  17067. results.push(item);
  17068. }
  17069. if (!directDescendantsOnly) {
  17070. item._getDescendants(results, false, predicate);
  17071. }
  17072. }
  17073. };
  17074. /**
  17075. * Will return all nodes that have this node as ascendant
  17076. * @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
  17077. * @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
  17078. * @return all children nodes of all types
  17079. */
  17080. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17081. var results = new Array();
  17082. this._getDescendants(results, directDescendantsOnly, predicate);
  17083. return results;
  17084. };
  17085. /**
  17086. * Get all child-meshes of this node
  17087. * @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
  17088. * @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
  17089. * @returns an array of {BABYLON.AbstractMesh}
  17090. */
  17091. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17092. var results = [];
  17093. this._getDescendants(results, directDescendantsOnly, function (node) {
  17094. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17095. });
  17096. return results;
  17097. };
  17098. /**
  17099. * Get all child-transformNodes of this node
  17100. * @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
  17101. * @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
  17102. * @returns an array of {BABYLON.TransformNode}
  17103. */
  17104. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17105. var results = [];
  17106. this._getDescendants(results, directDescendantsOnly, function (node) {
  17107. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17108. });
  17109. return results;
  17110. };
  17111. /**
  17112. * Get all direct children of this node
  17113. * @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
  17114. * @returns an array of {BABYLON.Node}
  17115. */
  17116. Node.prototype.getChildren = function (predicate) {
  17117. return this.getDescendants(true, predicate);
  17118. };
  17119. /** @ignore */
  17120. Node.prototype._setReady = function (state) {
  17121. if (state === this._isReady) {
  17122. return;
  17123. }
  17124. if (!state) {
  17125. this._isReady = false;
  17126. return;
  17127. }
  17128. if (this.onReady) {
  17129. this.onReady(this);
  17130. }
  17131. this._isReady = true;
  17132. };
  17133. /**
  17134. * Get an animation by name
  17135. * @param name defines the name of the animation to look for
  17136. * @returns null if not found else the requested animation
  17137. */
  17138. Node.prototype.getAnimationByName = function (name) {
  17139. for (var i = 0; i < this.animations.length; i++) {
  17140. var animation = this.animations[i];
  17141. if (animation.name === name) {
  17142. return animation;
  17143. }
  17144. }
  17145. return null;
  17146. };
  17147. /**
  17148. * Creates an animation range for this node
  17149. * @param name defines the name of the range
  17150. * @param from defines the starting key
  17151. * @param to defines the end key
  17152. */
  17153. Node.prototype.createAnimationRange = function (name, from, to) {
  17154. // check name not already in use
  17155. if (!this._ranges[name]) {
  17156. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17157. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17158. if (this.animations[i]) {
  17159. this.animations[i].createRange(name, from, to);
  17160. }
  17161. }
  17162. }
  17163. };
  17164. /**
  17165. * Delete a specific animation range
  17166. * @param name defines the name of the range to delete
  17167. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17168. */
  17169. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17170. if (deleteFrames === void 0) { deleteFrames = true; }
  17171. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17172. if (this.animations[i]) {
  17173. this.animations[i].deleteRange(name, deleteFrames);
  17174. }
  17175. }
  17176. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17177. };
  17178. /**
  17179. * Get an animation range by name
  17180. * @param name defines the name of the animation range to look for
  17181. * @returns null if not found else the requested animation range
  17182. */
  17183. Node.prototype.getAnimationRange = function (name) {
  17184. return this._ranges[name];
  17185. };
  17186. /**
  17187. * Will start the animation sequence
  17188. * @param name defines the range frames for animation sequence
  17189. * @param loop defines if the animation should loop (false by default)
  17190. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17191. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17192. * @returns the object created for this animation. If range does not exist, it will return null
  17193. */
  17194. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17195. var range = this.getAnimationRange(name);
  17196. if (!range) {
  17197. return null;
  17198. }
  17199. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17200. };
  17201. /**
  17202. * Serialize animation ranges into a JSON compatible object
  17203. * @returns serialization object
  17204. */
  17205. Node.prototype.serializeAnimationRanges = function () {
  17206. var serializationRanges = [];
  17207. for (var name in this._ranges) {
  17208. var localRange = this._ranges[name];
  17209. if (!localRange) {
  17210. continue;
  17211. }
  17212. var range = {};
  17213. range.name = name;
  17214. range.from = localRange.from;
  17215. range.to = localRange.to;
  17216. serializationRanges.push(range);
  17217. }
  17218. return serializationRanges;
  17219. };
  17220. /**
  17221. * Computes the world matrix of the node
  17222. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17223. * @returns the world matrix
  17224. */
  17225. Node.prototype.computeWorldMatrix = function (force) {
  17226. return BABYLON.Matrix.Identity();
  17227. };
  17228. /**
  17229. * Releases resources associated with this node.
  17230. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17231. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17232. */
  17233. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17234. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17235. if (!doNotRecurse) {
  17236. var nodes = this.getDescendants(true);
  17237. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17238. var node = nodes_1[_i];
  17239. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17240. }
  17241. }
  17242. else {
  17243. var transformNodes = this.getChildTransformNodes(true);
  17244. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17245. var transformNode = transformNodes_1[_a];
  17246. transformNode.parent = null;
  17247. transformNode.computeWorldMatrix(true);
  17248. }
  17249. }
  17250. this.parent = null;
  17251. // Callback
  17252. this.onDisposeObservable.notifyObservers(this);
  17253. this.onDisposeObservable.clear();
  17254. // Behaviors
  17255. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17256. var behavior = _c[_b];
  17257. behavior.detach();
  17258. }
  17259. this._behaviors = [];
  17260. this._isDisposed = true;
  17261. };
  17262. /**
  17263. * Parse animation range data from a serialization object and store them into a given node
  17264. * @param node defines where to store the animation ranges
  17265. * @param parsedNode defines the serialization object to read data from
  17266. * @param scene defines the hosting scene
  17267. */
  17268. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17269. if (parsedNode.ranges) {
  17270. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17271. var data = parsedNode.ranges[index];
  17272. node.createAnimationRange(data.name, data.from, data.to);
  17273. }
  17274. }
  17275. };
  17276. __decorate([
  17277. BABYLON.serialize()
  17278. ], Node.prototype, "name", void 0);
  17279. __decorate([
  17280. BABYLON.serialize()
  17281. ], Node.prototype, "id", void 0);
  17282. __decorate([
  17283. BABYLON.serialize()
  17284. ], Node.prototype, "uniqueId", void 0);
  17285. __decorate([
  17286. BABYLON.serialize()
  17287. ], Node.prototype, "state", void 0);
  17288. __decorate([
  17289. BABYLON.serialize()
  17290. ], Node.prototype, "metadata", void 0);
  17291. return Node;
  17292. }());
  17293. BABYLON.Node = Node;
  17294. })(BABYLON || (BABYLON = {}));
  17295. //# sourceMappingURL=babylon.node.js.map
  17296. "use strict";
  17297. var BABYLON;
  17298. (function (BABYLON) {
  17299. var BoundingSphere = /** @class */ (function () {
  17300. function BoundingSphere(minimum, maximum) {
  17301. this.minimum = minimum;
  17302. this.maximum = maximum;
  17303. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17304. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17305. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17306. this.radius = distance * 0.5;
  17307. this.centerWorld = BABYLON.Vector3.Zero();
  17308. this._update(BABYLON.Matrix.Identity());
  17309. }
  17310. // Methods
  17311. BoundingSphere.prototype._update = function (world) {
  17312. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17313. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17314. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17315. };
  17316. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17317. for (var i = 0; i < 6; i++) {
  17318. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17319. return false;
  17320. }
  17321. return true;
  17322. };
  17323. BoundingSphere.prototype.intersectsPoint = function (point) {
  17324. var x = this.centerWorld.x - point.x;
  17325. var y = this.centerWorld.y - point.y;
  17326. var z = this.centerWorld.z - point.z;
  17327. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17328. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17329. return false;
  17330. return true;
  17331. };
  17332. // Statics
  17333. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17334. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17335. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17336. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17337. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17338. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17339. return false;
  17340. return true;
  17341. };
  17342. return BoundingSphere;
  17343. }());
  17344. BABYLON.BoundingSphere = BoundingSphere;
  17345. })(BABYLON || (BABYLON = {}));
  17346. //# sourceMappingURL=babylon.boundingSphere.js.map
  17347. "use strict";
  17348. var BABYLON;
  17349. (function (BABYLON) {
  17350. var BoundingBox = /** @class */ (function () {
  17351. function BoundingBox(minimum, maximum) {
  17352. this.minimum = minimum;
  17353. this.maximum = maximum;
  17354. this.vectors = new Array();
  17355. this.vectorsWorld = new Array();
  17356. // Bounding vectors
  17357. this.vectors.push(this.minimum.clone());
  17358. this.vectors.push(this.maximum.clone());
  17359. this.vectors.push(this.minimum.clone());
  17360. this.vectors[2].x = this.maximum.x;
  17361. this.vectors.push(this.minimum.clone());
  17362. this.vectors[3].y = this.maximum.y;
  17363. this.vectors.push(this.minimum.clone());
  17364. this.vectors[4].z = this.maximum.z;
  17365. this.vectors.push(this.maximum.clone());
  17366. this.vectors[5].z = this.minimum.z;
  17367. this.vectors.push(this.maximum.clone());
  17368. this.vectors[6].x = this.minimum.x;
  17369. this.vectors.push(this.maximum.clone());
  17370. this.vectors[7].y = this.minimum.y;
  17371. // OBB
  17372. this.center = this.maximum.add(this.minimum).scale(0.5);
  17373. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17374. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17375. // World
  17376. for (var index = 0; index < this.vectors.length; index++) {
  17377. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17378. }
  17379. this.minimumWorld = BABYLON.Vector3.Zero();
  17380. this.maximumWorld = BABYLON.Vector3.Zero();
  17381. this.centerWorld = BABYLON.Vector3.Zero();
  17382. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17383. this._update(BABYLON.Matrix.Identity());
  17384. }
  17385. // Methods
  17386. BoundingBox.prototype.getWorldMatrix = function () {
  17387. return this._worldMatrix;
  17388. };
  17389. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17390. this._worldMatrix.copyFrom(matrix);
  17391. return this;
  17392. };
  17393. BoundingBox.prototype._update = function (world) {
  17394. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17395. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17396. for (var index = 0; index < this.vectors.length; index++) {
  17397. var v = this.vectorsWorld[index];
  17398. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17399. if (v.x < this.minimumWorld.x)
  17400. this.minimumWorld.x = v.x;
  17401. if (v.y < this.minimumWorld.y)
  17402. this.minimumWorld.y = v.y;
  17403. if (v.z < this.minimumWorld.z)
  17404. this.minimumWorld.z = v.z;
  17405. if (v.x > this.maximumWorld.x)
  17406. this.maximumWorld.x = v.x;
  17407. if (v.y > this.maximumWorld.y)
  17408. this.maximumWorld.y = v.y;
  17409. if (v.z > this.maximumWorld.z)
  17410. this.maximumWorld.z = v.z;
  17411. }
  17412. // Extend
  17413. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17414. this.extendSizeWorld.scaleInPlace(0.5);
  17415. // OBB
  17416. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17417. this.centerWorld.scaleInPlace(0.5);
  17418. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17419. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17420. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17421. this._worldMatrix = world;
  17422. };
  17423. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17424. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17425. };
  17426. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17427. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17428. };
  17429. BoundingBox.prototype.intersectsPoint = function (point) {
  17430. var delta = -BABYLON.Epsilon;
  17431. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17432. return false;
  17433. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17434. return false;
  17435. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17436. return false;
  17437. return true;
  17438. };
  17439. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17440. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17441. };
  17442. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17443. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17444. return false;
  17445. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17446. return false;
  17447. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17448. return false;
  17449. return true;
  17450. };
  17451. // Statics
  17452. BoundingBox.Intersects = function (box0, box1) {
  17453. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17454. return false;
  17455. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17456. return false;
  17457. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17458. return false;
  17459. return true;
  17460. };
  17461. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17462. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17463. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17464. return (num <= (sphereRadius * sphereRadius));
  17465. };
  17466. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17467. for (var p = 0; p < 6; p++) {
  17468. for (var i = 0; i < 8; i++) {
  17469. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17470. return false;
  17471. }
  17472. }
  17473. }
  17474. return true;
  17475. };
  17476. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17477. for (var p = 0; p < 6; p++) {
  17478. var inCount = 8;
  17479. for (var i = 0; i < 8; i++) {
  17480. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17481. --inCount;
  17482. }
  17483. else {
  17484. break;
  17485. }
  17486. }
  17487. if (inCount === 0)
  17488. return false;
  17489. }
  17490. return true;
  17491. };
  17492. return BoundingBox;
  17493. }());
  17494. BABYLON.BoundingBox = BoundingBox;
  17495. })(BABYLON || (BABYLON = {}));
  17496. //# sourceMappingURL=babylon.boundingBox.js.map
  17497. "use strict";
  17498. var BABYLON;
  17499. (function (BABYLON) {
  17500. var computeBoxExtents = function (axis, box) {
  17501. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17502. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17503. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17504. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17505. var r = r0 + r1 + r2;
  17506. return {
  17507. min: p - r,
  17508. max: p + r
  17509. };
  17510. };
  17511. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17512. var axisOverlap = function (axis, box0, box1) {
  17513. var result0 = computeBoxExtents(axis, box0);
  17514. var result1 = computeBoxExtents(axis, box1);
  17515. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17516. };
  17517. var BoundingInfo = /** @class */ (function () {
  17518. function BoundingInfo(minimum, maximum) {
  17519. this.minimum = minimum;
  17520. this.maximum = maximum;
  17521. this._isLocked = false;
  17522. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17523. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17524. }
  17525. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17526. get: function () {
  17527. return this._isLocked;
  17528. },
  17529. set: function (value) {
  17530. this._isLocked = value;
  17531. },
  17532. enumerable: true,
  17533. configurable: true
  17534. });
  17535. // Methods
  17536. BoundingInfo.prototype.update = function (world) {
  17537. if (this._isLocked) {
  17538. return;
  17539. }
  17540. this.boundingBox._update(world);
  17541. this.boundingSphere._update(world);
  17542. };
  17543. /**
  17544. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17545. * @param center New center of the bounding info
  17546. * @param extend New extend of the bounding info
  17547. */
  17548. BoundingInfo.prototype.centerOn = function (center, extend) {
  17549. this.minimum = center.subtract(extend);
  17550. this.maximum = center.add(extend);
  17551. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17552. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17553. return this;
  17554. };
  17555. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17556. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17557. return false;
  17558. return this.boundingBox.isInFrustum(frustumPlanes);
  17559. };
  17560. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17561. /**
  17562. * Gets the world distance between the min and max points of the bounding box
  17563. */
  17564. get: function () {
  17565. var boundingBox = this.boundingBox;
  17566. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  17567. return size.length();
  17568. },
  17569. enumerable: true,
  17570. configurable: true
  17571. });
  17572. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17573. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  17574. };
  17575. BoundingInfo.prototype._checkCollision = function (collider) {
  17576. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  17577. };
  17578. BoundingInfo.prototype.intersectsPoint = function (point) {
  17579. if (!this.boundingSphere.centerWorld) {
  17580. return false;
  17581. }
  17582. if (!this.boundingSphere.intersectsPoint(point)) {
  17583. return false;
  17584. }
  17585. if (!this.boundingBox.intersectsPoint(point)) {
  17586. return false;
  17587. }
  17588. return true;
  17589. };
  17590. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  17591. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  17592. return false;
  17593. }
  17594. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  17595. return false;
  17596. }
  17597. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  17598. return false;
  17599. }
  17600. if (!precise) {
  17601. return true;
  17602. }
  17603. var box0 = this.boundingBox;
  17604. var box1 = boundingInfo.boundingBox;
  17605. if (!axisOverlap(box0.directions[0], box0, box1))
  17606. return false;
  17607. if (!axisOverlap(box0.directions[1], box0, box1))
  17608. return false;
  17609. if (!axisOverlap(box0.directions[2], box0, box1))
  17610. return false;
  17611. if (!axisOverlap(box1.directions[0], box0, box1))
  17612. return false;
  17613. if (!axisOverlap(box1.directions[1], box0, box1))
  17614. return false;
  17615. if (!axisOverlap(box1.directions[2], box0, box1))
  17616. return false;
  17617. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  17618. return false;
  17619. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  17620. return false;
  17621. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  17622. return false;
  17623. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  17624. return false;
  17625. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  17626. return false;
  17627. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  17628. return false;
  17629. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  17630. return false;
  17631. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  17632. return false;
  17633. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  17634. return false;
  17635. return true;
  17636. };
  17637. return BoundingInfo;
  17638. }());
  17639. BABYLON.BoundingInfo = BoundingInfo;
  17640. })(BABYLON || (BABYLON = {}));
  17641. //# sourceMappingURL=babylon.boundingInfo.js.map
  17642. "use strict";
  17643. var BABYLON;
  17644. (function (BABYLON) {
  17645. var TransformNode = /** @class */ (function (_super) {
  17646. __extends(TransformNode, _super);
  17647. function TransformNode(name, scene, isPure) {
  17648. if (scene === void 0) { scene = null; }
  17649. if (isPure === void 0) { isPure = true; }
  17650. var _this = _super.call(this, name, scene) || this;
  17651. _this._forward = new BABYLON.Vector3(0, 0, 1);
  17652. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  17653. _this._up = new BABYLON.Vector3(0, 1, 0);
  17654. _this._right = new BABYLON.Vector3(1, 0, 0);
  17655. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  17656. // Properties
  17657. _this._rotation = BABYLON.Vector3.Zero();
  17658. _this._scaling = BABYLON.Vector3.One();
  17659. _this._isDirty = false;
  17660. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  17661. _this.scalingDeterminant = 1;
  17662. _this.infiniteDistance = false;
  17663. _this.position = BABYLON.Vector3.Zero();
  17664. _this._localWorld = BABYLON.Matrix.Zero();
  17665. _this._worldMatrix = BABYLON.Matrix.Zero();
  17666. _this._worldMatrixDeterminant = 0;
  17667. _this._absolutePosition = BABYLON.Vector3.Zero();
  17668. _this._pivotMatrix = BABYLON.Matrix.Identity();
  17669. _this._postMultiplyPivotMatrix = false;
  17670. _this._isWorldMatrixFrozen = false;
  17671. /**
  17672. * An event triggered after the world matrix is updated
  17673. */
  17674. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  17675. _this._nonUniformScaling = false;
  17676. if (isPure) {
  17677. _this.getScene().addTransformNode(_this);
  17678. }
  17679. return _this;
  17680. }
  17681. /**
  17682. * Gets a string idenfifying the name of the class
  17683. * @returns "TransformNode" string
  17684. */
  17685. TransformNode.prototype.getClassName = function () {
  17686. return "TransformNode";
  17687. };
  17688. Object.defineProperty(TransformNode.prototype, "rotation", {
  17689. /**
  17690. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  17691. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  17692. * Default : (0.0, 0.0, 0.0)
  17693. */
  17694. get: function () {
  17695. return this._rotation;
  17696. },
  17697. set: function (newRotation) {
  17698. this._rotation = newRotation;
  17699. },
  17700. enumerable: true,
  17701. configurable: true
  17702. });
  17703. Object.defineProperty(TransformNode.prototype, "scaling", {
  17704. /**
  17705. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17706. * Default : (1.0, 1.0, 1.0)
  17707. */
  17708. get: function () {
  17709. return this._scaling;
  17710. },
  17711. /**
  17712. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17713. * Default : (1.0, 1.0, 1.0)
  17714. */
  17715. set: function (newScaling) {
  17716. this._scaling = newScaling;
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  17722. /**
  17723. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  17724. * It's null by default.
  17725. * 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)
  17726. */
  17727. get: function () {
  17728. return this._rotationQuaternion;
  17729. },
  17730. set: function (quaternion) {
  17731. this._rotationQuaternion = quaternion;
  17732. //reset the rotation vector.
  17733. if (quaternion && this.rotation.length()) {
  17734. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  17735. }
  17736. },
  17737. enumerable: true,
  17738. configurable: true
  17739. });
  17740. Object.defineProperty(TransformNode.prototype, "forward", {
  17741. /**
  17742. * The forward direction of that transform in world space.
  17743. */
  17744. get: function () {
  17745. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(TransformNode.prototype, "up", {
  17751. /**
  17752. * The up direction of that transform in world space.
  17753. */
  17754. get: function () {
  17755. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(TransformNode.prototype, "right", {
  17761. /**
  17762. * The right direction of that transform in world space.
  17763. */
  17764. get: function () {
  17765. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. /**
  17771. * Returns the latest update of the World matrix
  17772. * Returns a Matrix.
  17773. */
  17774. TransformNode.prototype.getWorldMatrix = function () {
  17775. if (this._currentRenderId !== this.getScene().getRenderId()) {
  17776. this.computeWorldMatrix();
  17777. }
  17778. return this._worldMatrix;
  17779. };
  17780. /**
  17781. * Returns the latest update of the World matrix determinant.
  17782. */
  17783. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  17784. return this._worldMatrixDeterminant;
  17785. };
  17786. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  17787. /**
  17788. * Returns directly the latest state of the mesh World matrix.
  17789. * A Matrix is returned.
  17790. */
  17791. get: function () {
  17792. return this._worldMatrix;
  17793. },
  17794. enumerable: true,
  17795. configurable: true
  17796. });
  17797. /**
  17798. * Copies the paramater passed Matrix into the mesh Pose matrix.
  17799. * Returns the TransformNode.
  17800. */
  17801. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  17802. this._poseMatrix.copyFrom(matrix);
  17803. return this;
  17804. };
  17805. /**
  17806. * Returns the mesh Pose matrix.
  17807. * Returned object : Matrix
  17808. */
  17809. TransformNode.prototype.getPoseMatrix = function () {
  17810. return this._poseMatrix;
  17811. };
  17812. TransformNode.prototype._isSynchronized = function () {
  17813. if (this._isDirty) {
  17814. return false;
  17815. }
  17816. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  17817. return false;
  17818. if (this._cache.pivotMatrixUpdated) {
  17819. return false;
  17820. }
  17821. if (this.infiniteDistance) {
  17822. return false;
  17823. }
  17824. if (!this._cache.position.equals(this.position))
  17825. return false;
  17826. if (this.rotationQuaternion) {
  17827. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  17828. return false;
  17829. }
  17830. if (!this._cache.rotation.equals(this.rotation))
  17831. return false;
  17832. if (!this._cache.scaling.equals(this.scaling))
  17833. return false;
  17834. return true;
  17835. };
  17836. TransformNode.prototype._initCache = function () {
  17837. _super.prototype._initCache.call(this);
  17838. this._cache.localMatrixUpdated = false;
  17839. this._cache.position = BABYLON.Vector3.Zero();
  17840. this._cache.scaling = BABYLON.Vector3.Zero();
  17841. this._cache.rotation = BABYLON.Vector3.Zero();
  17842. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  17843. this._cache.billboardMode = -1;
  17844. };
  17845. TransformNode.prototype.markAsDirty = function (property) {
  17846. if (property === "rotation") {
  17847. this.rotationQuaternion = null;
  17848. }
  17849. this._currentRenderId = Number.MAX_VALUE;
  17850. this._isDirty = true;
  17851. return this;
  17852. };
  17853. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  17854. /**
  17855. * Returns the current mesh absolute position.
  17856. * Retuns a Vector3.
  17857. */
  17858. get: function () {
  17859. return this._absolutePosition;
  17860. },
  17861. enumerable: true,
  17862. configurable: true
  17863. });
  17864. /**
  17865. * Sets a new matrix to apply before all other transformation
  17866. * @param matrix defines the transform matrix
  17867. * @returns the current TransformNode
  17868. */
  17869. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  17870. return this.setPivotMatrix(matrix, false);
  17871. };
  17872. /**
  17873. * Sets a new pivot matrix to the current node
  17874. * @param matrix defines the new pivot matrix to use
  17875. * @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
  17876. * @returns the current TransformNode
  17877. */
  17878. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  17879. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  17880. this._pivotMatrix = matrix.clone();
  17881. this._cache.pivotMatrixUpdated = true;
  17882. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  17883. if (this._postMultiplyPivotMatrix) {
  17884. if (!this._pivotMatrixInverse) {
  17885. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  17886. }
  17887. else {
  17888. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  17889. }
  17890. }
  17891. return this;
  17892. };
  17893. /**
  17894. * Returns the mesh pivot matrix.
  17895. * Default : Identity.
  17896. * A Matrix is returned.
  17897. */
  17898. TransformNode.prototype.getPivotMatrix = function () {
  17899. return this._pivotMatrix;
  17900. };
  17901. /**
  17902. * Prevents the World matrix to be computed any longer.
  17903. * Returns the TransformNode.
  17904. */
  17905. TransformNode.prototype.freezeWorldMatrix = function () {
  17906. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  17907. this.computeWorldMatrix(true);
  17908. this._isWorldMatrixFrozen = true;
  17909. return this;
  17910. };
  17911. /**
  17912. * Allows back the World matrix computation.
  17913. * Returns the TransformNode.
  17914. */
  17915. TransformNode.prototype.unfreezeWorldMatrix = function () {
  17916. this._isWorldMatrixFrozen = false;
  17917. this.computeWorldMatrix(true);
  17918. return this;
  17919. };
  17920. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  17921. /**
  17922. * True if the World matrix has been frozen.
  17923. * Returns a boolean.
  17924. */
  17925. get: function () {
  17926. return this._isWorldMatrixFrozen;
  17927. },
  17928. enumerable: true,
  17929. configurable: true
  17930. });
  17931. /**
  17932. * Retuns the mesh absolute position in the World.
  17933. * Returns a Vector3.
  17934. */
  17935. TransformNode.prototype.getAbsolutePosition = function () {
  17936. this.computeWorldMatrix();
  17937. return this._absolutePosition;
  17938. };
  17939. /**
  17940. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  17941. * Returns the TransformNode.
  17942. */
  17943. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  17944. if (!absolutePosition) {
  17945. return this;
  17946. }
  17947. var absolutePositionX;
  17948. var absolutePositionY;
  17949. var absolutePositionZ;
  17950. if (absolutePosition.x === undefined) {
  17951. if (arguments.length < 3) {
  17952. return this;
  17953. }
  17954. absolutePositionX = arguments[0];
  17955. absolutePositionY = arguments[1];
  17956. absolutePositionZ = arguments[2];
  17957. }
  17958. else {
  17959. absolutePositionX = absolutePosition.x;
  17960. absolutePositionY = absolutePosition.y;
  17961. absolutePositionZ = absolutePosition.z;
  17962. }
  17963. if (this.parent) {
  17964. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17965. invertParentWorldMatrix.invert();
  17966. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  17967. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  17968. }
  17969. else {
  17970. this.position.x = absolutePositionX;
  17971. this.position.y = absolutePositionY;
  17972. this.position.z = absolutePositionZ;
  17973. }
  17974. return this;
  17975. };
  17976. /**
  17977. * Sets the mesh position in its local space.
  17978. * Returns the TransformNode.
  17979. */
  17980. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  17981. this.computeWorldMatrix();
  17982. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  17983. return this;
  17984. };
  17985. /**
  17986. * Returns the mesh position in the local space from the current World matrix values.
  17987. * Returns a new Vector3.
  17988. */
  17989. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  17990. this.computeWorldMatrix();
  17991. var invLocalWorldMatrix = this._localWorld.clone();
  17992. invLocalWorldMatrix.invert();
  17993. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  17994. };
  17995. /**
  17996. * Translates the mesh along the passed Vector3 in its local space.
  17997. * Returns the TransformNode.
  17998. */
  17999. TransformNode.prototype.locallyTranslate = function (vector3) {
  18000. this.computeWorldMatrix(true);
  18001. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18002. return this;
  18003. };
  18004. /**
  18005. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18006. * @param targetPoint the position (must be in same space as current mesh) to look at
  18007. * @param yawCor optional yaw (y-axis) correction in radians
  18008. * @param pitchCor optional pitch (x-axis) correction in radians
  18009. * @param rollCor optional roll (z-axis) correction in radians
  18010. * @param space the choosen space of the target
  18011. * @returns the TransformNode.
  18012. */
  18013. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18014. if (yawCor === void 0) { yawCor = 0; }
  18015. if (pitchCor === void 0) { pitchCor = 0; }
  18016. if (rollCor === void 0) { rollCor = 0; }
  18017. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18018. var dv = TransformNode._lookAtVectorCache;
  18019. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18020. targetPoint.subtractToRef(pos, dv);
  18021. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18022. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18023. var pitch = Math.atan2(dv.y, len);
  18024. if (this.rotationQuaternion) {
  18025. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18026. }
  18027. else {
  18028. this.rotation.x = pitch + pitchCor;
  18029. this.rotation.y = yaw + yawCor;
  18030. this.rotation.z = rollCor;
  18031. }
  18032. return this;
  18033. };
  18034. /**
  18035. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18036. * This Vector3 is expressed in the World space.
  18037. */
  18038. TransformNode.prototype.getDirection = function (localAxis) {
  18039. var result = BABYLON.Vector3.Zero();
  18040. this.getDirectionToRef(localAxis, result);
  18041. return result;
  18042. };
  18043. /**
  18044. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18045. * localAxis is expressed in the mesh local space.
  18046. * result is computed in the Wordl space from the mesh World matrix.
  18047. * Returns the TransformNode.
  18048. */
  18049. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18050. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18051. return this;
  18052. };
  18053. /**
  18054. * Sets a new pivot point to the current node
  18055. * @param point defines the new pivot point to use
  18056. * @param space defines if the point is in world or local space (local by default)
  18057. * @returns the current TransformNode
  18058. */
  18059. TransformNode.prototype.setPivotPoint = function (point, space) {
  18060. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18061. if (this.getScene().getRenderId() == 0) {
  18062. this.computeWorldMatrix(true);
  18063. }
  18064. var wm = this.getWorldMatrix();
  18065. if (space == BABYLON.Space.WORLD) {
  18066. var tmat = BABYLON.Tmp.Matrix[0];
  18067. wm.invertToRef(tmat);
  18068. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18069. }
  18070. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18071. };
  18072. /**
  18073. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18074. */
  18075. TransformNode.prototype.getPivotPoint = function () {
  18076. var point = BABYLON.Vector3.Zero();
  18077. this.getPivotPointToRef(point);
  18078. return point;
  18079. };
  18080. /**
  18081. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18082. * Returns the TransformNode.
  18083. */
  18084. TransformNode.prototype.getPivotPointToRef = function (result) {
  18085. result.x = -this._pivotMatrix.m[12];
  18086. result.y = -this._pivotMatrix.m[13];
  18087. result.z = -this._pivotMatrix.m[14];
  18088. return this;
  18089. };
  18090. /**
  18091. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18092. */
  18093. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18094. var point = BABYLON.Vector3.Zero();
  18095. this.getAbsolutePivotPointToRef(point);
  18096. return point;
  18097. };
  18098. /**
  18099. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18100. * Returns the TransformNode.
  18101. */
  18102. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18103. result.x = this._pivotMatrix.m[12];
  18104. result.y = this._pivotMatrix.m[13];
  18105. result.z = this._pivotMatrix.m[14];
  18106. this.getPivotPointToRef(result);
  18107. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18108. return this;
  18109. };
  18110. /**
  18111. * Defines the passed node as the parent of the current node.
  18112. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18113. * Returns the TransformNode.
  18114. */
  18115. TransformNode.prototype.setParent = function (node) {
  18116. if (node === null) {
  18117. var rotation = BABYLON.Tmp.Quaternion[0];
  18118. var position = BABYLON.Tmp.Vector3[0];
  18119. var scale = BABYLON.Tmp.Vector3[1];
  18120. if (this.parent && this.parent.computeWorldMatrix) {
  18121. this.parent.computeWorldMatrix(true);
  18122. }
  18123. this.computeWorldMatrix(true);
  18124. this.getWorldMatrix().decompose(scale, rotation, position);
  18125. if (this.rotationQuaternion) {
  18126. this.rotationQuaternion.copyFrom(rotation);
  18127. }
  18128. else {
  18129. rotation.toEulerAnglesToRef(this.rotation);
  18130. }
  18131. this.scaling.x = scale.x;
  18132. this.scaling.y = scale.y;
  18133. this.scaling.z = scale.z;
  18134. this.position.x = position.x;
  18135. this.position.y = position.y;
  18136. this.position.z = position.z;
  18137. }
  18138. else {
  18139. var rotation = BABYLON.Tmp.Quaternion[0];
  18140. var position = BABYLON.Tmp.Vector3[0];
  18141. var scale = BABYLON.Tmp.Vector3[1];
  18142. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18143. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18144. this.computeWorldMatrix(true);
  18145. node.computeWorldMatrix(true);
  18146. node.getWorldMatrix().invertToRef(invParentMatrix);
  18147. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18148. diffMatrix.decompose(scale, rotation, position);
  18149. if (this.rotationQuaternion) {
  18150. this.rotationQuaternion.copyFrom(rotation);
  18151. }
  18152. else {
  18153. rotation.toEulerAnglesToRef(this.rotation);
  18154. }
  18155. this.position.x = position.x;
  18156. this.position.y = position.y;
  18157. this.position.z = position.z;
  18158. this.scaling.x = scale.x;
  18159. this.scaling.y = scale.y;
  18160. this.scaling.z = scale.z;
  18161. }
  18162. this.parent = node;
  18163. return this;
  18164. };
  18165. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18166. get: function () {
  18167. return this._nonUniformScaling;
  18168. },
  18169. enumerable: true,
  18170. configurable: true
  18171. });
  18172. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18173. if (this._nonUniformScaling === value) {
  18174. return false;
  18175. }
  18176. this._nonUniformScaling = true;
  18177. return true;
  18178. };
  18179. /**
  18180. * Attach the current TransformNode to another TransformNode associated with a bone
  18181. * @param bone Bone affecting the TransformNode
  18182. * @param affectedTransformNode TransformNode associated with the bone
  18183. */
  18184. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18185. this._transformToBoneReferal = affectedTransformNode;
  18186. this.parent = bone;
  18187. if (bone.getWorldMatrix().determinant() < 0) {
  18188. this.scalingDeterminant *= -1;
  18189. }
  18190. return this;
  18191. };
  18192. TransformNode.prototype.detachFromBone = function () {
  18193. if (!this.parent) {
  18194. return this;
  18195. }
  18196. if (this.parent.getWorldMatrix().determinant() < 0) {
  18197. this.scalingDeterminant *= -1;
  18198. }
  18199. this._transformToBoneReferal = null;
  18200. this.parent = null;
  18201. return this;
  18202. };
  18203. /**
  18204. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18205. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18206. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18207. * The passed axis is also normalized.
  18208. * Returns the TransformNode.
  18209. */
  18210. TransformNode.prototype.rotate = function (axis, amount, space) {
  18211. axis.normalize();
  18212. if (!this.rotationQuaternion) {
  18213. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18214. this.rotation = BABYLON.Vector3.Zero();
  18215. }
  18216. var rotationQuaternion;
  18217. if (!space || space === BABYLON.Space.LOCAL) {
  18218. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18219. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18220. }
  18221. else {
  18222. if (this.parent) {
  18223. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18224. invertParentWorldMatrix.invert();
  18225. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18226. }
  18227. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18228. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18229. }
  18230. return this;
  18231. };
  18232. /**
  18233. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18234. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18235. * The passed axis is also normalized.
  18236. * Returns the TransformNode.
  18237. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18238. */
  18239. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18240. axis.normalize();
  18241. if (!this.rotationQuaternion) {
  18242. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18243. this.rotation.copyFromFloats(0, 0, 0);
  18244. }
  18245. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18246. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18247. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18248. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18249. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18250. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18251. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18252. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18253. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18254. return this;
  18255. };
  18256. /**
  18257. * Translates the mesh along the axis vector for the passed distance in the given space.
  18258. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18259. * Returns the TransformNode.
  18260. */
  18261. TransformNode.prototype.translate = function (axis, distance, space) {
  18262. var displacementVector = axis.scale(distance);
  18263. if (!space || space === BABYLON.Space.LOCAL) {
  18264. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18265. this.setPositionWithLocalVector(tempV3);
  18266. }
  18267. else {
  18268. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18269. }
  18270. return this;
  18271. };
  18272. /**
  18273. * Adds a rotation step to the mesh current rotation.
  18274. * x, y, z are Euler angles expressed in radians.
  18275. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18276. * This means this rotation is made in the mesh local space only.
  18277. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18278. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18279. * ```javascript
  18280. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18281. * ```
  18282. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18283. * 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.
  18284. * Returns the TransformNode.
  18285. */
  18286. TransformNode.prototype.addRotation = function (x, y, z) {
  18287. var rotationQuaternion;
  18288. if (this.rotationQuaternion) {
  18289. rotationQuaternion = this.rotationQuaternion;
  18290. }
  18291. else {
  18292. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18293. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18294. }
  18295. var accumulation = BABYLON.Tmp.Quaternion[0];
  18296. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18297. rotationQuaternion.multiplyInPlace(accumulation);
  18298. if (!this.rotationQuaternion) {
  18299. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18300. }
  18301. return this;
  18302. };
  18303. /**
  18304. * Computes the mesh World matrix and returns it.
  18305. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18306. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18307. * If the parameter `force`is set to `true`, the actual computation is done.
  18308. * Returns the mesh World Matrix.
  18309. */
  18310. TransformNode.prototype.computeWorldMatrix = function (force) {
  18311. if (this._isWorldMatrixFrozen) {
  18312. return this._worldMatrix;
  18313. }
  18314. if (!force && this.isSynchronized(true)) {
  18315. this._currentRenderId = this.getScene().getRenderId();
  18316. return this._worldMatrix;
  18317. }
  18318. this._cache.position.copyFrom(this.position);
  18319. this._cache.scaling.copyFrom(this.scaling);
  18320. this._cache.pivotMatrixUpdated = false;
  18321. this._cache.billboardMode = this.billboardMode;
  18322. this._currentRenderId = this.getScene().getRenderId();
  18323. this._childRenderId = this.getScene().getRenderId();
  18324. this._isDirty = false;
  18325. // Scaling
  18326. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18327. // Rotation
  18328. //rotate, if quaternion is set and rotation was used
  18329. if (this.rotationQuaternion) {
  18330. var len = this.rotation.length();
  18331. if (len) {
  18332. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18333. this.rotation.copyFromFloats(0, 0, 0);
  18334. }
  18335. }
  18336. if (this.rotationQuaternion) {
  18337. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18338. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18339. }
  18340. else {
  18341. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18342. this._cache.rotation.copyFrom(this.rotation);
  18343. }
  18344. // Translation
  18345. var camera = this.getScene().activeCamera;
  18346. if (this.infiniteDistance && !this.parent && camera) {
  18347. var cameraWorldMatrix = camera.getWorldMatrix();
  18348. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18349. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18350. }
  18351. else {
  18352. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18353. }
  18354. // Composing transformations
  18355. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18356. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18357. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18358. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18359. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18360. // Need to decompose each rotation here
  18361. var currentPosition = BABYLON.Tmp.Vector3[3];
  18362. if (this.parent && this.parent.getWorldMatrix) {
  18363. if (this._transformToBoneReferal) {
  18364. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18365. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18366. }
  18367. else {
  18368. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18369. }
  18370. }
  18371. else {
  18372. currentPosition.copyFrom(this.position);
  18373. }
  18374. currentPosition.subtractInPlace(camera.globalPosition);
  18375. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18376. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18377. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18378. }
  18379. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18380. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18381. }
  18382. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18383. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18384. }
  18385. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18386. }
  18387. else {
  18388. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18389. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18390. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18391. }
  18392. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18393. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18394. }
  18395. // Local world
  18396. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18397. // Parent
  18398. if (this.parent && this.parent.getWorldMatrix) {
  18399. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18400. if (this._transformToBoneReferal) {
  18401. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18402. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18403. }
  18404. else {
  18405. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18406. }
  18407. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18408. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18409. this._worldMatrix.copyFrom(this._localWorld);
  18410. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18411. }
  18412. else {
  18413. if (this._transformToBoneReferal) {
  18414. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18415. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18416. }
  18417. else {
  18418. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18419. }
  18420. }
  18421. this._markSyncedWithParent();
  18422. }
  18423. else {
  18424. this._worldMatrix.copyFrom(this._localWorld);
  18425. }
  18426. // Post multiply inverse of pivotMatrix
  18427. if (this._postMultiplyPivotMatrix) {
  18428. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18429. }
  18430. // Normal matrix
  18431. if (this.scaling.isNonUniform) {
  18432. this._updateNonUniformScalingState(true);
  18433. }
  18434. else if (this.parent && this.parent._nonUniformScaling) {
  18435. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18436. }
  18437. else {
  18438. this._updateNonUniformScalingState(false);
  18439. }
  18440. this._afterComputeWorldMatrix();
  18441. // Absolute position
  18442. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18443. // Callbacks
  18444. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18445. if (!this._poseMatrix) {
  18446. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18447. }
  18448. // Cache the determinant
  18449. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18450. return this._worldMatrix;
  18451. };
  18452. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18453. };
  18454. /**
  18455. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18456. * @param func: callback function to add
  18457. *
  18458. * Returns the TransformNode.
  18459. */
  18460. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18461. this.onAfterWorldMatrixUpdateObservable.add(func);
  18462. return this;
  18463. };
  18464. /**
  18465. * Removes a registered callback function.
  18466. * Returns the TransformNode.
  18467. */
  18468. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18469. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18470. return this;
  18471. };
  18472. /**
  18473. * Clone the current transform node
  18474. * Returns the new transform node
  18475. * @param name Name of the new clone
  18476. * @param newParent New parent for the clone
  18477. * @param doNotCloneChildren Do not clone children hierarchy
  18478. */
  18479. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18480. var _this = this;
  18481. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18482. result.name = name;
  18483. result.id = name;
  18484. if (newParent) {
  18485. result.parent = newParent;
  18486. }
  18487. if (!doNotCloneChildren) {
  18488. // Children
  18489. var directDescendants = this.getDescendants(true);
  18490. for (var index = 0; index < directDescendants.length; index++) {
  18491. var child = directDescendants[index];
  18492. if (child.clone) {
  18493. child.clone(name + "." + child.name, result);
  18494. }
  18495. }
  18496. }
  18497. return result;
  18498. };
  18499. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18500. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18501. serializationObject.type = this.getClassName();
  18502. // Parent
  18503. if (this.parent) {
  18504. serializationObject.parentId = this.parent.id;
  18505. }
  18506. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18507. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18508. }
  18509. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18510. serializationObject.isEnabled = this.isEnabled();
  18511. // Parent
  18512. if (this.parent) {
  18513. serializationObject.parentId = this.parent.id;
  18514. }
  18515. return serializationObject;
  18516. };
  18517. // Statics
  18518. /**
  18519. * Returns a new TransformNode object parsed from the source provided.
  18520. * The parameter `parsedMesh` is the source.
  18521. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18522. */
  18523. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18524. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18525. if (BABYLON.Tags) {
  18526. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18527. }
  18528. if (parsedTransformNode.localMatrix) {
  18529. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18530. }
  18531. else if (parsedTransformNode.pivotMatrix) {
  18532. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18533. }
  18534. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18535. // Parent
  18536. if (parsedTransformNode.parentId) {
  18537. transformNode._waitingParentId = parsedTransformNode.parentId;
  18538. }
  18539. return transformNode;
  18540. };
  18541. /**
  18542. * Releases resources associated with this transform node.
  18543. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18544. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18545. */
  18546. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18547. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18548. // Animations
  18549. this.getScene().stopAnimation(this);
  18550. // Remove from scene
  18551. this.getScene().removeTransformNode(this);
  18552. this.onAfterWorldMatrixUpdateObservable.clear();
  18553. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18554. };
  18555. // Statics
  18556. TransformNode.BILLBOARDMODE_NONE = 0;
  18557. TransformNode.BILLBOARDMODE_X = 1;
  18558. TransformNode.BILLBOARDMODE_Y = 2;
  18559. TransformNode.BILLBOARDMODE_Z = 4;
  18560. TransformNode.BILLBOARDMODE_ALL = 7;
  18561. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18562. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  18563. __decorate([
  18564. BABYLON.serializeAsVector3()
  18565. ], TransformNode.prototype, "_rotation", void 0);
  18566. __decorate([
  18567. BABYLON.serializeAsQuaternion()
  18568. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  18569. __decorate([
  18570. BABYLON.serializeAsVector3()
  18571. ], TransformNode.prototype, "_scaling", void 0);
  18572. __decorate([
  18573. BABYLON.serialize()
  18574. ], TransformNode.prototype, "billboardMode", void 0);
  18575. __decorate([
  18576. BABYLON.serialize()
  18577. ], TransformNode.prototype, "scalingDeterminant", void 0);
  18578. __decorate([
  18579. BABYLON.serialize()
  18580. ], TransformNode.prototype, "infiniteDistance", void 0);
  18581. __decorate([
  18582. BABYLON.serializeAsVector3()
  18583. ], TransformNode.prototype, "position", void 0);
  18584. return TransformNode;
  18585. }(BABYLON.Node));
  18586. BABYLON.TransformNode = TransformNode;
  18587. })(BABYLON || (BABYLON = {}));
  18588. //# sourceMappingURL=babylon.transformNode.js.map
  18589. "use strict";
  18590. var BABYLON;
  18591. (function (BABYLON) {
  18592. var AbstractMesh = /** @class */ (function (_super) {
  18593. __extends(AbstractMesh, _super);
  18594. // Constructor
  18595. function AbstractMesh(name, scene) {
  18596. if (scene === void 0) { scene = null; }
  18597. var _this = _super.call(this, name, scene, false) || this;
  18598. _this._facetNb = 0; // facet number
  18599. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  18600. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  18601. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  18602. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  18603. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  18604. _this._subDiv = {
  18605. max: 1,
  18606. X: 1,
  18607. Y: 1,
  18608. Z: 1
  18609. };
  18610. _this._facetDepthSort = false; // is the facet depth sort to be computed
  18611. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  18612. // Events
  18613. /**
  18614. * An event triggered when this mesh collides with another one
  18615. */
  18616. _this.onCollideObservable = new BABYLON.Observable();
  18617. /**
  18618. * An event triggered when the collision's position changes
  18619. */
  18620. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  18621. /**
  18622. * An event triggered when material is changed
  18623. */
  18624. _this.onMaterialChangedObservable = new BABYLON.Observable();
  18625. // Properties
  18626. _this.definedFacingForward = true; // orientation for POV movement & rotation
  18627. /**
  18628. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  18629. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  18630. * or
  18631. * 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.
  18632. * for more info check WebGl documentations
  18633. */
  18634. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  18635. /**
  18636. * 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:
  18637. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  18638. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  18639. * 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.
  18640. */
  18641. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  18642. /**
  18643. * 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.
  18644. * The default value is -1 which means don't break the query and wait till the result.
  18645. */
  18646. _this.occlusionRetryCount = -1;
  18647. _this._occlusionInternalRetryCounter = 0;
  18648. _this._isOccluded = false;
  18649. _this._isOcclusionQueryInProgress = false;
  18650. _this._visibility = 1.0;
  18651. _this.alphaIndex = Number.MAX_VALUE;
  18652. _this.isVisible = true;
  18653. _this.isPickable = true;
  18654. _this.showBoundingBox = false;
  18655. _this.showSubMeshesBoundingBox = false;
  18656. _this.isBlocker = false;
  18657. _this.enablePointerMoveEvents = false;
  18658. _this.renderingGroupId = 0;
  18659. _this._receiveShadows = false;
  18660. _this.renderOutline = false;
  18661. _this.outlineColor = BABYLON.Color3.Red();
  18662. _this.outlineWidth = 0.02;
  18663. _this.renderOverlay = false;
  18664. _this.overlayColor = BABYLON.Color3.Red();
  18665. _this.overlayAlpha = 0.5;
  18666. _this._hasVertexAlpha = false;
  18667. _this._useVertexColors = true;
  18668. _this._computeBonesUsingShaders = true;
  18669. _this._numBoneInfluencers = 4;
  18670. _this._applyFog = true;
  18671. _this.useOctreeForRenderingSelection = true;
  18672. _this.useOctreeForPicking = true;
  18673. _this.useOctreeForCollisions = true;
  18674. _this._layerMask = 0x0FFFFFFF;
  18675. /**
  18676. * True if the mesh must be rendered in any case.
  18677. */
  18678. _this.alwaysSelectAsActiveMesh = false;
  18679. /**
  18680. * This scene's action manager
  18681. */
  18682. _this.actionManager = null;
  18683. // Physics
  18684. _this.physicsImpostor = null;
  18685. // Collisions
  18686. _this._checkCollisions = false;
  18687. _this._collisionMask = -1;
  18688. _this._collisionGroup = -1;
  18689. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  18690. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  18691. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18692. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18693. // Edges
  18694. _this.edgesWidth = 1;
  18695. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  18696. // Cache
  18697. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  18698. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  18699. _this._renderId = 0;
  18700. _this._intersectionsInProgress = new Array();
  18701. _this._unIndexed = false;
  18702. _this._lightSources = new Array();
  18703. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18704. if (collidedMesh === void 0) { collidedMesh = null; }
  18705. //TODO move this to the collision coordinator!
  18706. if (_this.getScene().workerCollisions)
  18707. newPosition.multiplyInPlace(_this._collider._radius);
  18708. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  18709. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  18710. _this.position.addInPlace(_this._diffPositionForCollisions);
  18711. }
  18712. if (collidedMesh) {
  18713. _this.onCollideObservable.notifyObservers(collidedMesh);
  18714. }
  18715. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  18716. };
  18717. _this.getScene().addMesh(_this);
  18718. _this._resyncLightSources();
  18719. return _this;
  18720. }
  18721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  18722. get: function () {
  18723. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  18724. },
  18725. enumerable: true,
  18726. configurable: true
  18727. });
  18728. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  18729. get: function () {
  18730. return BABYLON.TransformNode.BILLBOARDMODE_X;
  18731. },
  18732. enumerable: true,
  18733. configurable: true
  18734. });
  18735. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  18736. get: function () {
  18737. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  18738. },
  18739. enumerable: true,
  18740. configurable: true
  18741. });
  18742. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  18743. get: function () {
  18744. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  18745. },
  18746. enumerable: true,
  18747. configurable: true
  18748. });
  18749. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  18750. get: function () {
  18751. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  18752. },
  18753. enumerable: true,
  18754. configurable: true
  18755. });
  18756. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  18757. /**
  18758. * Read-only : the number of facets in the mesh
  18759. */
  18760. get: function () {
  18761. return this._facetNb;
  18762. },
  18763. enumerable: true,
  18764. configurable: true
  18765. });
  18766. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  18767. /**
  18768. * The number (integer) of subdivisions per axis in the partioning space
  18769. */
  18770. get: function () {
  18771. return this._partitioningSubdivisions;
  18772. },
  18773. set: function (nb) {
  18774. this._partitioningSubdivisions = nb;
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  18780. /**
  18781. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  18782. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  18783. */
  18784. get: function () {
  18785. return this._partitioningBBoxRatio;
  18786. },
  18787. set: function (ratio) {
  18788. this._partitioningBBoxRatio = ratio;
  18789. },
  18790. enumerable: true,
  18791. configurable: true
  18792. });
  18793. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  18794. /**
  18795. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  18796. * Works only for updatable meshes.
  18797. * Doesn't work with multi-materials.
  18798. */
  18799. get: function () {
  18800. return this._facetDepthSort;
  18801. },
  18802. set: function (sort) {
  18803. this._facetDepthSort = sort;
  18804. },
  18805. enumerable: true,
  18806. configurable: true
  18807. });
  18808. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  18809. /**
  18810. * The location (Vector3) where the facet depth sort must be computed from.
  18811. * By default, the active camera position.
  18812. * Used only when facet depth sort is enabled.
  18813. */
  18814. get: function () {
  18815. return this._facetDepthSortFrom;
  18816. },
  18817. set: function (location) {
  18818. this._facetDepthSortFrom = location;
  18819. },
  18820. enumerable: true,
  18821. configurable: true
  18822. });
  18823. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  18824. /**
  18825. * Read-only boolean : is the feature facetData enabled ?
  18826. */
  18827. get: function () {
  18828. return this._facetDataEnabled;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  18834. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  18835. return false;
  18836. }
  18837. this._markSubMeshesAsMiscDirty();
  18838. return true;
  18839. };
  18840. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  18841. set: function (callback) {
  18842. if (this._onCollideObserver) {
  18843. this.onCollideObservable.remove(this._onCollideObserver);
  18844. }
  18845. this._onCollideObserver = this.onCollideObservable.add(callback);
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  18851. set: function (callback) {
  18852. if (this._onCollisionPositionChangeObserver) {
  18853. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  18854. }
  18855. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  18861. /**
  18862. * 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.
  18863. */
  18864. get: function () {
  18865. return this._isOccluded;
  18866. },
  18867. set: function (value) {
  18868. this._isOccluded = value;
  18869. },
  18870. enumerable: true,
  18871. configurable: true
  18872. });
  18873. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  18874. /**
  18875. * Flag to check the progress status of the query
  18876. */
  18877. get: function () {
  18878. return this._isOcclusionQueryInProgress;
  18879. },
  18880. enumerable: true,
  18881. configurable: true
  18882. });
  18883. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  18884. /**
  18885. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  18886. */
  18887. get: function () {
  18888. return this._visibility;
  18889. },
  18890. /**
  18891. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  18892. */
  18893. set: function (value) {
  18894. if (this._visibility === value) {
  18895. return;
  18896. }
  18897. this._visibility = value;
  18898. this._markSubMeshesAsMiscDirty();
  18899. },
  18900. enumerable: true,
  18901. configurable: true
  18902. });
  18903. Object.defineProperty(AbstractMesh.prototype, "material", {
  18904. get: function () {
  18905. return this._material;
  18906. },
  18907. set: function (value) {
  18908. if (this._material === value) {
  18909. return;
  18910. }
  18911. this._material = value;
  18912. if (this.onMaterialChangedObservable.hasObservers) {
  18913. this.onMaterialChangedObservable.notifyObservers(this);
  18914. }
  18915. if (!this.subMeshes) {
  18916. return;
  18917. }
  18918. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18919. var subMesh = _a[_i];
  18920. subMesh.setEffect(null);
  18921. }
  18922. },
  18923. enumerable: true,
  18924. configurable: true
  18925. });
  18926. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  18927. get: function () {
  18928. return this._receiveShadows;
  18929. },
  18930. set: function (value) {
  18931. if (this._receiveShadows === value) {
  18932. return;
  18933. }
  18934. this._receiveShadows = value;
  18935. this._markSubMeshesAsLightDirty();
  18936. },
  18937. enumerable: true,
  18938. configurable: true
  18939. });
  18940. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  18941. get: function () {
  18942. return this._hasVertexAlpha;
  18943. },
  18944. set: function (value) {
  18945. if (this._hasVertexAlpha === value) {
  18946. return;
  18947. }
  18948. this._hasVertexAlpha = value;
  18949. this._markSubMeshesAsAttributesDirty();
  18950. this._markSubMeshesAsMiscDirty();
  18951. },
  18952. enumerable: true,
  18953. configurable: true
  18954. });
  18955. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  18956. get: function () {
  18957. return this._useVertexColors;
  18958. },
  18959. set: function (value) {
  18960. if (this._useVertexColors === value) {
  18961. return;
  18962. }
  18963. this._useVertexColors = value;
  18964. this._markSubMeshesAsAttributesDirty();
  18965. },
  18966. enumerable: true,
  18967. configurable: true
  18968. });
  18969. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  18970. get: function () {
  18971. return this._computeBonesUsingShaders;
  18972. },
  18973. set: function (value) {
  18974. if (this._computeBonesUsingShaders === value) {
  18975. return;
  18976. }
  18977. this._computeBonesUsingShaders = value;
  18978. this._markSubMeshesAsAttributesDirty();
  18979. },
  18980. enumerable: true,
  18981. configurable: true
  18982. });
  18983. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  18984. get: function () {
  18985. return this._numBoneInfluencers;
  18986. },
  18987. set: function (value) {
  18988. if (this._numBoneInfluencers === value) {
  18989. return;
  18990. }
  18991. this._numBoneInfluencers = value;
  18992. this._markSubMeshesAsAttributesDirty();
  18993. },
  18994. enumerable: true,
  18995. configurable: true
  18996. });
  18997. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  18998. get: function () {
  18999. return this._applyFog;
  19000. },
  19001. set: function (value) {
  19002. if (this._applyFog === value) {
  19003. return;
  19004. }
  19005. this._applyFog = value;
  19006. this._markSubMeshesAsMiscDirty();
  19007. },
  19008. enumerable: true,
  19009. configurable: true
  19010. });
  19011. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19012. get: function () {
  19013. return this._layerMask;
  19014. },
  19015. set: function (value) {
  19016. if (value === this._layerMask) {
  19017. return;
  19018. }
  19019. this._layerMask = value;
  19020. this._resyncLightSources();
  19021. },
  19022. enumerable: true,
  19023. configurable: true
  19024. });
  19025. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19026. get: function () {
  19027. return this._collisionMask;
  19028. },
  19029. set: function (mask) {
  19030. this._collisionMask = !isNaN(mask) ? mask : -1;
  19031. },
  19032. enumerable: true,
  19033. configurable: true
  19034. });
  19035. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19036. get: function () {
  19037. return this._collisionGroup;
  19038. },
  19039. set: function (mask) {
  19040. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19041. },
  19042. enumerable: true,
  19043. configurable: true
  19044. });
  19045. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19046. get: function () {
  19047. return null;
  19048. },
  19049. enumerable: true,
  19050. configurable: true
  19051. });
  19052. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19053. get: function () {
  19054. return this._skeleton;
  19055. },
  19056. set: function (value) {
  19057. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19058. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19059. }
  19060. if (value && value.needInitialSkinMatrix) {
  19061. value._registerMeshWithPoseMatrix(this);
  19062. }
  19063. this._skeleton = value;
  19064. if (!this._skeleton) {
  19065. this._bonesTransformMatrices = null;
  19066. }
  19067. this._markSubMeshesAsAttributesDirty();
  19068. },
  19069. enumerable: true,
  19070. configurable: true
  19071. });
  19072. /**
  19073. * Returns the string "AbstractMesh"
  19074. */
  19075. AbstractMesh.prototype.getClassName = function () {
  19076. return "AbstractMesh";
  19077. };
  19078. /**
  19079. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19080. */
  19081. AbstractMesh.prototype.toString = function (fullDetails) {
  19082. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19083. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19084. if (this._skeleton) {
  19085. ret += ", skeleton: " + this._skeleton.name;
  19086. }
  19087. if (fullDetails) {
  19088. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19089. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19090. }
  19091. return ret;
  19092. };
  19093. AbstractMesh.prototype._rebuild = function () {
  19094. if (this._occlusionQuery) {
  19095. this._occlusionQuery = null;
  19096. }
  19097. if (this._edgesRenderer) {
  19098. this._edgesRenderer._rebuild();
  19099. }
  19100. if (!this.subMeshes) {
  19101. return;
  19102. }
  19103. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19104. var subMesh = _a[_i];
  19105. subMesh._rebuild();
  19106. }
  19107. };
  19108. AbstractMesh.prototype._resyncLightSources = function () {
  19109. this._lightSources.length = 0;
  19110. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19111. var light = _a[_i];
  19112. if (!light.isEnabled()) {
  19113. continue;
  19114. }
  19115. if (light.canAffectMesh(this)) {
  19116. this._lightSources.push(light);
  19117. }
  19118. }
  19119. this._markSubMeshesAsLightDirty();
  19120. };
  19121. AbstractMesh.prototype._resyncLighSource = function (light) {
  19122. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19123. var index = this._lightSources.indexOf(light);
  19124. if (index === -1) {
  19125. if (!isIn) {
  19126. return;
  19127. }
  19128. this._lightSources.push(light);
  19129. }
  19130. else {
  19131. if (isIn) {
  19132. return;
  19133. }
  19134. this._lightSources.splice(index, 1);
  19135. }
  19136. this._markSubMeshesAsLightDirty();
  19137. };
  19138. AbstractMesh.prototype._removeLightSource = function (light) {
  19139. var index = this._lightSources.indexOf(light);
  19140. if (index === -1) {
  19141. return;
  19142. }
  19143. this._lightSources.splice(index, 1);
  19144. this._markSubMeshesAsLightDirty();
  19145. };
  19146. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19147. if (!this.subMeshes) {
  19148. return;
  19149. }
  19150. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19151. var subMesh = _a[_i];
  19152. if (subMesh._materialDefines) {
  19153. func(subMesh._materialDefines);
  19154. }
  19155. }
  19156. };
  19157. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19158. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19159. };
  19160. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19161. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19162. };
  19163. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19164. if (!this.subMeshes) {
  19165. return;
  19166. }
  19167. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19168. var subMesh = _a[_i];
  19169. var material = subMesh.getMaterial();
  19170. if (material) {
  19171. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19172. }
  19173. }
  19174. };
  19175. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19176. /**
  19177. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19178. * Default : (1.0, 1.0, 1.0)
  19179. */
  19180. get: function () {
  19181. return this._scaling;
  19182. },
  19183. /**
  19184. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19185. * Default : (1.0, 1.0, 1.0)
  19186. */
  19187. set: function (newScaling) {
  19188. this._scaling = newScaling;
  19189. if (this.physicsImpostor) {
  19190. this.physicsImpostor.forceUpdate();
  19191. }
  19192. },
  19193. enumerable: true,
  19194. configurable: true
  19195. });
  19196. // Methods
  19197. /**
  19198. * Disables the mesh edger rendering mode.
  19199. * Returns the AbstractMesh.
  19200. */
  19201. AbstractMesh.prototype.disableEdgesRendering = function () {
  19202. if (this._edgesRenderer) {
  19203. this._edgesRenderer.dispose();
  19204. this._edgesRenderer = null;
  19205. }
  19206. return this;
  19207. };
  19208. /**
  19209. * Enables the edge rendering mode on the mesh.
  19210. * This mode makes the mesh edges visible.
  19211. * Returns the AbstractMesh.
  19212. */
  19213. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19214. if (epsilon === void 0) { epsilon = 0.95; }
  19215. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19216. this.disableEdgesRendering();
  19217. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19218. return this;
  19219. };
  19220. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19221. /**
  19222. * Returns true if the mesh is blocked. Used by the class Mesh.
  19223. * Returns the boolean `false` by default.
  19224. */
  19225. get: function () {
  19226. return false;
  19227. },
  19228. enumerable: true,
  19229. configurable: true
  19230. });
  19231. /**
  19232. * Returns the mesh itself by default, used by the class Mesh.
  19233. * Returned type : AbstractMesh
  19234. */
  19235. AbstractMesh.prototype.getLOD = function (camera) {
  19236. return this;
  19237. };
  19238. /**
  19239. * Returns 0 by default, used by the class Mesh.
  19240. * Returns an integer.
  19241. */
  19242. AbstractMesh.prototype.getTotalVertices = function () {
  19243. return 0;
  19244. };
  19245. /**
  19246. * Returns null by default, used by the class Mesh.
  19247. * Returned type : integer array
  19248. */
  19249. AbstractMesh.prototype.getIndices = function () {
  19250. return null;
  19251. };
  19252. /**
  19253. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19254. * Returned type : float array or Float32Array
  19255. */
  19256. AbstractMesh.prototype.getVerticesData = function (kind) {
  19257. return null;
  19258. };
  19259. /**
  19260. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19261. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19262. * The `data` are either a numeric array either a Float32Array.
  19263. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19264. * 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).
  19265. * Note that a new underlying VertexBuffer object is created each call.
  19266. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19267. *
  19268. * Possible `kind` values :
  19269. * - BABYLON.VertexBuffer.PositionKind
  19270. * - BABYLON.VertexBuffer.UVKind
  19271. * - BABYLON.VertexBuffer.UV2Kind
  19272. * - BABYLON.VertexBuffer.UV3Kind
  19273. * - BABYLON.VertexBuffer.UV4Kind
  19274. * - BABYLON.VertexBuffer.UV5Kind
  19275. * - BABYLON.VertexBuffer.UV6Kind
  19276. * - BABYLON.VertexBuffer.ColorKind
  19277. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19278. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19279. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19280. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19281. *
  19282. * Returns the Mesh.
  19283. */
  19284. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19285. return this;
  19286. };
  19287. /**
  19288. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19289. * If the mesh has no geometry, it is simply returned as it is.
  19290. * The `data` are either a numeric array either a Float32Array.
  19291. * No new underlying VertexBuffer object is created.
  19292. * 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.
  19293. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19294. *
  19295. * Possible `kind` values :
  19296. * - BABYLON.VertexBuffer.PositionKind
  19297. * - BABYLON.VertexBuffer.UVKind
  19298. * - BABYLON.VertexBuffer.UV2Kind
  19299. * - BABYLON.VertexBuffer.UV3Kind
  19300. * - BABYLON.VertexBuffer.UV4Kind
  19301. * - BABYLON.VertexBuffer.UV5Kind
  19302. * - BABYLON.VertexBuffer.UV6Kind
  19303. * - BABYLON.VertexBuffer.ColorKind
  19304. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19305. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19306. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19307. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19308. *
  19309. * Returns the Mesh.
  19310. */
  19311. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19312. return this;
  19313. };
  19314. /**
  19315. * Sets the mesh indices.
  19316. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19317. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19318. * This method creates a new index buffer each call.
  19319. * Returns the Mesh.
  19320. */
  19321. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19322. return this;
  19323. };
  19324. /** Returns false by default, used by the class Mesh.
  19325. * Returns a boolean
  19326. */
  19327. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19328. return false;
  19329. };
  19330. /**
  19331. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19332. * Returns a BoundingInfo
  19333. */
  19334. AbstractMesh.prototype.getBoundingInfo = function () {
  19335. if (this._masterMesh) {
  19336. return this._masterMesh.getBoundingInfo();
  19337. }
  19338. if (!this._boundingInfo) {
  19339. // this._boundingInfo is being created here
  19340. this._updateBoundingInfo();
  19341. }
  19342. // cannot be null.
  19343. return this._boundingInfo;
  19344. };
  19345. /**
  19346. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19347. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19348. */
  19349. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19350. if (includeDescendants === void 0) { includeDescendants = true; }
  19351. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19352. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19353. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19354. if (maxDimension === 0) {
  19355. return this;
  19356. }
  19357. var scale = 1 / maxDimension;
  19358. this.scaling.scaleInPlace(scale);
  19359. return this;
  19360. };
  19361. /**
  19362. * Sets a mesh new object BoundingInfo.
  19363. * Returns the AbstractMesh.
  19364. */
  19365. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19366. this._boundingInfo = boundingInfo;
  19367. return this;
  19368. };
  19369. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19370. get: function () {
  19371. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19372. },
  19373. enumerable: true,
  19374. configurable: true
  19375. });
  19376. AbstractMesh.prototype._preActivate = function () {
  19377. };
  19378. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19379. };
  19380. AbstractMesh.prototype._activate = function (renderId) {
  19381. this._renderId = renderId;
  19382. };
  19383. /**
  19384. * Returns the latest update of the World matrix
  19385. * Returns a Matrix.
  19386. */
  19387. AbstractMesh.prototype.getWorldMatrix = function () {
  19388. if (this._masterMesh) {
  19389. return this._masterMesh.getWorldMatrix();
  19390. }
  19391. return _super.prototype.getWorldMatrix.call(this);
  19392. };
  19393. /**
  19394. * Returns the latest update of the World matrix determinant.
  19395. */
  19396. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19397. if (this._masterMesh) {
  19398. return this._masterMesh._getWorldMatrixDeterminant();
  19399. }
  19400. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19401. };
  19402. // ================================== Point of View Movement =================================
  19403. /**
  19404. * Perform relative position change from the point of view of behind the front of the mesh.
  19405. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19406. * Supports definition of mesh facing forward or backward.
  19407. * @param {number} amountRight
  19408. * @param {number} amountUp
  19409. * @param {number} amountForward
  19410. *
  19411. * Returns the AbstractMesh.
  19412. */
  19413. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19414. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19415. return this;
  19416. };
  19417. /**
  19418. * Calculate relative position change from the point of view of behind the front of the mesh.
  19419. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19420. * Supports definition of mesh facing forward or backward.
  19421. * @param {number} amountRight
  19422. * @param {number} amountUp
  19423. * @param {number} amountForward
  19424. *
  19425. * Returns a new Vector3.
  19426. */
  19427. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19428. var rotMatrix = new BABYLON.Matrix();
  19429. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19430. rotQuaternion.toRotationMatrix(rotMatrix);
  19431. var translationDelta = BABYLON.Vector3.Zero();
  19432. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19433. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19434. return translationDelta;
  19435. };
  19436. // ================================== Point of View Rotation =================================
  19437. /**
  19438. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19439. * Supports definition of mesh facing forward or backward.
  19440. * @param {number} flipBack
  19441. * @param {number} twirlClockwise
  19442. * @param {number} tiltRight
  19443. *
  19444. * Returns the AbstractMesh.
  19445. */
  19446. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19447. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19448. return this;
  19449. };
  19450. /**
  19451. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19452. * Supports definition of mesh facing forward or backward.
  19453. * @param {number} flipBack
  19454. * @param {number} twirlClockwise
  19455. * @param {number} tiltRight
  19456. *
  19457. * Returns a new Vector3.
  19458. */
  19459. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19460. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19461. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19462. };
  19463. /**
  19464. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19465. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19466. */
  19467. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19468. if (includeDescendants === void 0) { includeDescendants = true; }
  19469. this.computeWorldMatrix(true);
  19470. var min;
  19471. var max;
  19472. var boundingInfo = this.getBoundingInfo();
  19473. if (!this.subMeshes) {
  19474. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19475. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19476. }
  19477. else {
  19478. min = boundingInfo.boundingBox.minimumWorld;
  19479. max = boundingInfo.boundingBox.maximumWorld;
  19480. }
  19481. if (includeDescendants) {
  19482. var descendants = this.getDescendants(false);
  19483. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19484. var descendant = descendants_1[_i];
  19485. var childMesh = descendant;
  19486. childMesh.computeWorldMatrix(true);
  19487. //make sure we have the needed params to get mix and max
  19488. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19489. continue;
  19490. }
  19491. var childBoundingInfo = childMesh.getBoundingInfo();
  19492. var boundingBox = childBoundingInfo.boundingBox;
  19493. var minBox = boundingBox.minimumWorld;
  19494. var maxBox = boundingBox.maximumWorld;
  19495. BABYLON.Tools.CheckExtends(minBox, min, max);
  19496. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19497. }
  19498. }
  19499. return {
  19500. min: min,
  19501. max: max
  19502. };
  19503. };
  19504. /**
  19505. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  19506. * Returns the AbstractMesh.
  19507. */
  19508. AbstractMesh.prototype._updateBoundingInfo = function () {
  19509. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  19510. this._boundingInfo.update(this.worldMatrixFromCache);
  19511. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19512. return this;
  19513. };
  19514. /**
  19515. * Update a mesh's children BoundingInfo objects only.
  19516. * Returns the AbstractMesh.
  19517. */
  19518. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  19519. if (!this.subMeshes) {
  19520. return this;
  19521. }
  19522. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19523. var subMesh = this.subMeshes[subIndex];
  19524. if (!subMesh.IsGlobal) {
  19525. subMesh.updateBoundingInfo(matrix);
  19526. }
  19527. }
  19528. return this;
  19529. };
  19530. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  19531. // Bounding info
  19532. this._updateBoundingInfo();
  19533. };
  19534. /**
  19535. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  19536. * A mesh is in the frustum if its bounding box intersects the frustum.
  19537. * Boolean returned.
  19538. */
  19539. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  19540. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  19541. };
  19542. /**
  19543. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  19544. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  19545. * Boolean returned.
  19546. */
  19547. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19548. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  19549. ;
  19550. };
  19551. /**
  19552. * True if the mesh intersects another mesh or a SolidParticle object.
  19553. * 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)
  19554. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  19555. * Returns a boolean.
  19556. */
  19557. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  19558. if (precise === void 0) { precise = false; }
  19559. if (!this._boundingInfo || !mesh._boundingInfo) {
  19560. return false;
  19561. }
  19562. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  19563. return true;
  19564. }
  19565. if (includeDescendants) {
  19566. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  19567. var child = _a[_i];
  19568. if (child.intersectsMesh(mesh, precise, true)) {
  19569. return true;
  19570. }
  19571. }
  19572. }
  19573. return false;
  19574. };
  19575. /**
  19576. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  19577. * Returns a boolean.
  19578. */
  19579. AbstractMesh.prototype.intersectsPoint = function (point) {
  19580. if (!this._boundingInfo) {
  19581. return false;
  19582. }
  19583. return this._boundingInfo.intersectsPoint(point);
  19584. };
  19585. AbstractMesh.prototype.getPhysicsImpostor = function () {
  19586. return this.physicsImpostor;
  19587. };
  19588. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  19589. if (camera === void 0) { camera = null; }
  19590. if (!camera) {
  19591. camera = this.getScene().activeCamera;
  19592. }
  19593. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  19594. };
  19595. /**
  19596. * Returns the distance from the mesh to the active camera.
  19597. * Returns a float.
  19598. */
  19599. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  19600. if (camera === void 0) { camera = null; }
  19601. if (!camera) {
  19602. camera = this.getScene().activeCamera;
  19603. }
  19604. return this.absolutePosition.subtract(camera.position).length();
  19605. };
  19606. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  19607. if (!this.physicsImpostor) {
  19608. return this;
  19609. }
  19610. this.physicsImpostor.applyImpulse(force, contactPoint);
  19611. return this;
  19612. };
  19613. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  19614. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  19615. return this;
  19616. }
  19617. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  19618. mainPivot: pivot1,
  19619. connectedPivot: pivot2,
  19620. nativeParams: options
  19621. });
  19622. return this;
  19623. };
  19624. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  19625. // Collisions
  19626. /**
  19627. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  19628. * Default `false`.
  19629. */
  19630. get: function () {
  19631. return this._checkCollisions;
  19632. },
  19633. set: function (collisionEnabled) {
  19634. this._checkCollisions = collisionEnabled;
  19635. if (this.getScene().workerCollisions) {
  19636. this.getScene().collisionCoordinator.onMeshUpdated(this);
  19637. }
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. Object.defineProperty(AbstractMesh.prototype, "collider", {
  19643. /**
  19644. * Gets Collider object used to compute collisions (not physics)
  19645. */
  19646. get: function () {
  19647. return this._collider;
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  19653. var globalPosition = this.getAbsolutePosition();
  19654. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  19655. if (!this._collider) {
  19656. this._collider = new BABYLON.Collider();
  19657. }
  19658. this._collider._radius = this.ellipsoid;
  19659. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  19660. return this;
  19661. };
  19662. // Submeshes octree
  19663. /**
  19664. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  19665. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  19666. * Returns an Octree of submeshes.
  19667. */
  19668. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  19669. if (maxCapacity === void 0) { maxCapacity = 64; }
  19670. if (maxDepth === void 0) { maxDepth = 2; }
  19671. if (!this._submeshesOctree) {
  19672. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  19673. }
  19674. this.computeWorldMatrix(true);
  19675. var boundingInfo = this.getBoundingInfo();
  19676. // Update octree
  19677. var bbox = boundingInfo.boundingBox;
  19678. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  19679. return this._submeshesOctree;
  19680. };
  19681. // Collisions
  19682. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  19683. this._generatePointsArray();
  19684. if (!this._positions) {
  19685. return this;
  19686. }
  19687. // Transformation
  19688. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  19689. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  19690. subMesh._lastColliderWorldVertices = [];
  19691. subMesh._trianglePlanes = [];
  19692. var start = subMesh.verticesStart;
  19693. var end = (subMesh.verticesStart + subMesh.verticesCount);
  19694. for (var i = start; i < end; i++) {
  19695. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  19696. }
  19697. }
  19698. // Collide
  19699. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  19700. if (collider.collisionFound) {
  19701. collider.collidedMesh = this;
  19702. }
  19703. return this;
  19704. };
  19705. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  19706. var subMeshes;
  19707. var len;
  19708. // Octrees
  19709. if (this._submeshesOctree && this.useOctreeForCollisions) {
  19710. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  19711. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  19712. len = intersections.length;
  19713. subMeshes = intersections.data;
  19714. }
  19715. else {
  19716. subMeshes = this.subMeshes;
  19717. len = subMeshes.length;
  19718. }
  19719. for (var index = 0; index < len; index++) {
  19720. var subMesh = subMeshes[index];
  19721. // Bounding test
  19722. if (len > 1 && !subMesh._checkCollision(collider))
  19723. continue;
  19724. this._collideForSubMesh(subMesh, transformMatrix, collider);
  19725. }
  19726. return this;
  19727. };
  19728. AbstractMesh.prototype._checkCollision = function (collider) {
  19729. // Bounding box test
  19730. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  19731. return this;
  19732. // Transformation matrix
  19733. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  19734. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  19735. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  19736. return this;
  19737. };
  19738. // Picking
  19739. AbstractMesh.prototype._generatePointsArray = function () {
  19740. return false;
  19741. };
  19742. /**
  19743. * Checks if the passed Ray intersects with the mesh.
  19744. * Returns an object PickingInfo.
  19745. */
  19746. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  19747. var pickingInfo = new BABYLON.PickingInfo();
  19748. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  19749. return pickingInfo;
  19750. }
  19751. if (!this._generatePointsArray()) {
  19752. return pickingInfo;
  19753. }
  19754. var intersectInfo = null;
  19755. // Octrees
  19756. var subMeshes;
  19757. var len;
  19758. if (this._submeshesOctree && this.useOctreeForPicking) {
  19759. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  19760. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  19761. len = intersections.length;
  19762. subMeshes = intersections.data;
  19763. }
  19764. else {
  19765. subMeshes = this.subMeshes;
  19766. len = subMeshes.length;
  19767. }
  19768. for (var index = 0; index < len; index++) {
  19769. var subMesh = subMeshes[index];
  19770. // Bounding test
  19771. if (len > 1 && !subMesh.canIntersects(ray))
  19772. continue;
  19773. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  19774. if (currentIntersectInfo) {
  19775. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19776. intersectInfo = currentIntersectInfo;
  19777. intersectInfo.subMeshId = index;
  19778. if (fastCheck) {
  19779. break;
  19780. }
  19781. }
  19782. }
  19783. }
  19784. if (intersectInfo) {
  19785. // Get picked point
  19786. var world = this.getWorldMatrix();
  19787. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  19788. var direction = ray.direction.clone();
  19789. direction = direction.scale(intersectInfo.distance);
  19790. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  19791. var pickedPoint = worldOrigin.add(worldDirection);
  19792. // Return result
  19793. pickingInfo.hit = true;
  19794. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  19795. pickingInfo.pickedPoint = pickedPoint;
  19796. pickingInfo.pickedMesh = this;
  19797. pickingInfo.bu = intersectInfo.bu || 0;
  19798. pickingInfo.bv = intersectInfo.bv || 0;
  19799. pickingInfo.faceId = intersectInfo.faceId;
  19800. pickingInfo.subMeshId = intersectInfo.subMeshId;
  19801. return pickingInfo;
  19802. }
  19803. return pickingInfo;
  19804. };
  19805. /**
  19806. * Clones the mesh, used by the class Mesh.
  19807. * Just returns `null` for an AbstractMesh.
  19808. */
  19809. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19810. return null;
  19811. };
  19812. /**
  19813. * Disposes all the mesh submeshes.
  19814. * Returns the AbstractMesh.
  19815. */
  19816. AbstractMesh.prototype.releaseSubMeshes = function () {
  19817. if (this.subMeshes) {
  19818. while (this.subMeshes.length) {
  19819. this.subMeshes[0].dispose();
  19820. }
  19821. }
  19822. else {
  19823. this.subMeshes = new Array();
  19824. }
  19825. return this;
  19826. };
  19827. /**
  19828. * Releases resources associated with this abstract mesh.
  19829. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19830. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19831. */
  19832. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19833. var _this = this;
  19834. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19835. var index;
  19836. // Smart Array Retainers.
  19837. this.getScene().freeActiveMeshes();
  19838. this.getScene().freeRenderingGroups();
  19839. // Action manager
  19840. if (this.actionManager !== undefined && this.actionManager !== null) {
  19841. this.actionManager.dispose();
  19842. this.actionManager = null;
  19843. }
  19844. // Skeleton
  19845. this._skeleton = null;
  19846. // Physics
  19847. if (this.physicsImpostor) {
  19848. this.physicsImpostor.dispose();
  19849. }
  19850. // Intersections in progress
  19851. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  19852. var other = this._intersectionsInProgress[index];
  19853. var pos = other._intersectionsInProgress.indexOf(this);
  19854. other._intersectionsInProgress.splice(pos, 1);
  19855. }
  19856. this._intersectionsInProgress = [];
  19857. // Lights
  19858. var lights = this.getScene().lights;
  19859. lights.forEach(function (light) {
  19860. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  19861. if (meshIndex !== -1) {
  19862. light.includedOnlyMeshes.splice(meshIndex, 1);
  19863. }
  19864. meshIndex = light.excludedMeshes.indexOf(_this);
  19865. if (meshIndex !== -1) {
  19866. light.excludedMeshes.splice(meshIndex, 1);
  19867. }
  19868. // Shadow generators
  19869. var generator = light.getShadowGenerator();
  19870. if (generator) {
  19871. var shadowMap = generator.getShadowMap();
  19872. if (shadowMap && shadowMap.renderList) {
  19873. meshIndex = shadowMap.renderList.indexOf(_this);
  19874. if (meshIndex !== -1) {
  19875. shadowMap.renderList.splice(meshIndex, 1);
  19876. }
  19877. }
  19878. }
  19879. });
  19880. // Edges
  19881. if (this._edgesRenderer) {
  19882. this._edgesRenderer.dispose();
  19883. this._edgesRenderer = null;
  19884. }
  19885. // SubMeshes
  19886. if (this.getClassName() !== "InstancedMesh") {
  19887. this.releaseSubMeshes();
  19888. }
  19889. // Octree
  19890. var sceneOctree = this.getScene().selectionOctree;
  19891. if (sceneOctree !== undefined && sceneOctree !== null) {
  19892. var index = sceneOctree.dynamicContent.indexOf(this);
  19893. if (index !== -1) {
  19894. sceneOctree.dynamicContent.splice(index, 1);
  19895. }
  19896. }
  19897. // Query
  19898. var engine = this.getScene().getEngine();
  19899. if (this._occlusionQuery) {
  19900. this._isOcclusionQueryInProgress = false;
  19901. engine.deleteQuery(this._occlusionQuery);
  19902. this._occlusionQuery = null;
  19903. }
  19904. // Engine
  19905. engine.wipeCaches();
  19906. // Remove from scene
  19907. this.getScene().removeMesh(this);
  19908. if (disposeMaterialAndTextures) {
  19909. if (this.material) {
  19910. this.material.dispose(false, true);
  19911. }
  19912. }
  19913. if (!doNotRecurse) {
  19914. // Particles
  19915. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  19916. if (this.getScene().particleSystems[index].emitter === this) {
  19917. this.getScene().particleSystems[index].dispose();
  19918. index--;
  19919. }
  19920. }
  19921. }
  19922. // facet data
  19923. if (this._facetDataEnabled) {
  19924. this.disableFacetData();
  19925. }
  19926. this.onAfterWorldMatrixUpdateObservable.clear();
  19927. this.onCollideObservable.clear();
  19928. this.onCollisionPositionChangeObservable.clear();
  19929. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19930. };
  19931. /**
  19932. * Adds the passed mesh as a child to the current mesh.
  19933. * Returns the AbstractMesh.
  19934. */
  19935. AbstractMesh.prototype.addChild = function (mesh) {
  19936. mesh.setParent(this);
  19937. return this;
  19938. };
  19939. /**
  19940. * Removes the passed mesh from the current mesh children list.
  19941. * Returns the AbstractMesh.
  19942. */
  19943. AbstractMesh.prototype.removeChild = function (mesh) {
  19944. mesh.setParent(null);
  19945. return this;
  19946. };
  19947. // Facet data
  19948. /**
  19949. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  19950. * Returns the AbstractMesh.
  19951. */
  19952. AbstractMesh.prototype._initFacetData = function () {
  19953. if (!this._facetNormals) {
  19954. this._facetNormals = new Array();
  19955. }
  19956. if (!this._facetPositions) {
  19957. this._facetPositions = new Array();
  19958. }
  19959. if (!this._facetPartitioning) {
  19960. this._facetPartitioning = new Array();
  19961. }
  19962. this._facetNb = (this.getIndices().length / 3) | 0;
  19963. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  19964. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  19965. for (var f = 0; f < this._facetNb; f++) {
  19966. this._facetNormals[f] = BABYLON.Vector3.Zero();
  19967. this._facetPositions[f] = BABYLON.Vector3.Zero();
  19968. }
  19969. this._facetDataEnabled = true;
  19970. return this;
  19971. };
  19972. /**
  19973. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  19974. * This method can be called within the render loop.
  19975. * 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.
  19976. * Returns the AbstractMesh.
  19977. */
  19978. AbstractMesh.prototype.updateFacetData = function () {
  19979. if (!this._facetDataEnabled) {
  19980. this._initFacetData();
  19981. }
  19982. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19983. var indices = this.getIndices();
  19984. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19985. var bInfo = this.getBoundingInfo();
  19986. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  19987. // init arrays, matrix and sort function on first call
  19988. this._facetDepthSortEnabled = true;
  19989. if (indices instanceof Uint16Array) {
  19990. this._depthSortedIndices = new Uint16Array(indices);
  19991. }
  19992. else if (indices instanceof Uint32Array) {
  19993. this._depthSortedIndices = new Uint32Array(indices);
  19994. }
  19995. else {
  19996. var needs32bits = false;
  19997. for (var i = 0; i < indices.length; i++) {
  19998. if (indices[i] > 65535) {
  19999. needs32bits = true;
  20000. break;
  20001. }
  20002. }
  20003. if (needs32bits) {
  20004. this._depthSortedIndices = new Uint32Array(indices);
  20005. }
  20006. else {
  20007. this._depthSortedIndices = new Uint16Array(indices);
  20008. }
  20009. }
  20010. this._facetDepthSortFunction = function (f1, f2) {
  20011. return (f2.sqDistance - f1.sqDistance);
  20012. };
  20013. if (!this._facetDepthSortFrom) {
  20014. var camera = this.getScene().activeCamera;
  20015. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20016. }
  20017. this._depthSortedFacets = [];
  20018. for (var f = 0; f < this._facetNb; f++) {
  20019. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20020. this._depthSortedFacets.push(depthSortedFacet);
  20021. }
  20022. this._invertedMatrix = BABYLON.Matrix.Identity();
  20023. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20024. }
  20025. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20026. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20027. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20028. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20029. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20030. this._subDiv.max = this._partitioningSubdivisions;
  20031. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20032. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20033. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20034. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20035. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20036. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20037. // set the parameters for ComputeNormals()
  20038. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20039. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20040. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20041. this._facetParameters.bInfo = bInfo;
  20042. this._facetParameters.bbSize = this._bbSize;
  20043. this._facetParameters.subDiv = this._subDiv;
  20044. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20045. this._facetParameters.depthSort = this._facetDepthSort;
  20046. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20047. this.computeWorldMatrix(true);
  20048. this._worldMatrix.invertToRef(this._invertedMatrix);
  20049. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20050. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20051. }
  20052. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20053. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20054. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20055. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20056. var l = (this._depthSortedIndices.length / 3) | 0;
  20057. for (var f = 0; f < l; f++) {
  20058. var sind = this._depthSortedFacets[f].ind;
  20059. this._depthSortedIndices[f * 3] = indices[sind];
  20060. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20061. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20062. }
  20063. this.updateIndices(this._depthSortedIndices);
  20064. }
  20065. return this;
  20066. };
  20067. /**
  20068. * Returns the facetLocalNormals array.
  20069. * The normals are expressed in the mesh local space.
  20070. */
  20071. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20072. if (!this._facetNormals) {
  20073. this.updateFacetData();
  20074. }
  20075. return this._facetNormals;
  20076. };
  20077. /**
  20078. * Returns the facetLocalPositions array.
  20079. * The facet positions are expressed in the mesh local space.
  20080. */
  20081. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20082. if (!this._facetPositions) {
  20083. this.updateFacetData();
  20084. }
  20085. return this._facetPositions;
  20086. };
  20087. /**
  20088. * Returns the facetLocalPartioning array.
  20089. */
  20090. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20091. if (!this._facetPartitioning) {
  20092. this.updateFacetData();
  20093. }
  20094. return this._facetPartitioning;
  20095. };
  20096. /**
  20097. * Returns the i-th facet position in the world system.
  20098. * This method allocates a new Vector3 per call.
  20099. */
  20100. AbstractMesh.prototype.getFacetPosition = function (i) {
  20101. var pos = BABYLON.Vector3.Zero();
  20102. this.getFacetPositionToRef(i, pos);
  20103. return pos;
  20104. };
  20105. /**
  20106. * Sets the reference Vector3 with the i-th facet position in the world system.
  20107. * Returns the AbstractMesh.
  20108. */
  20109. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20110. var localPos = (this.getFacetLocalPositions())[i];
  20111. var world = this.getWorldMatrix();
  20112. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20113. return this;
  20114. };
  20115. /**
  20116. * Returns the i-th facet normal in the world system.
  20117. * This method allocates a new Vector3 per call.
  20118. */
  20119. AbstractMesh.prototype.getFacetNormal = function (i) {
  20120. var norm = BABYLON.Vector3.Zero();
  20121. this.getFacetNormalToRef(i, norm);
  20122. return norm;
  20123. };
  20124. /**
  20125. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20126. * Returns the AbstractMesh.
  20127. */
  20128. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20129. var localNorm = (this.getFacetLocalNormals())[i];
  20130. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20131. return this;
  20132. };
  20133. /**
  20134. * 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).
  20135. */
  20136. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20137. var bInfo = this.getBoundingInfo();
  20138. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20139. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20140. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20141. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20142. return null;
  20143. }
  20144. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20145. };
  20146. /**
  20147. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20148. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20149. * 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.
  20150. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20151. * 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.
  20152. */
  20153. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20154. if (checkFace === void 0) { checkFace = false; }
  20155. if (facing === void 0) { facing = true; }
  20156. var world = this.getWorldMatrix();
  20157. var invMat = BABYLON.Tmp.Matrix[5];
  20158. world.invertToRef(invMat);
  20159. var invVect = BABYLON.Tmp.Vector3[8];
  20160. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20161. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20162. if (projected) {
  20163. // tranform the local computed projected vector to world coordinates
  20164. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20165. }
  20166. return closest;
  20167. };
  20168. /**
  20169. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20170. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20171. * 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.
  20172. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20173. * 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.
  20174. */
  20175. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20176. if (checkFace === void 0) { checkFace = false; }
  20177. if (facing === void 0) { facing = true; }
  20178. var closest = null;
  20179. var tmpx = 0.0;
  20180. var tmpy = 0.0;
  20181. var tmpz = 0.0;
  20182. var d = 0.0; // tmp dot facet normal * facet position
  20183. var t0 = 0.0;
  20184. var projx = 0.0;
  20185. var projy = 0.0;
  20186. var projz = 0.0;
  20187. // Get all the facets in the same partitioning block than (x, y, z)
  20188. var facetPositions = this.getFacetLocalPositions();
  20189. var facetNormals = this.getFacetLocalNormals();
  20190. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20191. if (!facetsInBlock) {
  20192. return null;
  20193. }
  20194. // Get the closest facet to (x, y, z)
  20195. var shortest = Number.MAX_VALUE; // init distance vars
  20196. var tmpDistance = shortest;
  20197. var fib; // current facet in the block
  20198. var norm; // current facet normal
  20199. var p0; // current facet barycenter position
  20200. // loop on all the facets in the current partitioning block
  20201. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20202. fib = facetsInBlock[idx];
  20203. norm = facetNormals[fib];
  20204. p0 = facetPositions[fib];
  20205. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20206. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20207. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20208. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20209. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20210. projx = x + norm.x * t0;
  20211. projy = y + norm.y * t0;
  20212. projz = z + norm.z * t0;
  20213. tmpx = projx - x;
  20214. tmpy = projy - y;
  20215. tmpz = projz - z;
  20216. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20217. if (tmpDistance < shortest) {
  20218. shortest = tmpDistance;
  20219. closest = fib;
  20220. if (projected) {
  20221. projected.x = projx;
  20222. projected.y = projy;
  20223. projected.z = projz;
  20224. }
  20225. }
  20226. }
  20227. }
  20228. return closest;
  20229. };
  20230. /**
  20231. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20232. */
  20233. AbstractMesh.prototype.getFacetDataParameters = function () {
  20234. return this._facetParameters;
  20235. };
  20236. /**
  20237. * Disables the feature FacetData and frees the related memory.
  20238. * Returns the AbstractMesh.
  20239. */
  20240. AbstractMesh.prototype.disableFacetData = function () {
  20241. if (this._facetDataEnabled) {
  20242. this._facetDataEnabled = false;
  20243. this._facetPositions = new Array();
  20244. this._facetNormals = new Array();
  20245. this._facetPartitioning = new Array();
  20246. this._facetParameters = null;
  20247. this._depthSortedIndices = new Uint32Array(0);
  20248. }
  20249. return this;
  20250. };
  20251. /**
  20252. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20253. * Returns the mesh.
  20254. */
  20255. AbstractMesh.prototype.updateIndices = function (indices) {
  20256. return this;
  20257. };
  20258. /**
  20259. * The mesh Geometry. Actually used by the Mesh object.
  20260. * Returns a blank geometry object.
  20261. */
  20262. /**
  20263. * Creates new normals data for the mesh.
  20264. * @param updatable.
  20265. */
  20266. AbstractMesh.prototype.createNormals = function (updatable) {
  20267. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20268. var indices = this.getIndices();
  20269. var normals;
  20270. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20271. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20272. }
  20273. else {
  20274. normals = [];
  20275. }
  20276. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20277. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20278. };
  20279. /**
  20280. * Align the mesh with a normal.
  20281. * Returns the mesh.
  20282. */
  20283. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20284. if (!upDirection) {
  20285. upDirection = BABYLON.Axis.Y;
  20286. }
  20287. var axisX = BABYLON.Tmp.Vector3[0];
  20288. var axisZ = BABYLON.Tmp.Vector3[1];
  20289. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20290. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20291. if (this.rotationQuaternion) {
  20292. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20293. }
  20294. else {
  20295. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20296. }
  20297. return this;
  20298. };
  20299. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20300. var engine = this.getEngine();
  20301. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20302. this._isOccluded = false;
  20303. return;
  20304. }
  20305. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20306. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20307. if (isOcclusionQueryAvailable) {
  20308. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20309. this._isOcclusionQueryInProgress = false;
  20310. this._occlusionInternalRetryCounter = 0;
  20311. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20312. }
  20313. else {
  20314. this._occlusionInternalRetryCounter++;
  20315. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20316. this._isOcclusionQueryInProgress = false;
  20317. this._occlusionInternalRetryCounter = 0;
  20318. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20319. // if strict continue the last state of the object.
  20320. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20321. }
  20322. else {
  20323. return;
  20324. }
  20325. }
  20326. }
  20327. var scene = this.getScene();
  20328. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20329. if (!this._occlusionQuery) {
  20330. this._occlusionQuery = engine.createQuery();
  20331. }
  20332. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20333. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20334. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20335. this._isOcclusionQueryInProgress = true;
  20336. };
  20337. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20338. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20339. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20340. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20341. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20342. return AbstractMesh;
  20343. }(BABYLON.TransformNode));
  20344. BABYLON.AbstractMesh = AbstractMesh;
  20345. })(BABYLON || (BABYLON = {}));
  20346. //# sourceMappingURL=babylon.abstractMesh.js.map
  20347. "use strict";
  20348. var BABYLON;
  20349. (function (BABYLON) {
  20350. /**
  20351. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20352. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20353. * 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.
  20354. */
  20355. var Light = /** @class */ (function (_super) {
  20356. __extends(Light, _super);
  20357. /**
  20358. * Creates a Light object in the scene.
  20359. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20360. * @param name The firendly name of the light
  20361. * @param scene The scene the light belongs too
  20362. */
  20363. function Light(name, scene) {
  20364. var _this = _super.call(this, name, scene) || this;
  20365. /**
  20366. * Diffuse gives the basic color to an object.
  20367. */
  20368. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20369. /**
  20370. * Specular produces a highlight color on an object.
  20371. * Note: This is note affecting PBR materials.
  20372. */
  20373. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20374. /**
  20375. * Strength of the light.
  20376. * Note: By default it is define in the framework own unit.
  20377. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20378. */
  20379. _this.intensity = 1.0;
  20380. /**
  20381. * Defines how far from the source the light is impacting in scene units.
  20382. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20383. */
  20384. _this.range = Number.MAX_VALUE;
  20385. /**
  20386. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20387. * of light.
  20388. */
  20389. _this._photometricScale = 1.0;
  20390. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20391. _this._radius = 0.00001;
  20392. /**
  20393. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20394. * exceeding the number allowed of the materials.
  20395. */
  20396. _this.renderPriority = 0;
  20397. /**
  20398. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20399. * the current shadow generator.
  20400. */
  20401. _this.shadowEnabled = true;
  20402. _this._excludeWithLayerMask = 0;
  20403. _this._includeOnlyWithLayerMask = 0;
  20404. _this._lightmapMode = 0;
  20405. /**
  20406. * @ignore Internal use only.
  20407. */
  20408. _this._excludedMeshesIds = new Array();
  20409. /**
  20410. * @ignore Internal use only.
  20411. */
  20412. _this._includedOnlyMeshesIds = new Array();
  20413. _this.getScene().addLight(_this);
  20414. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20415. _this._buildUniformLayout();
  20416. _this.includedOnlyMeshes = new Array();
  20417. _this.excludedMeshes = new Array();
  20418. _this._resyncMeshes();
  20419. return _this;
  20420. }
  20421. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20422. /**
  20423. * If every light affecting the material is in this lightmapMode,
  20424. * material.lightmapTexture adds or multiplies
  20425. * (depends on material.useLightmapAsShadowmap)
  20426. * after every other light calculations.
  20427. */
  20428. get: function () {
  20429. return Light._LIGHTMAP_DEFAULT;
  20430. },
  20431. enumerable: true,
  20432. configurable: true
  20433. });
  20434. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20435. /**
  20436. * material.lightmapTexture as only diffuse lighting from this light
  20437. * adds only specular lighting from this light
  20438. * adds dynamic shadows
  20439. */
  20440. get: function () {
  20441. return Light._LIGHTMAP_SPECULAR;
  20442. },
  20443. enumerable: true,
  20444. configurable: true
  20445. });
  20446. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20447. /**
  20448. * material.lightmapTexture as only lighting
  20449. * no light calculation from this light
  20450. * only adds dynamic shadows from this light
  20451. */
  20452. get: function () {
  20453. return Light._LIGHTMAP_SHADOWSONLY;
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20459. /**
  20460. * Each light type uses the default quantity according to its type:
  20461. * point/spot lights use luminous intensity
  20462. * directional lights use illuminance
  20463. */
  20464. get: function () {
  20465. return Light._INTENSITYMODE_AUTOMATIC;
  20466. },
  20467. enumerable: true,
  20468. configurable: true
  20469. });
  20470. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20471. /**
  20472. * lumen (lm)
  20473. */
  20474. get: function () {
  20475. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20476. },
  20477. enumerable: true,
  20478. configurable: true
  20479. });
  20480. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20481. /**
  20482. * candela (lm/sr)
  20483. */
  20484. get: function () {
  20485. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20486. },
  20487. enumerable: true,
  20488. configurable: true
  20489. });
  20490. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20491. /**
  20492. * lux (lm/m^2)
  20493. */
  20494. get: function () {
  20495. return Light._INTENSITYMODE_ILLUMINANCE;
  20496. },
  20497. enumerable: true,
  20498. configurable: true
  20499. });
  20500. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  20501. /**
  20502. * nit (cd/m^2)
  20503. */
  20504. get: function () {
  20505. return Light._INTENSITYMODE_LUMINANCE;
  20506. },
  20507. enumerable: true,
  20508. configurable: true
  20509. });
  20510. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  20511. /**
  20512. * Light type const id of the point light.
  20513. */
  20514. get: function () {
  20515. return Light._LIGHTTYPEID_POINTLIGHT;
  20516. },
  20517. enumerable: true,
  20518. configurable: true
  20519. });
  20520. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  20521. /**
  20522. * Light type const id of the directional light.
  20523. */
  20524. get: function () {
  20525. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  20526. },
  20527. enumerable: true,
  20528. configurable: true
  20529. });
  20530. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  20531. /**
  20532. * Light type const id of the spot light.
  20533. */
  20534. get: function () {
  20535. return Light._LIGHTTYPEID_SPOTLIGHT;
  20536. },
  20537. enumerable: true,
  20538. configurable: true
  20539. });
  20540. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  20541. /**
  20542. * Light type const id of the hemispheric light.
  20543. */
  20544. get: function () {
  20545. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  20546. },
  20547. enumerable: true,
  20548. configurable: true
  20549. });
  20550. Object.defineProperty(Light.prototype, "intensityMode", {
  20551. /**
  20552. * Gets the photometric scale used to interpret the intensity.
  20553. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20554. */
  20555. get: function () {
  20556. return this._intensityMode;
  20557. },
  20558. /**
  20559. * Sets the photometric scale used to interpret the intensity.
  20560. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20561. */
  20562. set: function (value) {
  20563. this._intensityMode = value;
  20564. this._computePhotometricScale();
  20565. },
  20566. enumerable: true,
  20567. configurable: true
  20568. });
  20569. ;
  20570. ;
  20571. Object.defineProperty(Light.prototype, "radius", {
  20572. /**
  20573. * Gets the light radius used by PBR Materials to simulate soft area lights.
  20574. */
  20575. get: function () {
  20576. return this._radius;
  20577. },
  20578. /**
  20579. * sets the light radius used by PBR Materials to simulate soft area lights.
  20580. */
  20581. set: function (value) {
  20582. this._radius = value;
  20583. this._computePhotometricScale();
  20584. },
  20585. enumerable: true,
  20586. configurable: true
  20587. });
  20588. ;
  20589. ;
  20590. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  20591. /**
  20592. * Gets the only meshes impacted by this light.
  20593. */
  20594. get: function () {
  20595. return this._includedOnlyMeshes;
  20596. },
  20597. /**
  20598. * Sets the only meshes impacted by this light.
  20599. */
  20600. set: function (value) {
  20601. this._includedOnlyMeshes = value;
  20602. this._hookArrayForIncludedOnly(value);
  20603. },
  20604. enumerable: true,
  20605. configurable: true
  20606. });
  20607. Object.defineProperty(Light.prototype, "excludedMeshes", {
  20608. /**
  20609. * Gets the meshes not impacted by this light.
  20610. */
  20611. get: function () {
  20612. return this._excludedMeshes;
  20613. },
  20614. /**
  20615. * Sets the meshes not impacted by this light.
  20616. */
  20617. set: function (value) {
  20618. this._excludedMeshes = value;
  20619. this._hookArrayForExcluded(value);
  20620. },
  20621. enumerable: true,
  20622. configurable: true
  20623. });
  20624. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  20625. /**
  20626. * Gets the layer id use to find what meshes are not impacted by the light.
  20627. * Inactive if 0
  20628. */
  20629. get: function () {
  20630. return this._excludeWithLayerMask;
  20631. },
  20632. /**
  20633. * Sets the layer id use to find what meshes are not impacted by the light.
  20634. * Inactive if 0
  20635. */
  20636. set: function (value) {
  20637. this._excludeWithLayerMask = value;
  20638. this._resyncMeshes();
  20639. },
  20640. enumerable: true,
  20641. configurable: true
  20642. });
  20643. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  20644. /**
  20645. * Gets the layer id use to find what meshes are impacted by the light.
  20646. * Inactive if 0
  20647. */
  20648. get: function () {
  20649. return this._includeOnlyWithLayerMask;
  20650. },
  20651. /**
  20652. * Sets the layer id use to find what meshes are impacted by the light.
  20653. * Inactive if 0
  20654. */
  20655. set: function (value) {
  20656. this._includeOnlyWithLayerMask = value;
  20657. this._resyncMeshes();
  20658. },
  20659. enumerable: true,
  20660. configurable: true
  20661. });
  20662. Object.defineProperty(Light.prototype, "lightmapMode", {
  20663. /**
  20664. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20665. */
  20666. get: function () {
  20667. return this._lightmapMode;
  20668. },
  20669. /**
  20670. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20671. */
  20672. set: function (value) {
  20673. if (this._lightmapMode === value) {
  20674. return;
  20675. }
  20676. this._lightmapMode = value;
  20677. this._markMeshesAsLightDirty();
  20678. },
  20679. enumerable: true,
  20680. configurable: true
  20681. });
  20682. /**
  20683. * Returns the string "Light".
  20684. * @returns the class name
  20685. */
  20686. Light.prototype.getClassName = function () {
  20687. return "Light";
  20688. };
  20689. /**
  20690. * Converts the light information to a readable string for debug purpose.
  20691. * @param fullDetails Supports for multiple levels of logging within scene loading
  20692. * @returns the human readable light info
  20693. */
  20694. Light.prototype.toString = function (fullDetails) {
  20695. var ret = "Name: " + this.name;
  20696. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  20697. if (this.animations) {
  20698. for (var i = 0; i < this.animations.length; i++) {
  20699. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20700. }
  20701. }
  20702. if (fullDetails) {
  20703. }
  20704. return ret;
  20705. };
  20706. /**
  20707. * Set the enabled state of this node.
  20708. * @param value - the new enabled state
  20709. */
  20710. Light.prototype.setEnabled = function (value) {
  20711. _super.prototype.setEnabled.call(this, value);
  20712. this._resyncMeshes();
  20713. };
  20714. /**
  20715. * Returns the Light associated shadow generator if any.
  20716. * @return the associated shadow generator.
  20717. */
  20718. Light.prototype.getShadowGenerator = function () {
  20719. return this._shadowGenerator;
  20720. };
  20721. /**
  20722. * Returns a Vector3, the absolute light position in the World.
  20723. * @returns the world space position of the light
  20724. */
  20725. Light.prototype.getAbsolutePosition = function () {
  20726. return BABYLON.Vector3.Zero();
  20727. };
  20728. /**
  20729. * Specifies if the light will affect the passed mesh.
  20730. * @param mesh The mesh to test against the light
  20731. * @return true the mesh is affected otherwise, false.
  20732. */
  20733. Light.prototype.canAffectMesh = function (mesh) {
  20734. if (!mesh) {
  20735. return true;
  20736. }
  20737. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  20738. return false;
  20739. }
  20740. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  20741. return false;
  20742. }
  20743. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  20744. return false;
  20745. }
  20746. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  20747. return false;
  20748. }
  20749. return true;
  20750. };
  20751. /**
  20752. * Computes and Returns the light World matrix.
  20753. * @returns the world matrix
  20754. */
  20755. Light.prototype.getWorldMatrix = function () {
  20756. this._currentRenderId = this.getScene().getRenderId();
  20757. this._childRenderId = this._currentRenderId;
  20758. var worldMatrix = this._getWorldMatrix();
  20759. if (this.parent && this.parent.getWorldMatrix) {
  20760. if (!this._parentedWorldMatrix) {
  20761. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  20762. }
  20763. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  20764. this._markSyncedWithParent();
  20765. return this._parentedWorldMatrix;
  20766. }
  20767. return worldMatrix;
  20768. };
  20769. /**
  20770. * Sort function to order lights for rendering.
  20771. * @param a First Light object to compare to second.
  20772. * @param b Second Light object to compare first.
  20773. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  20774. */
  20775. Light.CompareLightsPriority = function (a, b) {
  20776. //shadow-casting lights have priority over non-shadow-casting lights
  20777. //the renderPrioirty is a secondary sort criterion
  20778. if (a.shadowEnabled !== b.shadowEnabled) {
  20779. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  20780. }
  20781. return b.renderPriority - a.renderPriority;
  20782. };
  20783. /**
  20784. * Releases resources associated with this node.
  20785. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20786. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20787. */
  20788. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20789. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20790. if (this._shadowGenerator) {
  20791. this._shadowGenerator.dispose();
  20792. this._shadowGenerator = null;
  20793. }
  20794. // Animations
  20795. this.getScene().stopAnimation(this);
  20796. // Remove from meshes
  20797. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  20798. var mesh = _a[_i];
  20799. mesh._removeLightSource(this);
  20800. }
  20801. this._uniformBuffer.dispose();
  20802. // Remove from scene
  20803. this.getScene().removeLight(this);
  20804. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20805. };
  20806. /**
  20807. * Returns the light type ID (integer).
  20808. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  20809. */
  20810. Light.prototype.getTypeID = function () {
  20811. return 0;
  20812. };
  20813. /**
  20814. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  20815. * @returns the scaled intensity in intensity mode unit
  20816. */
  20817. Light.prototype.getScaledIntensity = function () {
  20818. return this._photometricScale * this.intensity;
  20819. };
  20820. /**
  20821. * Returns a new Light object, named "name", from the current one.
  20822. * @param name The name of the cloned light
  20823. * @returns the new created light
  20824. */
  20825. Light.prototype.clone = function (name) {
  20826. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  20827. if (!constructor) {
  20828. return null;
  20829. }
  20830. return BABYLON.SerializationHelper.Clone(constructor, this);
  20831. };
  20832. /**
  20833. * Serializes the current light into a Serialization object.
  20834. * @returns the serialized object.
  20835. */
  20836. Light.prototype.serialize = function () {
  20837. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20838. // Type
  20839. serializationObject.type = this.getTypeID();
  20840. // Parent
  20841. if (this.parent) {
  20842. serializationObject.parentId = this.parent.id;
  20843. }
  20844. // Inclusion / exclusions
  20845. if (this.excludedMeshes.length > 0) {
  20846. serializationObject.excludedMeshesIds = [];
  20847. this.excludedMeshes.forEach(function (mesh) {
  20848. serializationObject.excludedMeshesIds.push(mesh.id);
  20849. });
  20850. }
  20851. if (this.includedOnlyMeshes.length > 0) {
  20852. serializationObject.includedOnlyMeshesIds = [];
  20853. this.includedOnlyMeshes.forEach(function (mesh) {
  20854. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  20855. });
  20856. }
  20857. // Animations
  20858. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20859. serializationObject.ranges = this.serializeAnimationRanges();
  20860. return serializationObject;
  20861. };
  20862. /**
  20863. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  20864. * This new light is named "name" and added to the passed scene.
  20865. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  20866. * @param name The friendly name of the light
  20867. * @param scene The scene the new light will belong to
  20868. * @returns the constructor function
  20869. */
  20870. Light.GetConstructorFromName = function (type, name, scene) {
  20871. switch (type) {
  20872. case 0:
  20873. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  20874. case 1:
  20875. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  20876. case 2:
  20877. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  20878. case 3:
  20879. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  20880. }
  20881. return null;
  20882. };
  20883. /**
  20884. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  20885. * @param parsedLight The JSON representation of the light
  20886. * @param scene The scene to create the parsed light in
  20887. * @returns the created light after parsing
  20888. */
  20889. Light.Parse = function (parsedLight, scene) {
  20890. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  20891. if (!constructor) {
  20892. return null;
  20893. }
  20894. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  20895. // Inclusion / exclusions
  20896. if (parsedLight.excludedMeshesIds) {
  20897. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20898. }
  20899. if (parsedLight.includedOnlyMeshesIds) {
  20900. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20901. }
  20902. // Parent
  20903. if (parsedLight.parentId) {
  20904. light._waitingParentId = parsedLight.parentId;
  20905. }
  20906. // Animations
  20907. if (parsedLight.animations) {
  20908. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20909. var parsedAnimation = parsedLight.animations[animationIndex];
  20910. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20911. }
  20912. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  20913. }
  20914. if (parsedLight.autoAnimate) {
  20915. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  20916. }
  20917. return light;
  20918. };
  20919. Light.prototype._hookArrayForExcluded = function (array) {
  20920. var _this = this;
  20921. var oldPush = array.push;
  20922. array.push = function () {
  20923. var items = [];
  20924. for (var _i = 0; _i < arguments.length; _i++) {
  20925. items[_i] = arguments[_i];
  20926. }
  20927. var result = oldPush.apply(array, items);
  20928. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  20929. var item = items_1[_a];
  20930. item._resyncLighSource(_this);
  20931. }
  20932. return result;
  20933. };
  20934. var oldSplice = array.splice;
  20935. array.splice = function (index, deleteCount) {
  20936. var deleted = oldSplice.apply(array, [index, deleteCount]);
  20937. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  20938. var item = deleted_1[_i];
  20939. item._resyncLighSource(_this);
  20940. }
  20941. return deleted;
  20942. };
  20943. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  20944. var item = array_1[_i];
  20945. item._resyncLighSource(this);
  20946. }
  20947. };
  20948. Light.prototype._hookArrayForIncludedOnly = function (array) {
  20949. var _this = this;
  20950. var oldPush = array.push;
  20951. array.push = function () {
  20952. var items = [];
  20953. for (var _i = 0; _i < arguments.length; _i++) {
  20954. items[_i] = arguments[_i];
  20955. }
  20956. var result = oldPush.apply(array, items);
  20957. _this._resyncMeshes();
  20958. return result;
  20959. };
  20960. var oldSplice = array.splice;
  20961. array.splice = function (index, deleteCount) {
  20962. var deleted = oldSplice.apply(array, [index, deleteCount]);
  20963. _this._resyncMeshes();
  20964. return deleted;
  20965. };
  20966. this._resyncMeshes();
  20967. };
  20968. Light.prototype._resyncMeshes = function () {
  20969. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  20970. var mesh = _a[_i];
  20971. mesh._resyncLighSource(this);
  20972. }
  20973. };
  20974. /**
  20975. * Forces the meshes to update their light related information in their rendering used effects
  20976. * @ignore Internal Use Only
  20977. */
  20978. Light.prototype._markMeshesAsLightDirty = function () {
  20979. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  20980. var mesh = _a[_i];
  20981. if (mesh._lightSources.indexOf(this) !== -1) {
  20982. mesh._markSubMeshesAsLightDirty();
  20983. }
  20984. }
  20985. };
  20986. /**
  20987. * Recomputes the cached photometric scale if needed.
  20988. */
  20989. Light.prototype._computePhotometricScale = function () {
  20990. this._photometricScale = this._getPhotometricScale();
  20991. this.getScene().resetCachedMaterial();
  20992. };
  20993. /**
  20994. * Returns the Photometric Scale according to the light type and intensity mode.
  20995. */
  20996. Light.prototype._getPhotometricScale = function () {
  20997. var photometricScale = 0.0;
  20998. var lightTypeID = this.getTypeID();
  20999. //get photometric mode
  21000. var photometricMode = this.intensityMode;
  21001. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21002. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21003. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21004. }
  21005. else {
  21006. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21007. }
  21008. }
  21009. //compute photometric scale
  21010. switch (lightTypeID) {
  21011. case Light.LIGHTTYPEID_POINTLIGHT:
  21012. case Light.LIGHTTYPEID_SPOTLIGHT:
  21013. switch (photometricMode) {
  21014. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21015. photometricScale = 1.0 / (4.0 * Math.PI);
  21016. break;
  21017. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21018. photometricScale = 1.0;
  21019. break;
  21020. case Light.INTENSITYMODE_LUMINANCE:
  21021. photometricScale = this.radius * this.radius;
  21022. break;
  21023. }
  21024. break;
  21025. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21026. switch (photometricMode) {
  21027. case Light.INTENSITYMODE_ILLUMINANCE:
  21028. photometricScale = 1.0;
  21029. break;
  21030. case Light.INTENSITYMODE_LUMINANCE:
  21031. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21032. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21033. var apexAngleRadians = this.radius;
  21034. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21035. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21036. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21037. photometricScale = solidAngle;
  21038. break;
  21039. }
  21040. break;
  21041. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21042. // No fall off in hemisperic light.
  21043. photometricScale = 1.0;
  21044. break;
  21045. }
  21046. return photometricScale;
  21047. };
  21048. /**
  21049. * Reorder the light in the scene according to their defined priority.
  21050. * @ignore Internal Use Only
  21051. */
  21052. Light.prototype._reorderLightsInScene = function () {
  21053. var scene = this.getScene();
  21054. if (this._renderPriority != 0) {
  21055. scene.requireLightSorting = true;
  21056. }
  21057. this.getScene().sortLightsByPriority();
  21058. };
  21059. //lightmapMode Consts
  21060. Light._LIGHTMAP_DEFAULT = 0;
  21061. Light._LIGHTMAP_SPECULAR = 1;
  21062. Light._LIGHTMAP_SHADOWSONLY = 2;
  21063. // Intensity Mode Consts
  21064. Light._INTENSITYMODE_AUTOMATIC = 0;
  21065. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21066. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21067. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21068. Light._INTENSITYMODE_LUMINANCE = 4;
  21069. // Light types ids const.
  21070. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21071. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21072. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21073. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21074. __decorate([
  21075. BABYLON.serializeAsColor3()
  21076. ], Light.prototype, "diffuse", void 0);
  21077. __decorate([
  21078. BABYLON.serializeAsColor3()
  21079. ], Light.prototype, "specular", void 0);
  21080. __decorate([
  21081. BABYLON.serialize()
  21082. ], Light.prototype, "intensity", void 0);
  21083. __decorate([
  21084. BABYLON.serialize()
  21085. ], Light.prototype, "range", void 0);
  21086. __decorate([
  21087. BABYLON.serialize()
  21088. ], Light.prototype, "intensityMode", null);
  21089. __decorate([
  21090. BABYLON.serialize()
  21091. ], Light.prototype, "radius", null);
  21092. __decorate([
  21093. BABYLON.serialize()
  21094. ], Light.prototype, "_renderPriority", void 0);
  21095. __decorate([
  21096. BABYLON.expandToProperty("_reorderLightsInScene")
  21097. ], Light.prototype, "renderPriority", void 0);
  21098. __decorate([
  21099. BABYLON.serialize()
  21100. ], Light.prototype, "shadowEnabled", void 0);
  21101. __decorate([
  21102. BABYLON.serialize("excludeWithLayerMask")
  21103. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21104. __decorate([
  21105. BABYLON.serialize("includeOnlyWithLayerMask")
  21106. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21107. __decorate([
  21108. BABYLON.serialize("lightmapMode")
  21109. ], Light.prototype, "_lightmapMode", void 0);
  21110. return Light;
  21111. }(BABYLON.Node));
  21112. BABYLON.Light = Light;
  21113. })(BABYLON || (BABYLON = {}));
  21114. //# sourceMappingURL=babylon.light.js.map
  21115. "use strict";
  21116. var BABYLON;
  21117. (function (BABYLON) {
  21118. var Camera = /** @class */ (function (_super) {
  21119. __extends(Camera, _super);
  21120. function Camera(name, position, scene) {
  21121. var _this = _super.call(this, name, scene) || this;
  21122. /**
  21123. * The vector the camera should consider as up.
  21124. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21125. */
  21126. _this.upVector = BABYLON.Vector3.Up();
  21127. _this.orthoLeft = null;
  21128. _this.orthoRight = null;
  21129. _this.orthoBottom = null;
  21130. _this.orthoTop = null;
  21131. /**
  21132. * FOV is set in Radians. (default is 0.8)
  21133. */
  21134. _this.fov = 0.8;
  21135. _this.minZ = 1;
  21136. _this.maxZ = 10000.0;
  21137. _this.inertia = 0.9;
  21138. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21139. _this.isIntermediate = false;
  21140. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21141. /**
  21142. * Restricts the camera to viewing objects with the same layerMask.
  21143. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21144. */
  21145. _this.layerMask = 0x0FFFFFFF;
  21146. /**
  21147. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21148. */
  21149. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21150. // Camera rig members
  21151. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21152. _this._rigCameras = new Array();
  21153. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21154. _this._skipRendering = false;
  21155. _this.customRenderTargets = new Array();
  21156. // Observables
  21157. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21158. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21159. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21160. _this.onRestoreStateObservable = new BABYLON.Observable();
  21161. // Cache
  21162. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21163. _this._projectionMatrix = new BABYLON.Matrix();
  21164. _this._doNotComputeProjectionMatrix = false;
  21165. _this._postProcesses = new Array();
  21166. _this._transformMatrix = BABYLON.Matrix.Zero();
  21167. _this._activeMeshes = new BABYLON.SmartArray(256);
  21168. _this._globalPosition = BABYLON.Vector3.Zero();
  21169. _this._refreshFrustumPlanes = true;
  21170. _this.getScene().addCamera(_this);
  21171. if (!_this.getScene().activeCamera) {
  21172. _this.getScene().activeCamera = _this;
  21173. }
  21174. _this.position = position;
  21175. return _this;
  21176. }
  21177. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21178. get: function () {
  21179. return Camera._PERSPECTIVE_CAMERA;
  21180. },
  21181. enumerable: true,
  21182. configurable: true
  21183. });
  21184. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21185. get: function () {
  21186. return Camera._ORTHOGRAPHIC_CAMERA;
  21187. },
  21188. enumerable: true,
  21189. configurable: true
  21190. });
  21191. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21192. /**
  21193. * This is the default FOV mode for perspective cameras.
  21194. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21195. *
  21196. */
  21197. get: function () {
  21198. return Camera._FOVMODE_VERTICAL_FIXED;
  21199. },
  21200. enumerable: true,
  21201. configurable: true
  21202. });
  21203. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21204. /**
  21205. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21206. *
  21207. */
  21208. get: function () {
  21209. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21210. },
  21211. enumerable: true,
  21212. configurable: true
  21213. });
  21214. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21215. get: function () {
  21216. return Camera._RIG_MODE_NONE;
  21217. },
  21218. enumerable: true,
  21219. configurable: true
  21220. });
  21221. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21222. get: function () {
  21223. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21224. },
  21225. enumerable: true,
  21226. configurable: true
  21227. });
  21228. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21229. get: function () {
  21230. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21231. },
  21232. enumerable: true,
  21233. configurable: true
  21234. });
  21235. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21236. get: function () {
  21237. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21238. },
  21239. enumerable: true,
  21240. configurable: true
  21241. });
  21242. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21243. get: function () {
  21244. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21245. },
  21246. enumerable: true,
  21247. configurable: true
  21248. });
  21249. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21250. get: function () {
  21251. return Camera._RIG_MODE_VR;
  21252. },
  21253. enumerable: true,
  21254. configurable: true
  21255. });
  21256. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21257. get: function () {
  21258. return Camera._RIG_MODE_WEBVR;
  21259. },
  21260. enumerable: true,
  21261. configurable: true
  21262. });
  21263. /**
  21264. * Store current camera state (fov, position, etc..)
  21265. */
  21266. Camera.prototype.storeState = function () {
  21267. this._stateStored = true;
  21268. this._storedFov = this.fov;
  21269. return this;
  21270. };
  21271. /**
  21272. * Restores the camera state values if it has been stored. You must call storeState() first
  21273. */
  21274. Camera.prototype._restoreStateValues = function () {
  21275. if (!this._stateStored) {
  21276. return false;
  21277. }
  21278. this.fov = this._storedFov;
  21279. return true;
  21280. };
  21281. /**
  21282. * Restored camera state. You must call storeState() first
  21283. */
  21284. Camera.prototype.restoreState = function () {
  21285. if (this._restoreStateValues()) {
  21286. this.onRestoreStateObservable.notifyObservers(this);
  21287. return true;
  21288. }
  21289. return false;
  21290. };
  21291. Camera.prototype.getClassName = function () {
  21292. return "Camera";
  21293. };
  21294. /**
  21295. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21296. */
  21297. Camera.prototype.toString = function (fullDetails) {
  21298. var ret = "Name: " + this.name;
  21299. ret += ", type: " + this.getClassName();
  21300. if (this.animations) {
  21301. for (var i = 0; i < this.animations.length; i++) {
  21302. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21303. }
  21304. }
  21305. if (fullDetails) {
  21306. }
  21307. return ret;
  21308. };
  21309. Object.defineProperty(Camera.prototype, "globalPosition", {
  21310. get: function () {
  21311. return this._globalPosition;
  21312. },
  21313. enumerable: true,
  21314. configurable: true
  21315. });
  21316. Camera.prototype.getActiveMeshes = function () {
  21317. return this._activeMeshes;
  21318. };
  21319. Camera.prototype.isActiveMesh = function (mesh) {
  21320. return (this._activeMeshes.indexOf(mesh) !== -1);
  21321. };
  21322. /**
  21323. * Is this camera ready to be used/rendered
  21324. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21325. * @return true if the camera is ready
  21326. */
  21327. Camera.prototype.isReady = function (completeCheck) {
  21328. if (completeCheck === void 0) { completeCheck = false; }
  21329. if (completeCheck) {
  21330. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21331. var pp = _a[_i];
  21332. if (pp && !pp.isReady()) {
  21333. return false;
  21334. }
  21335. }
  21336. }
  21337. return _super.prototype.isReady.call(this, completeCheck);
  21338. };
  21339. //Cache
  21340. Camera.prototype._initCache = function () {
  21341. _super.prototype._initCache.call(this);
  21342. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21343. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21344. this._cache.mode = undefined;
  21345. this._cache.minZ = undefined;
  21346. this._cache.maxZ = undefined;
  21347. this._cache.fov = undefined;
  21348. this._cache.fovMode = undefined;
  21349. this._cache.aspectRatio = undefined;
  21350. this._cache.orthoLeft = undefined;
  21351. this._cache.orthoRight = undefined;
  21352. this._cache.orthoBottom = undefined;
  21353. this._cache.orthoTop = undefined;
  21354. this._cache.renderWidth = undefined;
  21355. this._cache.renderHeight = undefined;
  21356. };
  21357. Camera.prototype._updateCache = function (ignoreParentClass) {
  21358. if (!ignoreParentClass) {
  21359. _super.prototype._updateCache.call(this);
  21360. }
  21361. this._cache.position.copyFrom(this.position);
  21362. this._cache.upVector.copyFrom(this.upVector);
  21363. };
  21364. // Synchronized
  21365. Camera.prototype._isSynchronized = function () {
  21366. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21367. };
  21368. Camera.prototype._isSynchronizedViewMatrix = function () {
  21369. if (!_super.prototype._isSynchronized.call(this))
  21370. return false;
  21371. return this._cache.position.equals(this.position)
  21372. && this._cache.upVector.equals(this.upVector)
  21373. && this.isSynchronizedWithParent();
  21374. };
  21375. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21376. var check = this._cache.mode === this.mode
  21377. && this._cache.minZ === this.minZ
  21378. && this._cache.maxZ === this.maxZ;
  21379. if (!check) {
  21380. return false;
  21381. }
  21382. var engine = this.getEngine();
  21383. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21384. check = this._cache.fov === this.fov
  21385. && this._cache.fovMode === this.fovMode
  21386. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21387. }
  21388. else {
  21389. check = this._cache.orthoLeft === this.orthoLeft
  21390. && this._cache.orthoRight === this.orthoRight
  21391. && this._cache.orthoBottom === this.orthoBottom
  21392. && this._cache.orthoTop === this.orthoTop
  21393. && this._cache.renderWidth === engine.getRenderWidth()
  21394. && this._cache.renderHeight === engine.getRenderHeight();
  21395. }
  21396. return check;
  21397. };
  21398. // Controls
  21399. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21400. };
  21401. Camera.prototype.detachControl = function (element) {
  21402. };
  21403. Camera.prototype.update = function () {
  21404. this._checkInputs();
  21405. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21406. this._updateRigCameras();
  21407. }
  21408. };
  21409. Camera.prototype._checkInputs = function () {
  21410. this.onAfterCheckInputsObservable.notifyObservers(this);
  21411. };
  21412. Object.defineProperty(Camera.prototype, "rigCameras", {
  21413. get: function () {
  21414. return this._rigCameras;
  21415. },
  21416. enumerable: true,
  21417. configurable: true
  21418. });
  21419. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21420. get: function () {
  21421. return this._rigPostProcess;
  21422. },
  21423. enumerable: true,
  21424. configurable: true
  21425. });
  21426. /**
  21427. * Internal, gets the first post proces.
  21428. * @returns the first post process to be run on this camera.
  21429. */
  21430. Camera.prototype._getFirstPostProcess = function () {
  21431. for (var pp in this._postProcesses) {
  21432. if (this._postProcesses[pp] !== null) {
  21433. return this._postProcesses[pp];
  21434. }
  21435. }
  21436. return null;
  21437. };
  21438. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21439. // invalidate framebuffer
  21440. var firstPostProcess = this._getFirstPostProcess();
  21441. if (firstPostProcess) {
  21442. firstPostProcess.markTextureDirty();
  21443. }
  21444. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21445. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21446. var cam = this._rigCameras[i];
  21447. var rigPostProcess = cam._rigPostProcess;
  21448. // for VR rig, there does not have to be a post process
  21449. if (rigPostProcess) {
  21450. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21451. if (isPass) {
  21452. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21453. cam.isIntermediate = this._postProcesses.length === 0;
  21454. }
  21455. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21456. rigPostProcess.markTextureDirty();
  21457. }
  21458. else {
  21459. cam._postProcesses = this._postProcesses.slice(0);
  21460. }
  21461. }
  21462. };
  21463. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21464. if (insertAt === void 0) { insertAt = null; }
  21465. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21466. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21467. return 0;
  21468. }
  21469. if (insertAt == null || insertAt < 0) {
  21470. this._postProcesses.push(postProcess);
  21471. }
  21472. else if (this._postProcesses[insertAt] === null) {
  21473. this._postProcesses[insertAt] = postProcess;
  21474. }
  21475. else {
  21476. this._postProcesses.splice(insertAt, 0, postProcess);
  21477. }
  21478. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21479. return this._postProcesses.indexOf(postProcess);
  21480. };
  21481. Camera.prototype.detachPostProcess = function (postProcess) {
  21482. var idx = this._postProcesses.indexOf(postProcess);
  21483. if (idx !== -1) {
  21484. this._postProcesses[idx] = null;
  21485. }
  21486. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21487. };
  21488. Camera.prototype.getWorldMatrix = function () {
  21489. if (!this._worldMatrix) {
  21490. this._worldMatrix = BABYLON.Matrix.Identity();
  21491. }
  21492. var viewMatrix = this.getViewMatrix();
  21493. viewMatrix.invertToRef(this._worldMatrix);
  21494. return this._worldMatrix;
  21495. };
  21496. Camera.prototype._getViewMatrix = function () {
  21497. return BABYLON.Matrix.Identity();
  21498. };
  21499. Camera.prototype.getViewMatrix = function (force) {
  21500. if (!force && this._isSynchronizedViewMatrix()) {
  21501. return this._computedViewMatrix;
  21502. }
  21503. this.updateCache();
  21504. this._computedViewMatrix = this._getViewMatrix();
  21505. this._currentRenderId = this.getScene().getRenderId();
  21506. this._childRenderId = this._currentRenderId;
  21507. this._refreshFrustumPlanes = true;
  21508. if (!this.parent || !this.parent.getWorldMatrix) {
  21509. this._globalPosition.copyFrom(this.position);
  21510. }
  21511. else {
  21512. if (!this._worldMatrix) {
  21513. this._worldMatrix = BABYLON.Matrix.Identity();
  21514. }
  21515. this._computedViewMatrix.invertToRef(this._worldMatrix);
  21516. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  21517. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  21518. this._computedViewMatrix.invert();
  21519. this._markSyncedWithParent();
  21520. }
  21521. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  21522. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  21523. }
  21524. this.onViewMatrixChangedObservable.notifyObservers(this);
  21525. return this._computedViewMatrix;
  21526. };
  21527. Camera.prototype.freezeProjectionMatrix = function (projection) {
  21528. this._doNotComputeProjectionMatrix = true;
  21529. if (projection !== undefined) {
  21530. this._projectionMatrix = projection;
  21531. }
  21532. };
  21533. ;
  21534. Camera.prototype.unfreezeProjectionMatrix = function () {
  21535. this._doNotComputeProjectionMatrix = false;
  21536. };
  21537. ;
  21538. Camera.prototype.getProjectionMatrix = function (force) {
  21539. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  21540. return this._projectionMatrix;
  21541. }
  21542. // Cache
  21543. this._cache.mode = this.mode;
  21544. this._cache.minZ = this.minZ;
  21545. this._cache.maxZ = this.maxZ;
  21546. // Matrix
  21547. this._refreshFrustumPlanes = true;
  21548. var engine = this.getEngine();
  21549. var scene = this.getScene();
  21550. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21551. this._cache.fov = this.fov;
  21552. this._cache.fovMode = this.fovMode;
  21553. this._cache.aspectRatio = engine.getAspectRatio(this);
  21554. if (this.minZ <= 0) {
  21555. this.minZ = 0.1;
  21556. }
  21557. if (scene.useRightHandedSystem) {
  21558. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21559. }
  21560. else {
  21561. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21562. }
  21563. }
  21564. else {
  21565. var halfWidth = engine.getRenderWidth() / 2.0;
  21566. var halfHeight = engine.getRenderHeight() / 2.0;
  21567. if (scene.useRightHandedSystem) {
  21568. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21569. }
  21570. else {
  21571. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21572. }
  21573. this._cache.orthoLeft = this.orthoLeft;
  21574. this._cache.orthoRight = this.orthoRight;
  21575. this._cache.orthoBottom = this.orthoBottom;
  21576. this._cache.orthoTop = this.orthoTop;
  21577. this._cache.renderWidth = engine.getRenderWidth();
  21578. this._cache.renderHeight = engine.getRenderHeight();
  21579. }
  21580. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  21581. return this._projectionMatrix;
  21582. };
  21583. Camera.prototype.getTranformationMatrix = function () {
  21584. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21585. return this._transformMatrix;
  21586. };
  21587. Camera.prototype.updateFrustumPlanes = function () {
  21588. if (!this._refreshFrustumPlanes) {
  21589. return;
  21590. }
  21591. this.getTranformationMatrix();
  21592. if (!this._frustumPlanes) {
  21593. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21594. }
  21595. else {
  21596. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21597. }
  21598. this._refreshFrustumPlanes = false;
  21599. };
  21600. Camera.prototype.isInFrustum = function (target) {
  21601. this.updateFrustumPlanes();
  21602. return target.isInFrustum(this._frustumPlanes);
  21603. };
  21604. Camera.prototype.isCompletelyInFrustum = function (target) {
  21605. this.updateFrustumPlanes();
  21606. return target.isCompletelyInFrustum(this._frustumPlanes);
  21607. };
  21608. Camera.prototype.getForwardRay = function (length, transform, origin) {
  21609. if (length === void 0) { length = 100; }
  21610. if (!transform) {
  21611. transform = this.getWorldMatrix();
  21612. }
  21613. if (!origin) {
  21614. origin = this.position;
  21615. }
  21616. var forward = new BABYLON.Vector3(0, 0, 1);
  21617. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  21618. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  21619. return new BABYLON.Ray(origin, direction, length);
  21620. };
  21621. /**
  21622. * Releases resources associated with this node.
  21623. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21624. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21625. */
  21626. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21627. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21628. // Observables
  21629. this.onViewMatrixChangedObservable.clear();
  21630. this.onProjectionMatrixChangedObservable.clear();
  21631. this.onAfterCheckInputsObservable.clear();
  21632. this.onRestoreStateObservable.clear();
  21633. // Inputs
  21634. if (this.inputs) {
  21635. this.inputs.clear();
  21636. }
  21637. // Animations
  21638. this.getScene().stopAnimation(this);
  21639. // Remove from scene
  21640. this.getScene().removeCamera(this);
  21641. while (this._rigCameras.length > 0) {
  21642. var camera = this._rigCameras.pop();
  21643. if (camera) {
  21644. camera.dispose();
  21645. }
  21646. }
  21647. // Postprocesses
  21648. if (this._rigPostProcess) {
  21649. this._rigPostProcess.dispose(this);
  21650. this._rigPostProcess = null;
  21651. this._postProcesses = [];
  21652. }
  21653. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21654. this._rigPostProcess = null;
  21655. this._postProcesses = [];
  21656. }
  21657. else {
  21658. var i = this._postProcesses.length;
  21659. while (--i >= 0) {
  21660. var postProcess = this._postProcesses[i];
  21661. if (postProcess) {
  21662. postProcess.dispose(this);
  21663. }
  21664. }
  21665. }
  21666. // Render targets
  21667. var i = this.customRenderTargets.length;
  21668. while (--i >= 0) {
  21669. this.customRenderTargets[i].dispose();
  21670. }
  21671. this.customRenderTargets = [];
  21672. // Active Meshes
  21673. this._activeMeshes.dispose();
  21674. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21675. };
  21676. Object.defineProperty(Camera.prototype, "leftCamera", {
  21677. // ---- Camera rigs section ----
  21678. get: function () {
  21679. if (this._rigCameras.length < 1) {
  21680. return null;
  21681. }
  21682. return this._rigCameras[0];
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. Object.defineProperty(Camera.prototype, "rightCamera", {
  21688. get: function () {
  21689. if (this._rigCameras.length < 2) {
  21690. return null;
  21691. }
  21692. return this._rigCameras[1];
  21693. },
  21694. enumerable: true,
  21695. configurable: true
  21696. });
  21697. Camera.prototype.getLeftTarget = function () {
  21698. if (this._rigCameras.length < 1) {
  21699. return null;
  21700. }
  21701. return this._rigCameras[0].getTarget();
  21702. };
  21703. Camera.prototype.getRightTarget = function () {
  21704. if (this._rigCameras.length < 2) {
  21705. return null;
  21706. }
  21707. return this._rigCameras[1].getTarget();
  21708. };
  21709. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  21710. if (this.cameraRigMode === mode) {
  21711. return;
  21712. }
  21713. while (this._rigCameras.length > 0) {
  21714. var camera = this._rigCameras.pop();
  21715. if (camera) {
  21716. camera.dispose();
  21717. }
  21718. }
  21719. this.cameraRigMode = mode;
  21720. this._cameraRigParams = {};
  21721. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  21722. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  21723. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  21724. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  21725. // create the rig cameras, unless none
  21726. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21727. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  21728. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  21729. if (leftCamera && rightCamera) {
  21730. this._rigCameras.push(leftCamera);
  21731. this._rigCameras.push(rightCamera);
  21732. }
  21733. }
  21734. switch (this.cameraRigMode) {
  21735. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  21736. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  21737. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  21738. break;
  21739. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  21740. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  21741. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  21742. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21743. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  21744. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  21745. break;
  21746. case Camera.RIG_MODE_VR:
  21747. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  21748. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  21749. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  21750. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21751. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  21752. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  21753. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  21754. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  21755. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  21756. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21757. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  21758. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  21759. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  21760. if (metrics.compensateDistortion) {
  21761. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  21762. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  21763. }
  21764. break;
  21765. case Camera.RIG_MODE_WEBVR:
  21766. if (rigParams.vrDisplay) {
  21767. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  21768. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  21769. //Left eye
  21770. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  21771. this._rigCameras[0].setCameraRigParameter("left", true);
  21772. //leaving this for future reference
  21773. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  21774. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  21775. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  21776. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  21777. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21778. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  21779. this._rigCameras[0].parent = this;
  21780. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  21781. //Right eye
  21782. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  21783. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  21784. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  21785. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  21786. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  21787. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  21788. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  21789. this._rigCameras[1].parent = this;
  21790. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  21791. if (Camera.UseAlternateWebVRRendering) {
  21792. this._rigCameras[1]._skipRendering = true;
  21793. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  21794. }
  21795. }
  21796. break;
  21797. }
  21798. this._cascadePostProcessesToRigCams();
  21799. this.update();
  21800. };
  21801. Camera.prototype._getVRProjectionMatrix = function () {
  21802. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  21803. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  21804. return this._projectionMatrix;
  21805. };
  21806. Camera.prototype._updateCameraRotationMatrix = function () {
  21807. //Here for WebVR
  21808. };
  21809. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  21810. //Here for WebVR
  21811. };
  21812. /**
  21813. * This function MUST be overwritten by the different WebVR cameras available.
  21814. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  21815. */
  21816. Camera.prototype._getWebVRProjectionMatrix = function () {
  21817. return BABYLON.Matrix.Identity();
  21818. };
  21819. /**
  21820. * This function MUST be overwritten by the different WebVR cameras available.
  21821. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  21822. */
  21823. Camera.prototype._getWebVRViewMatrix = function () {
  21824. return BABYLON.Matrix.Identity();
  21825. };
  21826. Camera.prototype.setCameraRigParameter = function (name, value) {
  21827. if (!this._cameraRigParams) {
  21828. this._cameraRigParams = {};
  21829. }
  21830. this._cameraRigParams[name] = value;
  21831. //provisionnally:
  21832. if (name === "interaxialDistance") {
  21833. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  21834. }
  21835. };
  21836. /**
  21837. * needs to be overridden by children so sub has required properties to be copied
  21838. */
  21839. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  21840. return null;
  21841. };
  21842. /**
  21843. * May need to be overridden by children
  21844. */
  21845. Camera.prototype._updateRigCameras = function () {
  21846. for (var i = 0; i < this._rigCameras.length; i++) {
  21847. this._rigCameras[i].minZ = this.minZ;
  21848. this._rigCameras[i].maxZ = this.maxZ;
  21849. this._rigCameras[i].fov = this.fov;
  21850. }
  21851. // only update viewport when ANAGLYPH
  21852. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  21853. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  21854. }
  21855. };
  21856. Camera.prototype._setupInputs = function () {
  21857. };
  21858. Camera.prototype.serialize = function () {
  21859. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21860. // Type
  21861. serializationObject.type = this.getClassName();
  21862. // Parent
  21863. if (this.parent) {
  21864. serializationObject.parentId = this.parent.id;
  21865. }
  21866. if (this.inputs) {
  21867. this.inputs.serialize(serializationObject);
  21868. }
  21869. // Animations
  21870. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21871. serializationObject.ranges = this.serializeAnimationRanges();
  21872. return serializationObject;
  21873. };
  21874. Camera.prototype.clone = function (name) {
  21875. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  21876. };
  21877. Camera.prototype.getDirection = function (localAxis) {
  21878. var result = BABYLON.Vector3.Zero();
  21879. this.getDirectionToRef(localAxis, result);
  21880. return result;
  21881. };
  21882. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  21883. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  21884. };
  21885. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  21886. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  21887. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  21888. switch (type) {
  21889. case "ArcRotateCamera":
  21890. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  21891. case "DeviceOrientationCamera":
  21892. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  21893. case "FollowCamera":
  21894. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  21895. case "ArcFollowCamera":
  21896. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  21897. case "GamepadCamera":
  21898. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  21899. case "TouchCamera":
  21900. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  21901. case "VirtualJoysticksCamera":
  21902. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  21903. case "WebVRFreeCamera":
  21904. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  21905. case "WebVRGamepadCamera":
  21906. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  21907. case "VRDeviceOrientationFreeCamera":
  21908. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  21909. case "VRDeviceOrientationGamepadCamera":
  21910. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  21911. case "AnaglyphArcRotateCamera":
  21912. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  21913. case "AnaglyphFreeCamera":
  21914. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  21915. case "AnaglyphGamepadCamera":
  21916. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  21917. case "AnaglyphUniversalCamera":
  21918. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  21919. case "StereoscopicArcRotateCamera":
  21920. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  21921. case "StereoscopicFreeCamera":
  21922. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  21923. case "StereoscopicGamepadCamera":
  21924. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  21925. case "StereoscopicUniversalCamera":
  21926. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  21927. case "FreeCamera":// Forcing Universal here
  21928. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  21929. default:// Universal Camera is the default value
  21930. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  21931. }
  21932. };
  21933. Camera.prototype.computeWorldMatrix = function () {
  21934. return this.getWorldMatrix();
  21935. };
  21936. Camera.Parse = function (parsedCamera, scene) {
  21937. var type = parsedCamera.type;
  21938. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  21939. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  21940. // Parent
  21941. if (parsedCamera.parentId) {
  21942. camera._waitingParentId = parsedCamera.parentId;
  21943. }
  21944. //If camera has an input manager, let it parse inputs settings
  21945. if (camera.inputs) {
  21946. camera.inputs.parse(parsedCamera);
  21947. camera._setupInputs();
  21948. }
  21949. if (camera.setPosition) {
  21950. camera.position.copyFromFloats(0, 0, 0);
  21951. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  21952. }
  21953. // Target
  21954. if (parsedCamera.target) {
  21955. if (camera.setTarget) {
  21956. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  21957. }
  21958. }
  21959. // Apply 3d rig, when found
  21960. if (parsedCamera.cameraRigMode) {
  21961. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  21962. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  21963. }
  21964. // Animations
  21965. if (parsedCamera.animations) {
  21966. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  21967. var parsedAnimation = parsedCamera.animations[animationIndex];
  21968. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21969. }
  21970. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  21971. }
  21972. if (parsedCamera.autoAnimate) {
  21973. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  21974. }
  21975. return camera;
  21976. };
  21977. // Statics
  21978. Camera._PERSPECTIVE_CAMERA = 0;
  21979. Camera._ORTHOGRAPHIC_CAMERA = 1;
  21980. Camera._FOVMODE_VERTICAL_FIXED = 0;
  21981. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  21982. Camera._RIG_MODE_NONE = 0;
  21983. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  21984. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  21985. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  21986. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  21987. Camera._RIG_MODE_VR = 20;
  21988. Camera._RIG_MODE_WEBVR = 21;
  21989. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  21990. Camera.UseAlternateWebVRRendering = false;
  21991. __decorate([
  21992. BABYLON.serializeAsVector3()
  21993. ], Camera.prototype, "position", void 0);
  21994. __decorate([
  21995. BABYLON.serializeAsVector3()
  21996. ], Camera.prototype, "upVector", void 0);
  21997. __decorate([
  21998. BABYLON.serialize()
  21999. ], Camera.prototype, "orthoLeft", void 0);
  22000. __decorate([
  22001. BABYLON.serialize()
  22002. ], Camera.prototype, "orthoRight", void 0);
  22003. __decorate([
  22004. BABYLON.serialize()
  22005. ], Camera.prototype, "orthoBottom", void 0);
  22006. __decorate([
  22007. BABYLON.serialize()
  22008. ], Camera.prototype, "orthoTop", void 0);
  22009. __decorate([
  22010. BABYLON.serialize()
  22011. ], Camera.prototype, "fov", void 0);
  22012. __decorate([
  22013. BABYLON.serialize()
  22014. ], Camera.prototype, "minZ", void 0);
  22015. __decorate([
  22016. BABYLON.serialize()
  22017. ], Camera.prototype, "maxZ", void 0);
  22018. __decorate([
  22019. BABYLON.serialize()
  22020. ], Camera.prototype, "inertia", void 0);
  22021. __decorate([
  22022. BABYLON.serialize()
  22023. ], Camera.prototype, "mode", void 0);
  22024. __decorate([
  22025. BABYLON.serialize()
  22026. ], Camera.prototype, "layerMask", void 0);
  22027. __decorate([
  22028. BABYLON.serialize()
  22029. ], Camera.prototype, "fovMode", void 0);
  22030. __decorate([
  22031. BABYLON.serialize()
  22032. ], Camera.prototype, "cameraRigMode", void 0);
  22033. __decorate([
  22034. BABYLON.serialize()
  22035. ], Camera.prototype, "interaxialDistance", void 0);
  22036. __decorate([
  22037. BABYLON.serialize()
  22038. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22039. return Camera;
  22040. }(BABYLON.Node));
  22041. BABYLON.Camera = Camera;
  22042. })(BABYLON || (BABYLON = {}));
  22043. //# sourceMappingURL=babylon.camera.js.map
  22044. "use strict";
  22045. var BABYLON;
  22046. (function (BABYLON) {
  22047. var RenderingManager = /** @class */ (function () {
  22048. function RenderingManager(scene) {
  22049. this._renderingGroups = new Array();
  22050. this._autoClearDepthStencil = {};
  22051. this._customOpaqueSortCompareFn = {};
  22052. this._customAlphaTestSortCompareFn = {};
  22053. this._customTransparentSortCompareFn = {};
  22054. this._renderinGroupInfo = null;
  22055. this._scene = scene;
  22056. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22057. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22058. }
  22059. }
  22060. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22061. if (depth === void 0) { depth = true; }
  22062. if (stencil === void 0) { stencil = true; }
  22063. if (this._depthStencilBufferAlreadyCleaned) {
  22064. return;
  22065. }
  22066. this._scene.getEngine().clear(null, false, depth, stencil);
  22067. this._depthStencilBufferAlreadyCleaned = true;
  22068. };
  22069. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22070. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22071. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22072. var info = null;
  22073. if (observable) {
  22074. if (!this._renderinGroupInfo) {
  22075. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22076. }
  22077. info = this._renderinGroupInfo;
  22078. info.scene = this._scene;
  22079. info.camera = this._scene.activeCamera;
  22080. }
  22081. // Dispatch sprites
  22082. if (renderSprites) {
  22083. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22084. var manager = this._scene.spriteManagers[index];
  22085. this.dispatchSprites(manager);
  22086. }
  22087. }
  22088. // Render
  22089. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22090. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22091. var renderingGroup = this._renderingGroups[index];
  22092. if (!renderingGroup && !observable)
  22093. continue;
  22094. var renderingGroupMask = 0;
  22095. // Fire PRECLEAR stage
  22096. if (observable && info) {
  22097. renderingGroupMask = Math.pow(2, index);
  22098. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22099. info.renderingGroupId = index;
  22100. observable.notifyObservers(info, renderingGroupMask);
  22101. }
  22102. // Clear depth/stencil if needed
  22103. if (RenderingManager.AUTOCLEAR) {
  22104. var autoClear = this._autoClearDepthStencil[index];
  22105. if (autoClear && autoClear.autoClear) {
  22106. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22107. }
  22108. }
  22109. if (observable && info) {
  22110. // Fire PREOPAQUE stage
  22111. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22112. observable.notifyObservers(info, renderingGroupMask);
  22113. // Fire PRETRANSPARENT stage
  22114. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22115. observable.notifyObservers(info, renderingGroupMask);
  22116. }
  22117. if (renderingGroup)
  22118. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22119. // Fire POSTTRANSPARENT stage
  22120. if (observable && info) {
  22121. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22122. observable.notifyObservers(info, renderingGroupMask);
  22123. }
  22124. }
  22125. };
  22126. RenderingManager.prototype.reset = function () {
  22127. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22128. var renderingGroup = this._renderingGroups[index];
  22129. if (renderingGroup) {
  22130. renderingGroup.prepare();
  22131. }
  22132. }
  22133. };
  22134. RenderingManager.prototype.dispose = function () {
  22135. this.freeRenderingGroups();
  22136. this._renderingGroups.length = 0;
  22137. };
  22138. /**
  22139. * Clear the info related to rendering groups preventing retention points during dispose.
  22140. */
  22141. RenderingManager.prototype.freeRenderingGroups = function () {
  22142. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22143. var renderingGroup = this._renderingGroups[index];
  22144. if (renderingGroup) {
  22145. renderingGroup.dispose();
  22146. }
  22147. }
  22148. };
  22149. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22150. if (this._renderingGroups[renderingGroupId] === undefined) {
  22151. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22152. }
  22153. };
  22154. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22155. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22156. this._prepareRenderingGroup(renderingGroupId);
  22157. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22158. };
  22159. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22160. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22161. this._prepareRenderingGroup(renderingGroupId);
  22162. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22163. };
  22164. /**
  22165. * @param subMesh The submesh to dispatch
  22166. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22167. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22168. */
  22169. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22170. if (mesh === undefined) {
  22171. mesh = subMesh.getMesh();
  22172. }
  22173. var renderingGroupId = mesh.renderingGroupId || 0;
  22174. this._prepareRenderingGroup(renderingGroupId);
  22175. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22176. };
  22177. /**
  22178. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22179. * This allowed control for front to back rendering or reversly depending of the special needs.
  22180. *
  22181. * @param renderingGroupId The rendering group id corresponding to its index
  22182. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22183. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22184. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22185. */
  22186. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22187. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22188. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22189. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22190. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22191. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22192. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22193. if (this._renderingGroups[renderingGroupId]) {
  22194. var group = this._renderingGroups[renderingGroupId];
  22195. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22196. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22197. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22198. }
  22199. };
  22200. /**
  22201. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22202. *
  22203. * @param renderingGroupId The rendering group id corresponding to its index
  22204. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22205. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22206. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22207. */
  22208. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22209. if (depth === void 0) { depth = true; }
  22210. if (stencil === void 0) { stencil = true; }
  22211. this._autoClearDepthStencil[renderingGroupId] = {
  22212. autoClear: autoClearDepthStencil,
  22213. depth: depth,
  22214. stencil: stencil
  22215. };
  22216. };
  22217. /**
  22218. * The max id used for rendering groups (not included)
  22219. */
  22220. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22221. /**
  22222. * The min id used for rendering groups (included)
  22223. */
  22224. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22225. /**
  22226. * Used to globally prevent autoclearing scenes.
  22227. */
  22228. RenderingManager.AUTOCLEAR = true;
  22229. return RenderingManager;
  22230. }());
  22231. BABYLON.RenderingManager = RenderingManager;
  22232. })(BABYLON || (BABYLON = {}));
  22233. //# sourceMappingURL=babylon.renderingManager.js.map
  22234. "use strict";
  22235. var BABYLON;
  22236. (function (BABYLON) {
  22237. var RenderingGroup = /** @class */ (function () {
  22238. /**
  22239. * Creates a new rendering group.
  22240. * @param index The rendering group index
  22241. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22242. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22243. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22244. */
  22245. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22246. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22247. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22248. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22249. this.index = index;
  22250. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22251. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22252. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22253. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22254. this._particleSystems = new BABYLON.SmartArray(256);
  22255. this._spriteManagers = new BABYLON.SmartArray(256);
  22256. this._edgesRenderers = new BABYLON.SmartArray(16);
  22257. this._scene = scene;
  22258. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22259. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22260. this.transparentSortCompareFn = transparentSortCompareFn;
  22261. }
  22262. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22263. /**
  22264. * Set the opaque sort comparison function.
  22265. * If null the sub meshes will be render in the order they were created
  22266. */
  22267. set: function (value) {
  22268. this._opaqueSortCompareFn = value;
  22269. if (value) {
  22270. this._renderOpaque = this.renderOpaqueSorted;
  22271. }
  22272. else {
  22273. this._renderOpaque = RenderingGroup.renderUnsorted;
  22274. }
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22280. /**
  22281. * Set the alpha test sort comparison function.
  22282. * If null the sub meshes will be render in the order they were created
  22283. */
  22284. set: function (value) {
  22285. this._alphaTestSortCompareFn = value;
  22286. if (value) {
  22287. this._renderAlphaTest = this.renderAlphaTestSorted;
  22288. }
  22289. else {
  22290. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22291. }
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22297. /**
  22298. * Set the transparent sort comparison function.
  22299. * If null the sub meshes will be render in the order they were created
  22300. */
  22301. set: function (value) {
  22302. if (value) {
  22303. this._transparentSortCompareFn = value;
  22304. }
  22305. else {
  22306. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22307. }
  22308. this._renderTransparent = this.renderTransparentSorted;
  22309. },
  22310. enumerable: true,
  22311. configurable: true
  22312. });
  22313. /**
  22314. * Render all the sub meshes contained in the group.
  22315. * @param customRenderFunction Used to override the default render behaviour of the group.
  22316. * @returns true if rendered some submeshes.
  22317. */
  22318. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22319. if (customRenderFunction) {
  22320. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22321. return;
  22322. }
  22323. var engine = this._scene.getEngine();
  22324. // Depth only
  22325. if (this._depthOnlySubMeshes.length !== 0) {
  22326. engine.setColorWrite(false);
  22327. this._renderAlphaTest(this._depthOnlySubMeshes);
  22328. engine.setColorWrite(true);
  22329. }
  22330. // Opaque
  22331. if (this._opaqueSubMeshes.length !== 0) {
  22332. this._renderOpaque(this._opaqueSubMeshes);
  22333. }
  22334. // Alpha test
  22335. if (this._alphaTestSubMeshes.length !== 0) {
  22336. this._renderAlphaTest(this._alphaTestSubMeshes);
  22337. }
  22338. var stencilState = engine.getStencilBuffer();
  22339. engine.setStencilBuffer(false);
  22340. // Sprites
  22341. if (renderSprites) {
  22342. this._renderSprites();
  22343. }
  22344. // Particles
  22345. if (renderParticles) {
  22346. this._renderParticles(activeMeshes);
  22347. }
  22348. if (this.onBeforeTransparentRendering) {
  22349. this.onBeforeTransparentRendering();
  22350. }
  22351. // Transparent
  22352. if (this._transparentSubMeshes.length !== 0) {
  22353. this._renderTransparent(this._transparentSubMeshes);
  22354. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22355. }
  22356. // Set back stencil to false in case it changes before the edge renderer.
  22357. engine.setStencilBuffer(false);
  22358. // Edges
  22359. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22360. this._edgesRenderers.data[edgesRendererIndex].render();
  22361. }
  22362. // Restore Stencil state.
  22363. engine.setStencilBuffer(stencilState);
  22364. };
  22365. /**
  22366. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22367. * @param subMeshes The submeshes to render
  22368. */
  22369. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22370. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22371. };
  22372. /**
  22373. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22374. * @param subMeshes The submeshes to render
  22375. */
  22376. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22377. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22378. };
  22379. /**
  22380. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22381. * @param subMeshes The submeshes to render
  22382. */
  22383. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22384. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22385. };
  22386. /**
  22387. * Renders the submeshes in a specified order.
  22388. * @param subMeshes The submeshes to sort before render
  22389. * @param sortCompareFn The comparison function use to sort
  22390. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22391. * @param transparent Specifies to activate blending if true
  22392. */
  22393. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22394. var subIndex = 0;
  22395. var subMesh;
  22396. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22397. for (; subIndex < subMeshes.length; subIndex++) {
  22398. subMesh = subMeshes.data[subIndex];
  22399. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22400. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22401. }
  22402. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22403. if (sortCompareFn) {
  22404. sortedArray.sort(sortCompareFn);
  22405. }
  22406. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22407. subMesh = sortedArray[subIndex];
  22408. if (transparent) {
  22409. var material = subMesh.getMaterial();
  22410. if (material && material.needDepthPrePass) {
  22411. var engine = material.getScene().getEngine();
  22412. engine.setColorWrite(false);
  22413. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22414. subMesh.render(false);
  22415. engine.setColorWrite(true);
  22416. }
  22417. }
  22418. subMesh.render(transparent);
  22419. }
  22420. };
  22421. /**
  22422. * Renders the submeshes in the order they were dispatched (no sort applied).
  22423. * @param subMeshes The submeshes to render
  22424. */
  22425. RenderingGroup.renderUnsorted = function (subMeshes) {
  22426. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22427. var submesh = subMeshes.data[subIndex];
  22428. submesh.render(false);
  22429. }
  22430. };
  22431. /**
  22432. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22433. * are rendered back to front if in the same alpha index.
  22434. *
  22435. * @param a The first submesh
  22436. * @param b The second submesh
  22437. * @returns The result of the comparison
  22438. */
  22439. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22440. // Alpha index first
  22441. if (a._alphaIndex > b._alphaIndex) {
  22442. return 1;
  22443. }
  22444. if (a._alphaIndex < b._alphaIndex) {
  22445. return -1;
  22446. }
  22447. // Then distance to camera
  22448. return RenderingGroup.backToFrontSortCompare(a, b);
  22449. };
  22450. /**
  22451. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22452. * are rendered back to front.
  22453. *
  22454. * @param a The first submesh
  22455. * @param b The second submesh
  22456. * @returns The result of the comparison
  22457. */
  22458. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22459. // Then distance to camera
  22460. if (a._distanceToCamera < b._distanceToCamera) {
  22461. return 1;
  22462. }
  22463. if (a._distanceToCamera > b._distanceToCamera) {
  22464. return -1;
  22465. }
  22466. return 0;
  22467. };
  22468. /**
  22469. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22470. * are rendered front to back (prevent overdraw).
  22471. *
  22472. * @param a The first submesh
  22473. * @param b The second submesh
  22474. * @returns The result of the comparison
  22475. */
  22476. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22477. // Then distance to camera
  22478. if (a._distanceToCamera < b._distanceToCamera) {
  22479. return -1;
  22480. }
  22481. if (a._distanceToCamera > b._distanceToCamera) {
  22482. return 1;
  22483. }
  22484. return 0;
  22485. };
  22486. /**
  22487. * Resets the different lists of submeshes to prepare a new frame.
  22488. */
  22489. RenderingGroup.prototype.prepare = function () {
  22490. this._opaqueSubMeshes.reset();
  22491. this._transparentSubMeshes.reset();
  22492. this._alphaTestSubMeshes.reset();
  22493. this._depthOnlySubMeshes.reset();
  22494. this._particleSystems.reset();
  22495. this._spriteManagers.reset();
  22496. this._edgesRenderers.reset();
  22497. };
  22498. RenderingGroup.prototype.dispose = function () {
  22499. this._opaqueSubMeshes.dispose();
  22500. this._transparentSubMeshes.dispose();
  22501. this._alphaTestSubMeshes.dispose();
  22502. this._depthOnlySubMeshes.dispose();
  22503. this._particleSystems.dispose();
  22504. this._spriteManagers.dispose();
  22505. this._edgesRenderers.dispose();
  22506. };
  22507. /**
  22508. * Inserts the submesh in its correct queue depending on its material.
  22509. * @param subMesh The submesh to dispatch
  22510. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22511. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22512. */
  22513. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  22514. // Get mesh and materials if not provided
  22515. if (mesh === undefined) {
  22516. mesh = subMesh.getMesh();
  22517. }
  22518. if (material === undefined) {
  22519. material = subMesh.getMaterial();
  22520. }
  22521. if (material === null || material === undefined) {
  22522. return;
  22523. }
  22524. if (material.needAlphaBlendingForMesh(mesh)) {
  22525. this._transparentSubMeshes.push(subMesh);
  22526. }
  22527. else if (material.needAlphaTesting()) {
  22528. if (material.needDepthPrePass) {
  22529. this._depthOnlySubMeshes.push(subMesh);
  22530. }
  22531. this._alphaTestSubMeshes.push(subMesh);
  22532. }
  22533. else {
  22534. if (material.needDepthPrePass) {
  22535. this._depthOnlySubMeshes.push(subMesh);
  22536. }
  22537. this._opaqueSubMeshes.push(subMesh); // Opaque
  22538. }
  22539. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  22540. this._edgesRenderers.push(mesh._edgesRenderer);
  22541. }
  22542. };
  22543. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  22544. this._spriteManagers.push(spriteManager);
  22545. };
  22546. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  22547. this._particleSystems.push(particleSystem);
  22548. };
  22549. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  22550. if (this._particleSystems.length === 0) {
  22551. return;
  22552. }
  22553. // Particles
  22554. var activeCamera = this._scene.activeCamera;
  22555. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  22556. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  22557. var particleSystem = this._particleSystems.data[particleIndex];
  22558. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  22559. continue;
  22560. }
  22561. var emitter = particleSystem.emitter;
  22562. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  22563. this._scene._activeParticles.addCount(particleSystem.render(), false);
  22564. }
  22565. }
  22566. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  22567. };
  22568. RenderingGroup.prototype._renderSprites = function () {
  22569. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  22570. return;
  22571. }
  22572. // Sprites
  22573. var activeCamera = this._scene.activeCamera;
  22574. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  22575. for (var id = 0; id < this._spriteManagers.length; id++) {
  22576. var spriteManager = this._spriteManagers.data[id];
  22577. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  22578. spriteManager.render();
  22579. }
  22580. }
  22581. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  22582. };
  22583. return RenderingGroup;
  22584. }());
  22585. BABYLON.RenderingGroup = RenderingGroup;
  22586. })(BABYLON || (BABYLON = {}));
  22587. //# sourceMappingURL=babylon.renderingGroup.js.map
  22588. "use strict";
  22589. var BABYLON;
  22590. (function (BABYLON) {
  22591. /** @ignore */
  22592. var ClickInfo = /** @class */ (function () {
  22593. function ClickInfo() {
  22594. this._singleClick = false;
  22595. this._doubleClick = false;
  22596. this._hasSwiped = false;
  22597. this._ignore = false;
  22598. }
  22599. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  22600. get: function () {
  22601. return this._singleClick;
  22602. },
  22603. set: function (b) {
  22604. this._singleClick = b;
  22605. },
  22606. enumerable: true,
  22607. configurable: true
  22608. });
  22609. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  22610. get: function () {
  22611. return this._doubleClick;
  22612. },
  22613. set: function (b) {
  22614. this._doubleClick = b;
  22615. },
  22616. enumerable: true,
  22617. configurable: true
  22618. });
  22619. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  22620. get: function () {
  22621. return this._hasSwiped;
  22622. },
  22623. set: function (b) {
  22624. this._hasSwiped = b;
  22625. },
  22626. enumerable: true,
  22627. configurable: true
  22628. });
  22629. Object.defineProperty(ClickInfo.prototype, "ignore", {
  22630. get: function () {
  22631. return this._ignore;
  22632. },
  22633. set: function (b) {
  22634. this._ignore = b;
  22635. },
  22636. enumerable: true,
  22637. configurable: true
  22638. });
  22639. return ClickInfo;
  22640. }());
  22641. /**
  22642. * This class is used by the onRenderingGroupObservable
  22643. */
  22644. var RenderingGroupInfo = /** @class */ (function () {
  22645. function RenderingGroupInfo() {
  22646. }
  22647. /**
  22648. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  22649. * This stage will be fired no matter what
  22650. */
  22651. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  22652. /**
  22653. * Called before opaque object are rendered.
  22654. * This stage will be fired only if there's 3D Opaque content to render
  22655. */
  22656. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  22657. /**
  22658. * Called after the opaque objects are rendered and before the transparent ones
  22659. * This stage will be fired only if there's 3D transparent content to render
  22660. */
  22661. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  22662. /**
  22663. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  22664. * This stage will be fired no matter what
  22665. */
  22666. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  22667. return RenderingGroupInfo;
  22668. }());
  22669. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  22670. /**
  22671. * Represents a scene to be rendered by the engine.
  22672. * @see http://doc.babylonjs.com/features/scene
  22673. */
  22674. var Scene = /** @class */ (function () {
  22675. /**
  22676. * Creates a new Scene
  22677. * @param engine defines the engine to use to render this scene
  22678. */
  22679. function Scene(engine) {
  22680. // Members
  22681. /**
  22682. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  22683. */
  22684. this.autoClear = true;
  22685. /**
  22686. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  22687. */
  22688. this.autoClearDepthAndStencil = true;
  22689. /**
  22690. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  22691. */
  22692. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  22693. /**
  22694. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  22695. */
  22696. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22697. this._forceWireframe = false;
  22698. this._forcePointsCloud = false;
  22699. /**
  22700. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  22701. */
  22702. this.forceShowBoundingBoxes = false;
  22703. /**
  22704. * Gets or sets a boolean indicating if animations are enabled
  22705. */
  22706. this.animationsEnabled = true;
  22707. /**
  22708. * Gets or sets a boolean indicating if a constant deltatime has to be used
  22709. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  22710. */
  22711. this.useConstantAnimationDeltaTime = false;
  22712. /**
  22713. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  22714. * Please note that it requires to run a ray cast through the scene on every frame
  22715. */
  22716. this.constantlyUpdateMeshUnderPointer = false;
  22717. /**
  22718. * Defines the HTML cursor to use when hovering over interactive elements
  22719. */
  22720. this.hoverCursor = "pointer";
  22721. /**
  22722. * Defines the HTML default cursor to use (empty by default)
  22723. */
  22724. this.defaultCursor = "";
  22725. /**
  22726. * This is used to call preventDefault() on pointer down
  22727. * in order to block unwanted artifacts like system double clicks
  22728. */
  22729. this.preventDefaultOnPointerDown = true;
  22730. // Metadata
  22731. /**
  22732. * Gets or sets user defined metadata
  22733. */
  22734. this.metadata = null;
  22735. /**
  22736. * Use this array to add regular expressions used to disable offline support for specific urls
  22737. */
  22738. this.disableOfflineSupportExceptionRules = new Array();
  22739. /**
  22740. * An event triggered when the scene is disposed.
  22741. */
  22742. this.onDisposeObservable = new BABYLON.Observable();
  22743. this._onDisposeObserver = null;
  22744. /**
  22745. * An event triggered before rendering the scene (right after animations and physics)
  22746. */
  22747. this.onBeforeRenderObservable = new BABYLON.Observable();
  22748. this._onBeforeRenderObserver = null;
  22749. /**
  22750. * An event triggered after rendering the scene
  22751. */
  22752. this.onAfterRenderObservable = new BABYLON.Observable();
  22753. this._onAfterRenderObserver = null;
  22754. /**
  22755. * An event triggered before animating the scene
  22756. */
  22757. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  22758. /**
  22759. * An event triggered after animations processing
  22760. */
  22761. this.onAfterAnimationsObservable = new BABYLON.Observable();
  22762. /**
  22763. * An event triggered before draw calls are ready to be sent
  22764. */
  22765. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  22766. /**
  22767. * An event triggered after draw calls have been sent
  22768. */
  22769. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  22770. /**
  22771. * An event triggered when physic simulation is about to be run
  22772. */
  22773. this.onBeforePhysicsObservable = new BABYLON.Observable();
  22774. /**
  22775. * An event triggered when physic simulation has been done
  22776. */
  22777. this.onAfterPhysicsObservable = new BABYLON.Observable();
  22778. /**
  22779. * An event triggered when the scene is ready
  22780. */
  22781. this.onReadyObservable = new BABYLON.Observable();
  22782. /**
  22783. * An event triggered before rendering a camera
  22784. */
  22785. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  22786. this._onBeforeCameraRenderObserver = null;
  22787. /**
  22788. * An event triggered after rendering a camera
  22789. */
  22790. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  22791. this._onAfterCameraRenderObserver = null;
  22792. /**
  22793. * An event triggered when active meshes evaluation is about to start
  22794. */
  22795. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  22796. /**
  22797. * An event triggered when active meshes evaluation is done
  22798. */
  22799. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  22800. /**
  22801. * An event triggered when particles rendering is about to start
  22802. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  22803. */
  22804. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  22805. /**
  22806. * An event triggered when particles rendering is done
  22807. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  22808. */
  22809. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  22810. /**
  22811. * An event triggered when sprites rendering is about to start
  22812. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  22813. */
  22814. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  22815. /**
  22816. * An event triggered when sprites rendering is done
  22817. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  22818. */
  22819. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  22820. /**
  22821. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  22822. */
  22823. this.onDataLoadedObservable = new BABYLON.Observable();
  22824. /**
  22825. * An event triggered when a camera is created
  22826. */
  22827. this.onNewCameraAddedObservable = new BABYLON.Observable();
  22828. /**
  22829. * An event triggered when a camera is removed
  22830. */
  22831. this.onCameraRemovedObservable = new BABYLON.Observable();
  22832. /**
  22833. * An event triggered when a light is created
  22834. */
  22835. this.onNewLightAddedObservable = new BABYLON.Observable();
  22836. /**
  22837. * An event triggered when a light is removed
  22838. */
  22839. this.onLightRemovedObservable = new BABYLON.Observable();
  22840. /**
  22841. * An event triggered when a geometry is created
  22842. */
  22843. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  22844. /**
  22845. * An event triggered when a geometry is removed
  22846. */
  22847. this.onGeometryRemovedObservable = new BABYLON.Observable();
  22848. /**
  22849. * An event triggered when a transform node is created
  22850. */
  22851. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  22852. /**
  22853. * An event triggered when a transform node is removed
  22854. */
  22855. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  22856. /**
  22857. * An event triggered when a mesh is created
  22858. */
  22859. this.onNewMeshAddedObservable = new BABYLON.Observable();
  22860. /**
  22861. * An event triggered when a mesh is removed
  22862. */
  22863. this.onMeshRemovedObservable = new BABYLON.Observable();
  22864. /**
  22865. * An event triggered when render targets are about to be rendered
  22866. * Can happen multiple times per frame.
  22867. */
  22868. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  22869. /**
  22870. * An event triggered when render targets were rendered.
  22871. * Can happen multiple times per frame.
  22872. */
  22873. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  22874. /**
  22875. * An event triggered before calculating deterministic simulation step
  22876. */
  22877. this.onBeforeStepObservable = new BABYLON.Observable();
  22878. /**
  22879. * An event triggered after calculating deterministic simulation step
  22880. */
  22881. this.onAfterStepObservable = new BABYLON.Observable();
  22882. /**
  22883. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  22884. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  22885. * 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)
  22886. */
  22887. this.onRenderingGroupObservable = new BABYLON.Observable();
  22888. // Animations
  22889. /**
  22890. * Gets a list of Animations associated with the scene
  22891. */
  22892. this.animations = [];
  22893. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  22894. /**
  22895. * 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).
  22896. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  22897. */
  22898. this.onPrePointerObservable = new BABYLON.Observable();
  22899. /**
  22900. * Observable event triggered each time an input event is received from the rendering canvas
  22901. */
  22902. this.onPointerObservable = new BABYLON.Observable();
  22903. this._meshPickProceed = false;
  22904. this._currentPickResult = null;
  22905. this._previousPickResult = null;
  22906. this._totalPointersPressed = 0;
  22907. this._doubleClickOccured = false;
  22908. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  22909. this.cameraToUseForPointers = null;
  22910. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  22911. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  22912. this._startingPointerTime = 0;
  22913. this._previousStartingPointerTime = 0;
  22914. // Deterministic lockstep
  22915. this._timeAccumulator = 0;
  22916. this._currentStepId = 0;
  22917. this._currentInternalStep = 0;
  22918. // Keyboard
  22919. /**
  22920. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  22921. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  22922. */
  22923. this.onPreKeyboardObservable = new BABYLON.Observable();
  22924. /**
  22925. * Observable event triggered each time an keyboard event is received from the hosting window
  22926. */
  22927. this.onKeyboardObservable = new BABYLON.Observable();
  22928. // Coordinates system
  22929. this._useRightHandedSystem = false;
  22930. // Fog
  22931. this._fogEnabled = true;
  22932. this._fogMode = Scene.FOGMODE_NONE;
  22933. /**
  22934. * Gets or sets the fog color to use
  22935. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22936. */
  22937. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  22938. /**
  22939. * Gets or sets the fog density to use
  22940. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22941. */
  22942. this.fogDensity = 0.1;
  22943. /**
  22944. * Gets or sets the fog start distance to use
  22945. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22946. */
  22947. this.fogStart = 0;
  22948. /**
  22949. * Gets or sets the fog end distance to use
  22950. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22951. */
  22952. this.fogEnd = 1000.0;
  22953. // Lights
  22954. this._shadowsEnabled = true;
  22955. this._lightsEnabled = true;
  22956. /**
  22957. * All of the lights added to this scene
  22958. * @see http://doc.babylonjs.com/babylon101/lights
  22959. */
  22960. this.lights = new Array();
  22961. // Cameras
  22962. /** All of the cameras added to this scene.
  22963. * @see http://doc.babylonjs.com/babylon101/cameras
  22964. */
  22965. this.cameras = new Array();
  22966. /** All of the active cameras added to this scene. */
  22967. this.activeCameras = new Array();
  22968. // Meshes
  22969. /**
  22970. * All of the tranform nodes added to this scene
  22971. * @see http://doc.babylonjs.com/how_to/transformnode
  22972. */
  22973. this.transformNodes = new Array();
  22974. /**
  22975. * All of the (abstract) meshes added to this scene
  22976. */
  22977. this.meshes = new Array();
  22978. /**
  22979. * All of the animation groups added to this scene
  22980. * @see http://doc.babylonjs.com/how_to/group
  22981. */
  22982. this.animationGroups = new Array();
  22983. // Geometries
  22984. this._geometries = new Array();
  22985. /**
  22986. * All of the materials added to this scene
  22987. * @see http://doc.babylonjs.com/babylon101/materials
  22988. */
  22989. this.materials = new Array();
  22990. /**
  22991. * All of the multi-materials added to this scene
  22992. * @see http://doc.babylonjs.com/how_to/multi_materials
  22993. */
  22994. this.multiMaterials = new Array();
  22995. // Textures
  22996. this._texturesEnabled = true;
  22997. /**
  22998. * All of the textures added to this scene
  22999. */
  23000. this.textures = new Array();
  23001. // Particles
  23002. /**
  23003. * Gets or sets a boolean indicating if particles are enabled on this scene
  23004. */
  23005. this.particlesEnabled = true;
  23006. /**
  23007. * All of the particle systems added to this scene
  23008. * @see http://doc.babylonjs.com/babylon101/particles
  23009. */
  23010. this.particleSystems = new Array();
  23011. // Sprites
  23012. /**
  23013. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23014. */
  23015. this.spritesEnabled = true;
  23016. /**
  23017. * All of the sprite managers added to this scene
  23018. * @see http://doc.babylonjs.com/babylon101/sprites
  23019. */
  23020. this.spriteManagers = new Array();
  23021. /**
  23022. * The list of layers (background and foreground) of the scene
  23023. */
  23024. this.layers = new Array();
  23025. /**
  23026. * The list of effect layers (highlights/glow) added to the scene
  23027. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23028. * @see http://doc.babylonjs.com/how_to/glow_layer
  23029. */
  23030. this.effectLayers = new Array();
  23031. // Skeletons
  23032. this._skeletonsEnabled = true;
  23033. /**
  23034. * The list of skeletons added to the scene
  23035. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23036. */
  23037. this.skeletons = new Array();
  23038. // Morph targets
  23039. /**
  23040. * The list of morph target managers added to the scene
  23041. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23042. */
  23043. this.morphTargetManagers = new Array();
  23044. // Lens flares
  23045. /**
  23046. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23047. */
  23048. this.lensFlaresEnabled = true;
  23049. /**
  23050. * The list of lens flare system added to the scene
  23051. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23052. */
  23053. this.lensFlareSystems = new Array();
  23054. // Collisions
  23055. /**
  23056. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23057. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23058. */
  23059. this.collisionsEnabled = true;
  23060. /**
  23061. * Defines the gravity applied to this scene (used only for collisions)
  23062. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23063. */
  23064. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23065. // Postprocesses
  23066. /**
  23067. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23068. */
  23069. this.postProcessesEnabled = true;
  23070. /**
  23071. * The list of postprocesses added to the scene
  23072. */
  23073. this.postProcesses = new Array();
  23074. // Customs render targets
  23075. /**
  23076. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23077. */
  23078. this.renderTargetsEnabled = true;
  23079. /**
  23080. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23081. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23082. */
  23083. this.dumpNextRenderTargets = false;
  23084. /**
  23085. * The list of user defined render targets added to the scene
  23086. */
  23087. this.customRenderTargets = new Array();
  23088. /**
  23089. * Gets the list of meshes imported to the scene through SceneLoader
  23090. */
  23091. this.importedMeshesFiles = new Array();
  23092. // Probes
  23093. /**
  23094. * Gets or sets a boolean indicating if probes are enabled on this scene
  23095. */
  23096. this.probesEnabled = true;
  23097. /**
  23098. * The list of reflection probes added to the scene
  23099. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23100. */
  23101. this.reflectionProbes = new Array();
  23102. /** @ignore */
  23103. this._actionManagers = new Array();
  23104. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23105. // Procedural textures
  23106. /**
  23107. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23108. */
  23109. this.proceduralTexturesEnabled = true;
  23110. /**
  23111. * The list of procedural textures added to the scene
  23112. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23113. */
  23114. this.proceduralTextures = new Array();
  23115. /**
  23116. * The list of sound tracks added to the scene
  23117. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23118. */
  23119. this.soundTracks = new Array();
  23120. this._audioEnabled = true;
  23121. this._headphone = false;
  23122. // Performance counters
  23123. this._totalVertices = new BABYLON.PerfCounter();
  23124. /** @ignore */
  23125. this._activeIndices = new BABYLON.PerfCounter();
  23126. /** @ignore */
  23127. this._activeParticles = new BABYLON.PerfCounter();
  23128. /** @ignore */
  23129. this._activeBones = new BABYLON.PerfCounter();
  23130. this._animationTime = 0;
  23131. /**
  23132. * Gets or sets a general scale for animation speed
  23133. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23134. */
  23135. this.animationTimeScale = 1;
  23136. this._renderId = 0;
  23137. this._executeWhenReadyTimeoutId = -1;
  23138. this._intermediateRendering = false;
  23139. this._viewUpdateFlag = -1;
  23140. this._projectionUpdateFlag = -1;
  23141. this._alternateViewUpdateFlag = -1;
  23142. this._alternateProjectionUpdateFlag = -1;
  23143. /** @ignore */
  23144. this._toBeDisposed = new BABYLON.SmartArray(256);
  23145. this._activeRequests = new Array();
  23146. this._pendingData = new Array();
  23147. this._isDisposed = false;
  23148. /**
  23149. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23150. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23151. */
  23152. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23153. this._activeMeshes = new BABYLON.SmartArray(256);
  23154. this._processedMaterials = new BABYLON.SmartArray(256);
  23155. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23156. /** @ignore */
  23157. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23158. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23159. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23160. /** @ignore */
  23161. this._activeAnimatables = new Array();
  23162. this._transformMatrix = BABYLON.Matrix.Zero();
  23163. this._useAlternateCameraConfiguration = false;
  23164. this._alternateRendering = false;
  23165. /**
  23166. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23167. * This is useful if there are more lights that the maximum simulteanous authorized
  23168. */
  23169. this.requireLightSorting = false;
  23170. this._depthRenderer = {};
  23171. this._activeMeshesFrozen = false;
  23172. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23173. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23174. this._engine.scenes.push(this);
  23175. this._uid = null;
  23176. this._renderingManager = new BABYLON.RenderingManager(this);
  23177. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23178. if (BABYLON.OutlineRenderer) {
  23179. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23180. }
  23181. if (BABYLON.Tools.IsWindowObjectExist()) {
  23182. this.attachControl();
  23183. }
  23184. //simplification queue
  23185. if (BABYLON.SimplificationQueue) {
  23186. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23187. }
  23188. //collision coordinator initialization. For now legacy per default.
  23189. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23190. // Uniform Buffer
  23191. this._createUbo();
  23192. // Default Image processing definition.
  23193. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23194. }
  23195. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23196. /** The fog is deactivated */
  23197. get: function () {
  23198. return Scene._FOGMODE_NONE;
  23199. },
  23200. enumerable: true,
  23201. configurable: true
  23202. });
  23203. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23204. /** The fog density is following an exponential function */
  23205. get: function () {
  23206. return Scene._FOGMODE_EXP;
  23207. },
  23208. enumerable: true,
  23209. configurable: true
  23210. });
  23211. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23212. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23213. get: function () {
  23214. return Scene._FOGMODE_EXP2;
  23215. },
  23216. enumerable: true,
  23217. configurable: true
  23218. });
  23219. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23220. /** The fog density is following a linear function. */
  23221. get: function () {
  23222. return Scene._FOGMODE_LINEAR;
  23223. },
  23224. enumerable: true,
  23225. configurable: true
  23226. });
  23227. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23228. /**
  23229. * Texture used in all pbr material as the reflection texture.
  23230. * As in the majority of the scene they are the same (exception for multi room and so on),
  23231. * this is easier to reference from here than from all the materials.
  23232. */
  23233. get: function () {
  23234. return this._environmentTexture;
  23235. },
  23236. /**
  23237. * Texture used in all pbr material as the reflection texture.
  23238. * As in the majority of the scene they are the same (exception for multi room and so on),
  23239. * this is easier to set here than in all the materials.
  23240. */
  23241. set: function (value) {
  23242. if (this._environmentTexture === value) {
  23243. return;
  23244. }
  23245. this._environmentTexture = value;
  23246. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23247. },
  23248. enumerable: true,
  23249. configurable: true
  23250. });
  23251. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23252. /**
  23253. * Default image processing configuration used either in the rendering
  23254. * Forward main pass or through the imageProcessingPostProcess if present.
  23255. * As in the majority of the scene they are the same (exception for multi camera),
  23256. * this is easier to reference from here than from all the materials and post process.
  23257. *
  23258. * No setter as we it is a shared configuration, you can set the values instead.
  23259. */
  23260. get: function () {
  23261. return this._imageProcessingConfiguration;
  23262. },
  23263. enumerable: true,
  23264. configurable: true
  23265. });
  23266. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23267. get: function () {
  23268. return this._forceWireframe;
  23269. },
  23270. /**
  23271. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23272. */
  23273. set: function (value) {
  23274. if (this._forceWireframe === value) {
  23275. return;
  23276. }
  23277. this._forceWireframe = value;
  23278. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23279. },
  23280. enumerable: true,
  23281. configurable: true
  23282. });
  23283. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23284. get: function () {
  23285. return this._forcePointsCloud;
  23286. },
  23287. /**
  23288. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23289. */
  23290. set: function (value) {
  23291. if (this._forcePointsCloud === value) {
  23292. return;
  23293. }
  23294. this._forcePointsCloud = value;
  23295. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23296. },
  23297. enumerable: true,
  23298. configurable: true
  23299. });
  23300. Object.defineProperty(Scene.prototype, "onDispose", {
  23301. /** Sets a function to be executed when this scene is disposed. */
  23302. set: function (callback) {
  23303. if (this._onDisposeObserver) {
  23304. this.onDisposeObservable.remove(this._onDisposeObserver);
  23305. }
  23306. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23307. },
  23308. enumerable: true,
  23309. configurable: true
  23310. });
  23311. Object.defineProperty(Scene.prototype, "beforeRender", {
  23312. /** Sets a function to be executed before rendering this scene */
  23313. set: function (callback) {
  23314. if (this._onBeforeRenderObserver) {
  23315. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23316. }
  23317. if (callback) {
  23318. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23319. }
  23320. },
  23321. enumerable: true,
  23322. configurable: true
  23323. });
  23324. Object.defineProperty(Scene.prototype, "afterRender", {
  23325. /** Sets a function to be executed after rendering this scene */
  23326. set: function (callback) {
  23327. if (this._onAfterRenderObserver) {
  23328. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23329. }
  23330. if (callback) {
  23331. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23332. }
  23333. },
  23334. enumerable: true,
  23335. configurable: true
  23336. });
  23337. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23338. /** Sets a function to be executed before rendering a camera*/
  23339. set: function (callback) {
  23340. if (this._onBeforeCameraRenderObserver) {
  23341. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23342. }
  23343. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23344. },
  23345. enumerable: true,
  23346. configurable: true
  23347. });
  23348. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23349. /** Sets a function to be executed after rendering a camera*/
  23350. set: function (callback) {
  23351. if (this._onAfterCameraRenderObserver) {
  23352. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23353. }
  23354. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23355. },
  23356. enumerable: true,
  23357. configurable: true
  23358. });
  23359. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23360. /**
  23361. * Gets the gamepad manager associated with the scene
  23362. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23363. */
  23364. get: function () {
  23365. if (!this._gamepadManager) {
  23366. this._gamepadManager = new BABYLON.GamepadManager(this);
  23367. }
  23368. return this._gamepadManager;
  23369. },
  23370. enumerable: true,
  23371. configurable: true
  23372. });
  23373. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23374. /**
  23375. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23376. */
  23377. get: function () {
  23378. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23379. },
  23380. enumerable: true,
  23381. configurable: true
  23382. });
  23383. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23384. get: function () {
  23385. return this._useRightHandedSystem;
  23386. },
  23387. /**
  23388. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23389. */
  23390. set: function (value) {
  23391. if (this._useRightHandedSystem === value) {
  23392. return;
  23393. }
  23394. this._useRightHandedSystem = value;
  23395. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23396. },
  23397. enumerable: true,
  23398. configurable: true
  23399. });
  23400. /**
  23401. * Sets the step Id used by deterministic lock step
  23402. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23403. * @param newStepId defines the step Id
  23404. */
  23405. Scene.prototype.setStepId = function (newStepId) {
  23406. this._currentStepId = newStepId;
  23407. };
  23408. ;
  23409. /**
  23410. * Gets the step Id used by deterministic lock step
  23411. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23412. * @returns the step Id
  23413. */
  23414. Scene.prototype.getStepId = function () {
  23415. return this._currentStepId;
  23416. };
  23417. ;
  23418. /**
  23419. * Gets the internal step used by deterministic lock step
  23420. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23421. * @returns the internal step
  23422. */
  23423. Scene.prototype.getInternalStep = function () {
  23424. return this._currentInternalStep;
  23425. };
  23426. ;
  23427. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23428. get: function () {
  23429. return this._fogEnabled;
  23430. },
  23431. /**
  23432. * Gets or sets a boolean indicating if fog is enabled on this scene
  23433. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23434. */
  23435. set: function (value) {
  23436. if (this._fogEnabled === value) {
  23437. return;
  23438. }
  23439. this._fogEnabled = value;
  23440. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23441. },
  23442. enumerable: true,
  23443. configurable: true
  23444. });
  23445. Object.defineProperty(Scene.prototype, "fogMode", {
  23446. get: function () {
  23447. return this._fogMode;
  23448. },
  23449. /**
  23450. * Gets or sets the fog mode to use
  23451. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23452. */
  23453. set: function (value) {
  23454. if (this._fogMode === value) {
  23455. return;
  23456. }
  23457. this._fogMode = value;
  23458. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23459. },
  23460. enumerable: true,
  23461. configurable: true
  23462. });
  23463. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23464. get: function () {
  23465. return this._shadowsEnabled;
  23466. },
  23467. /**
  23468. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23469. */
  23470. set: function (value) {
  23471. if (this._shadowsEnabled === value) {
  23472. return;
  23473. }
  23474. this._shadowsEnabled = value;
  23475. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23476. },
  23477. enumerable: true,
  23478. configurable: true
  23479. });
  23480. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23481. get: function () {
  23482. return this._lightsEnabled;
  23483. },
  23484. /**
  23485. * Gets or sets a boolean indicating if lights are enabled on this scene
  23486. */
  23487. set: function (value) {
  23488. if (this._lightsEnabled === value) {
  23489. return;
  23490. }
  23491. this._lightsEnabled = value;
  23492. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23493. },
  23494. enumerable: true,
  23495. configurable: true
  23496. });
  23497. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  23498. /** The default material used on meshes when no material is affected */
  23499. get: function () {
  23500. if (!this._defaultMaterial) {
  23501. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  23502. }
  23503. return this._defaultMaterial;
  23504. },
  23505. /** The default material used on meshes when no material is affected */
  23506. set: function (value) {
  23507. this._defaultMaterial = value;
  23508. },
  23509. enumerable: true,
  23510. configurable: true
  23511. });
  23512. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  23513. get: function () {
  23514. return this._texturesEnabled;
  23515. },
  23516. /**
  23517. * Gets or sets a boolean indicating if textures are enabled on this scene
  23518. */
  23519. set: function (value) {
  23520. if (this._texturesEnabled === value) {
  23521. return;
  23522. }
  23523. this._texturesEnabled = value;
  23524. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23525. },
  23526. enumerable: true,
  23527. configurable: true
  23528. });
  23529. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  23530. get: function () {
  23531. return this._skeletonsEnabled;
  23532. },
  23533. /**
  23534. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  23535. */
  23536. set: function (value) {
  23537. if (this._skeletonsEnabled === value) {
  23538. return;
  23539. }
  23540. this._skeletonsEnabled = value;
  23541. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  23542. },
  23543. enumerable: true,
  23544. configurable: true
  23545. });
  23546. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  23547. /**
  23548. * Gets the postprocess render pipeline manager
  23549. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  23550. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  23551. */
  23552. get: function () {
  23553. if (!this._postProcessRenderPipelineManager) {
  23554. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  23555. }
  23556. return this._postProcessRenderPipelineManager;
  23557. },
  23558. enumerable: true,
  23559. configurable: true
  23560. });
  23561. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  23562. /**
  23563. * Gets the main soundtrack associated with the scene
  23564. */
  23565. get: function () {
  23566. if (!this._mainSoundTrack) {
  23567. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  23568. }
  23569. return this._mainSoundTrack;
  23570. },
  23571. enumerable: true,
  23572. configurable: true
  23573. });
  23574. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  23575. /** @ignore */
  23576. get: function () {
  23577. return this._alternateRendering;
  23578. },
  23579. enumerable: true,
  23580. configurable: true
  23581. });
  23582. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  23583. /**
  23584. * Gets the list of frustum planes (built from the active camera)
  23585. */
  23586. get: function () {
  23587. return this._frustumPlanes;
  23588. },
  23589. enumerable: true,
  23590. configurable: true
  23591. });
  23592. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  23593. /**
  23594. * Gets the current geometry buffer associated to the scene.
  23595. */
  23596. get: function () {
  23597. return this._geometryBufferRenderer;
  23598. },
  23599. /**
  23600. * Sets the current geometry buffer for the scene.
  23601. */
  23602. set: function (geometryBufferRenderer) {
  23603. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  23604. this._geometryBufferRenderer = geometryBufferRenderer;
  23605. }
  23606. },
  23607. enumerable: true,
  23608. configurable: true
  23609. });
  23610. Object.defineProperty(Scene.prototype, "debugLayer", {
  23611. /**
  23612. * Gets the debug layer associated with the scene
  23613. * @see http://doc.babylonjs.com/features/playground_debuglayer
  23614. */
  23615. get: function () {
  23616. if (!this._debugLayer) {
  23617. this._debugLayer = new BABYLON.DebugLayer(this);
  23618. }
  23619. return this._debugLayer;
  23620. },
  23621. enumerable: true,
  23622. configurable: true
  23623. });
  23624. Object.defineProperty(Scene.prototype, "workerCollisions", {
  23625. /**
  23626. * Gets a boolean indicating if collisions are processed on a web worker
  23627. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  23628. */
  23629. get: function () {
  23630. return this._workerCollisions;
  23631. },
  23632. set: function (enabled) {
  23633. if (!BABYLON.CollisionCoordinatorLegacy) {
  23634. return;
  23635. }
  23636. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  23637. this._workerCollisions = enabled;
  23638. if (this.collisionCoordinator) {
  23639. this.collisionCoordinator.destroy();
  23640. }
  23641. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  23642. this.collisionCoordinator.init(this);
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. Object.defineProperty(Scene.prototype, "selectionOctree", {
  23648. /**
  23649. * Gets the octree used to boost mesh selection (picking)
  23650. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  23651. */
  23652. get: function () {
  23653. return this._selectionOctree;
  23654. },
  23655. enumerable: true,
  23656. configurable: true
  23657. });
  23658. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  23659. /**
  23660. * Gets the mesh that is currently under the pointer
  23661. */
  23662. get: function () {
  23663. return this._pointerOverMesh;
  23664. },
  23665. enumerable: true,
  23666. configurable: true
  23667. });
  23668. Object.defineProperty(Scene.prototype, "pointerX", {
  23669. /**
  23670. * Gets the current on-screen X position of the pointer
  23671. */
  23672. get: function () {
  23673. return this._pointerX;
  23674. },
  23675. enumerable: true,
  23676. configurable: true
  23677. });
  23678. Object.defineProperty(Scene.prototype, "pointerY", {
  23679. /**
  23680. * Gets the current on-screen Y position of the pointer
  23681. */
  23682. get: function () {
  23683. return this._pointerY;
  23684. },
  23685. enumerable: true,
  23686. configurable: true
  23687. });
  23688. /**
  23689. * Gets the cached material (ie. the latest rendered one)
  23690. * @returns the cached material
  23691. */
  23692. Scene.prototype.getCachedMaterial = function () {
  23693. return this._cachedMaterial;
  23694. };
  23695. /**
  23696. * Gets the cached effect (ie. the latest rendered one)
  23697. * @returns the cached effect
  23698. */
  23699. Scene.prototype.getCachedEffect = function () {
  23700. return this._cachedEffect;
  23701. };
  23702. /**
  23703. * Gets the cached visibility state (ie. the latest rendered one)
  23704. * @returns the cached visibility state
  23705. */
  23706. Scene.prototype.getCachedVisibility = function () {
  23707. return this._cachedVisibility;
  23708. };
  23709. /**
  23710. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  23711. * @param material defines the current material
  23712. * @param effect defines the current effect
  23713. * @param visibility defines the current visibility state
  23714. * @returns true if one parameter is not cached
  23715. */
  23716. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  23717. if (visibility === void 0) { visibility = 1; }
  23718. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  23719. };
  23720. /**
  23721. * Gets the bounding box renderer associated with the scene
  23722. * @returns a BoundingBoxRenderer
  23723. */
  23724. Scene.prototype.getBoundingBoxRenderer = function () {
  23725. if (!this._boundingBoxRenderer) {
  23726. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  23727. }
  23728. return this._boundingBoxRenderer;
  23729. };
  23730. /**
  23731. * Gets the outline renderer associated with the scene
  23732. * @returns a OutlineRenderer
  23733. */
  23734. Scene.prototype.getOutlineRenderer = function () {
  23735. return this._outlineRenderer;
  23736. };
  23737. /**
  23738. * Gets the engine associated with the scene
  23739. * @returns an Engine
  23740. */
  23741. Scene.prototype.getEngine = function () {
  23742. return this._engine;
  23743. };
  23744. /**
  23745. * Gets the total number of vertices rendered per frame
  23746. * @returns the total number of vertices rendered per frame
  23747. */
  23748. Scene.prototype.getTotalVertices = function () {
  23749. return this._totalVertices.current;
  23750. };
  23751. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  23752. /**
  23753. * Gets the performance counter for total vertices
  23754. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23755. */
  23756. get: function () {
  23757. return this._totalVertices;
  23758. },
  23759. enumerable: true,
  23760. configurable: true
  23761. });
  23762. /**
  23763. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  23764. * @returns the total number of active indices rendered per frame
  23765. */
  23766. Scene.prototype.getActiveIndices = function () {
  23767. return this._activeIndices.current;
  23768. };
  23769. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  23770. /**
  23771. * Gets the performance counter for active indices
  23772. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23773. */
  23774. get: function () {
  23775. return this._activeIndices;
  23776. },
  23777. enumerable: true,
  23778. configurable: true
  23779. });
  23780. /**
  23781. * Gets the total number of active particles rendered per frame
  23782. * @returns the total number of active particles rendered per frame
  23783. */
  23784. Scene.prototype.getActiveParticles = function () {
  23785. return this._activeParticles.current;
  23786. };
  23787. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  23788. /**
  23789. * Gets the performance counter for active particles
  23790. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23791. */
  23792. get: function () {
  23793. return this._activeParticles;
  23794. },
  23795. enumerable: true,
  23796. configurable: true
  23797. });
  23798. /**
  23799. * Gets the total number of active bones rendered per frame
  23800. * @returns the total number of active bones rendered per frame
  23801. */
  23802. Scene.prototype.getActiveBones = function () {
  23803. return this._activeBones.current;
  23804. };
  23805. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  23806. /**
  23807. * Gets the performance counter for active bones
  23808. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  23809. */
  23810. get: function () {
  23811. return this._activeBones;
  23812. },
  23813. enumerable: true,
  23814. configurable: true
  23815. });
  23816. /** @ignore */
  23817. Scene.prototype.getInterFramePerfCounter = function () {
  23818. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23819. return 0;
  23820. };
  23821. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  23822. /** @ignore */
  23823. get: function () {
  23824. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23825. return null;
  23826. },
  23827. enumerable: true,
  23828. configurable: true
  23829. });
  23830. /** @ignore */
  23831. Scene.prototype.getLastFrameDuration = function () {
  23832. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  23833. return 0;
  23834. };
  23835. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  23836. /** @ignore */
  23837. get: function () {
  23838. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  23839. return null;
  23840. },
  23841. enumerable: true,
  23842. configurable: true
  23843. });
  23844. /** @ignore */
  23845. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  23846. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  23847. return 0;
  23848. };
  23849. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  23850. /** @ignore */
  23851. get: function () {
  23852. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  23853. return null;
  23854. },
  23855. enumerable: true,
  23856. configurable: true
  23857. });
  23858. /**
  23859. * Gets the array of active meshes
  23860. * @returns an array of AbstractMesh
  23861. */
  23862. Scene.prototype.getActiveMeshes = function () {
  23863. return this._activeMeshes;
  23864. };
  23865. /** @ignore */
  23866. Scene.prototype.getRenderTargetsDuration = function () {
  23867. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  23868. return 0;
  23869. };
  23870. /** @ignore */
  23871. Scene.prototype.getRenderDuration = function () {
  23872. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  23873. return 0;
  23874. };
  23875. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  23876. /** @ignore */
  23877. get: function () {
  23878. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  23879. return null;
  23880. },
  23881. enumerable: true,
  23882. configurable: true
  23883. });
  23884. /** @ignore */
  23885. Scene.prototype.getParticlesDuration = function () {
  23886. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  23887. return 0;
  23888. };
  23889. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  23890. /** @ignore */
  23891. get: function () {
  23892. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  23893. return null;
  23894. },
  23895. enumerable: true,
  23896. configurable: true
  23897. });
  23898. /** @ignore */
  23899. Scene.prototype.getSpritesDuration = function () {
  23900. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  23901. return 0;
  23902. };
  23903. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  23904. /** @ignore */
  23905. get: function () {
  23906. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  23907. return null;
  23908. },
  23909. enumerable: true,
  23910. configurable: true
  23911. });
  23912. /**
  23913. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  23914. * @returns a number
  23915. */
  23916. Scene.prototype.getAnimationRatio = function () {
  23917. return this._animationRatio;
  23918. };
  23919. /**
  23920. * Gets an unique Id for the current frame
  23921. * @returns a number
  23922. */
  23923. Scene.prototype.getRenderId = function () {
  23924. return this._renderId;
  23925. };
  23926. /** Call this function if you want to manually increment the render Id*/
  23927. Scene.prototype.incrementRenderId = function () {
  23928. this._renderId++;
  23929. };
  23930. Scene.prototype._updatePointerPosition = function (evt) {
  23931. var canvasRect = this._engine.getRenderingCanvasClientRect();
  23932. if (!canvasRect) {
  23933. return;
  23934. }
  23935. this._pointerX = evt.clientX - canvasRect.left;
  23936. this._pointerY = evt.clientY - canvasRect.top;
  23937. this._unTranslatedPointerX = this._pointerX;
  23938. this._unTranslatedPointerY = this._pointerY;
  23939. };
  23940. Scene.prototype._createUbo = function () {
  23941. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  23942. this._sceneUbo.addUniform("viewProjection", 16);
  23943. this._sceneUbo.addUniform("view", 16);
  23944. };
  23945. Scene.prototype._createAlternateUbo = function () {
  23946. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  23947. this._alternateSceneUbo.addUniform("viewProjection", 16);
  23948. this._alternateSceneUbo.addUniform("view", 16);
  23949. };
  23950. // Pointers handling
  23951. /**
  23952. * Use this method to simulate a pointer move on a mesh
  23953. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  23954. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  23955. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  23956. * @returns the current scene
  23957. */
  23958. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  23959. var evt = new PointerEvent("pointermove", pointerEventInit);
  23960. return this._processPointerMove(pickResult, evt);
  23961. };
  23962. Scene.prototype._processPointerMove = function (pickResult, evt) {
  23963. var canvas = this._engine.getRenderingCanvas();
  23964. if (!canvas) {
  23965. return this;
  23966. }
  23967. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  23968. this.setPointerOverSprite(null);
  23969. this.setPointerOverMesh(pickResult.pickedMesh);
  23970. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  23971. if (this._pointerOverMesh.actionManager.hoverCursor) {
  23972. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  23973. }
  23974. else {
  23975. canvas.style.cursor = this.hoverCursor;
  23976. }
  23977. }
  23978. else {
  23979. canvas.style.cursor = this.defaultCursor;
  23980. }
  23981. }
  23982. else {
  23983. this.setPointerOverMesh(null);
  23984. // Sprites
  23985. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  23986. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  23987. this.setPointerOverSprite(pickResult.pickedSprite);
  23988. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  23989. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  23990. }
  23991. else {
  23992. canvas.style.cursor = this.hoverCursor;
  23993. }
  23994. }
  23995. else {
  23996. this.setPointerOverSprite(null);
  23997. // Restore pointer
  23998. canvas.style.cursor = this.defaultCursor;
  23999. }
  24000. }
  24001. if (pickResult) {
  24002. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24003. if (this.onPointerMove) {
  24004. this.onPointerMove(evt, pickResult, type);
  24005. }
  24006. if (this.onPointerObservable.hasObservers()) {
  24007. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24008. this.onPointerObservable.notifyObservers(pi, type);
  24009. }
  24010. }
  24011. return this;
  24012. };
  24013. /**
  24014. * Use this method to simulate a pointer down on a mesh
  24015. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24016. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24017. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24018. * @returns the current scene
  24019. */
  24020. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24021. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24022. return this._processPointerDown(pickResult, evt);
  24023. };
  24024. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24025. var _this = this;
  24026. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24027. this._pickedDownMesh = pickResult.pickedMesh;
  24028. var actionManager = pickResult.pickedMesh.actionManager;
  24029. if (actionManager) {
  24030. if (actionManager.hasPickTriggers) {
  24031. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24032. switch (evt.button) {
  24033. case 0:
  24034. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24035. break;
  24036. case 1:
  24037. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24038. break;
  24039. case 2:
  24040. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24041. break;
  24042. }
  24043. }
  24044. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24045. window.setTimeout(function () {
  24046. 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);
  24047. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24048. if (_this._totalPointersPressed !== 0 &&
  24049. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24050. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24051. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24052. _this._startingPointerTime = 0;
  24053. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24054. }
  24055. }
  24056. }, Scene.LongPressDelay);
  24057. }
  24058. }
  24059. }
  24060. if (pickResult) {
  24061. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24062. if (this.onPointerDown) {
  24063. this.onPointerDown(evt, pickResult, type);
  24064. }
  24065. if (this.onPointerObservable.hasObservers()) {
  24066. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24067. this.onPointerObservable.notifyObservers(pi, type);
  24068. }
  24069. }
  24070. return this;
  24071. };
  24072. /**
  24073. * Use this method to simulate a pointer up on a mesh
  24074. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24075. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24076. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24077. * @returns the current scene
  24078. */
  24079. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24080. var evt = new PointerEvent("pointerup", pointerEventInit);
  24081. var clickInfo = new ClickInfo();
  24082. clickInfo.singleClick = true;
  24083. clickInfo.ignore = true;
  24084. return this._processPointerUp(pickResult, evt, clickInfo);
  24085. };
  24086. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24087. if (pickResult && pickResult && pickResult.pickedMesh) {
  24088. this._pickedUpMesh = pickResult.pickedMesh;
  24089. if (this._pickedDownMesh === this._pickedUpMesh) {
  24090. if (this.onPointerPick) {
  24091. this.onPointerPick(evt, pickResult);
  24092. }
  24093. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24094. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24095. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24096. this.onPointerObservable.notifyObservers(pi, type_1);
  24097. }
  24098. }
  24099. if (pickResult.pickedMesh.actionManager) {
  24100. if (clickInfo.ignore) {
  24101. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24102. }
  24103. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24104. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24105. }
  24106. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24107. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24108. }
  24109. }
  24110. }
  24111. if (this._pickedDownMesh &&
  24112. this._pickedDownMesh.actionManager &&
  24113. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24114. this._pickedDownMesh !== this._pickedUpMesh) {
  24115. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24116. }
  24117. var type = BABYLON.PointerEventTypes.POINTERUP;
  24118. if (this.onPointerObservable.hasObservers()) {
  24119. if (!clickInfo.ignore) {
  24120. if (!clickInfo.hasSwiped) {
  24121. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24122. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24123. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24124. this.onPointerObservable.notifyObservers(pi, type_2);
  24125. }
  24126. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24127. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24128. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24129. this.onPointerObservable.notifyObservers(pi, type_3);
  24130. }
  24131. }
  24132. }
  24133. else {
  24134. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24135. this.onPointerObservable.notifyObservers(pi, type);
  24136. }
  24137. }
  24138. if (this.onPointerUp) {
  24139. this.onPointerUp(evt, pickResult, type);
  24140. }
  24141. return this;
  24142. };
  24143. /**
  24144. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24145. * @param attachUp defines if you want to attach events to pointerup
  24146. * @param attachDown defines if you want to attach events to pointerdown
  24147. * @param attachMove defines if you want to attach events to pointermove
  24148. */
  24149. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24150. var _this = this;
  24151. if (attachUp === void 0) { attachUp = true; }
  24152. if (attachDown === void 0) { attachDown = true; }
  24153. if (attachMove === void 0) { attachMove = true; }
  24154. this._initActionManager = function (act, clickInfo) {
  24155. if (!_this._meshPickProceed) {
  24156. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24157. _this._currentPickResult = pickResult;
  24158. if (pickResult) {
  24159. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24160. }
  24161. _this._meshPickProceed = true;
  24162. }
  24163. return act;
  24164. };
  24165. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24166. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24167. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24168. btn !== _this._previousButtonPressed) {
  24169. _this._doubleClickOccured = false;
  24170. clickInfo.singleClick = true;
  24171. clickInfo.ignore = false;
  24172. cb(clickInfo, _this._currentPickResult);
  24173. }
  24174. };
  24175. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24176. var clickInfo = new ClickInfo();
  24177. _this._currentPickResult = null;
  24178. var act = null;
  24179. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24180. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24181. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24182. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24183. act = _this._initActionManager(act, clickInfo);
  24184. if (act)
  24185. checkPicking = act.hasPickTriggers;
  24186. }
  24187. if (checkPicking) {
  24188. var btn = evt.button;
  24189. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24190. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24191. if (!clickInfo.hasSwiped) {
  24192. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24193. if (!checkSingleClickImmediately) {
  24194. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24195. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24196. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24197. act = _this._initActionManager(act, clickInfo);
  24198. if (act)
  24199. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24200. }
  24201. }
  24202. if (checkSingleClickImmediately) {
  24203. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24204. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24205. btn !== _this._previousButtonPressed) {
  24206. clickInfo.singleClick = true;
  24207. cb(clickInfo, _this._currentPickResult);
  24208. }
  24209. }
  24210. else {
  24211. // wait that no double click has been raised during the double click delay
  24212. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24213. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24214. }
  24215. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24216. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24217. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24218. act = _this._initActionManager(act, clickInfo);
  24219. if (act)
  24220. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24221. }
  24222. if (checkDoubleClick) {
  24223. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24224. if (btn === _this._previousButtonPressed &&
  24225. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24226. !_this._doubleClickOccured) {
  24227. // pointer has not moved for 2 clicks, it's a double click
  24228. if (!clickInfo.hasSwiped &&
  24229. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24230. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24231. _this._previousStartingPointerTime = 0;
  24232. _this._doubleClickOccured = true;
  24233. clickInfo.doubleClick = true;
  24234. clickInfo.ignore = false;
  24235. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24236. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24237. }
  24238. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24239. cb(clickInfo, _this._currentPickResult);
  24240. }
  24241. else {
  24242. _this._doubleClickOccured = false;
  24243. _this._previousStartingPointerTime = _this._startingPointerTime;
  24244. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24245. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24246. _this._previousButtonPressed = btn;
  24247. if (Scene.ExclusiveDoubleClickMode) {
  24248. if (_this._previousDelayedSimpleClickTimeout) {
  24249. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24250. }
  24251. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24252. cb(clickInfo, _this._previousPickResult);
  24253. }
  24254. else {
  24255. cb(clickInfo, _this._currentPickResult);
  24256. }
  24257. }
  24258. }
  24259. else {
  24260. _this._doubleClickOccured = false;
  24261. _this._previousStartingPointerTime = _this._startingPointerTime;
  24262. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24263. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24264. _this._previousButtonPressed = btn;
  24265. }
  24266. }
  24267. }
  24268. }
  24269. clickInfo.ignore = true;
  24270. cb(clickInfo, _this._currentPickResult);
  24271. };
  24272. this._spritePredicate = function (sprite) {
  24273. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24274. };
  24275. this._onPointerMove = function (evt) {
  24276. _this._updatePointerPosition(evt);
  24277. // PreObservable support
  24278. if (_this.onPrePointerObservable.hasObservers()) {
  24279. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24280. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24281. _this.onPrePointerObservable.notifyObservers(pi, type);
  24282. if (pi.skipOnPointerObservable) {
  24283. return;
  24284. }
  24285. }
  24286. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24287. return;
  24288. }
  24289. if (!_this.pointerMovePredicate) {
  24290. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24291. }
  24292. // Meshes
  24293. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24294. _this._processPointerMove(pickResult, evt);
  24295. };
  24296. this._onPointerDown = function (evt) {
  24297. _this._totalPointersPressed++;
  24298. _this._pickedDownMesh = null;
  24299. _this._meshPickProceed = false;
  24300. _this._updatePointerPosition(evt);
  24301. if (_this.preventDefaultOnPointerDown && canvas) {
  24302. evt.preventDefault();
  24303. canvas.focus();
  24304. }
  24305. // PreObservable support
  24306. if (_this.onPrePointerObservable.hasObservers()) {
  24307. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24308. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24309. _this.onPrePointerObservable.notifyObservers(pi, type);
  24310. if (pi.skipOnPointerObservable) {
  24311. return;
  24312. }
  24313. }
  24314. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24315. return;
  24316. }
  24317. _this._startingPointerPosition.x = _this._pointerX;
  24318. _this._startingPointerPosition.y = _this._pointerY;
  24319. _this._startingPointerTime = new Date().getTime();
  24320. if (!_this.pointerDownPredicate) {
  24321. _this.pointerDownPredicate = function (mesh) {
  24322. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24323. };
  24324. }
  24325. // Meshes
  24326. _this._pickedDownMesh = null;
  24327. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24328. _this._processPointerDown(pickResult, evt);
  24329. // Sprites
  24330. _this._pickedDownSprite = null;
  24331. if (_this.spriteManagers.length > 0) {
  24332. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24333. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24334. if (pickResult.pickedSprite.actionManager) {
  24335. _this._pickedDownSprite = pickResult.pickedSprite;
  24336. switch (evt.button) {
  24337. case 0:
  24338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24339. break;
  24340. case 1:
  24341. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24342. break;
  24343. case 2:
  24344. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24345. break;
  24346. }
  24347. if (pickResult.pickedSprite.actionManager) {
  24348. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24349. }
  24350. }
  24351. }
  24352. }
  24353. };
  24354. this._onPointerUp = function (evt) {
  24355. if (_this._totalPointersPressed === 0) {
  24356. return; // So we need to test it the pointer down was pressed before.
  24357. }
  24358. _this._totalPointersPressed--;
  24359. _this._pickedUpMesh = null;
  24360. _this._meshPickProceed = false;
  24361. _this._updatePointerPosition(evt);
  24362. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24363. // PreObservable support
  24364. if (_this.onPrePointerObservable.hasObservers()) {
  24365. if (!clickInfo.ignore) {
  24366. if (!clickInfo.hasSwiped) {
  24367. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24368. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24369. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24370. _this.onPrePointerObservable.notifyObservers(pi, type);
  24371. if (pi.skipOnPointerObservable) {
  24372. return;
  24373. }
  24374. }
  24375. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24376. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24377. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24378. _this.onPrePointerObservable.notifyObservers(pi, type);
  24379. if (pi.skipOnPointerObservable) {
  24380. return;
  24381. }
  24382. }
  24383. }
  24384. }
  24385. else {
  24386. var type = BABYLON.PointerEventTypes.POINTERUP;
  24387. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24388. _this.onPrePointerObservable.notifyObservers(pi, type);
  24389. if (pi.skipOnPointerObservable) {
  24390. return;
  24391. }
  24392. }
  24393. }
  24394. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24395. return;
  24396. }
  24397. if (!_this.pointerUpPredicate) {
  24398. _this.pointerUpPredicate = function (mesh) {
  24399. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24400. };
  24401. }
  24402. // Meshes
  24403. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24404. _this._initActionManager(null, clickInfo);
  24405. }
  24406. if (!pickResult) {
  24407. pickResult = _this._currentPickResult;
  24408. }
  24409. _this._processPointerUp(pickResult, evt, clickInfo);
  24410. // Sprites
  24411. if (_this.spriteManagers.length > 0) {
  24412. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24413. if (spritePickResult) {
  24414. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24415. if (spritePickResult.pickedSprite.actionManager) {
  24416. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24417. if (spritePickResult.pickedSprite.actionManager) {
  24418. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24419. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24420. }
  24421. }
  24422. }
  24423. }
  24424. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24425. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24426. }
  24427. }
  24428. }
  24429. _this._previousPickResult = _this._currentPickResult;
  24430. });
  24431. };
  24432. this._onKeyDown = function (evt) {
  24433. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24434. if (_this.onPreKeyboardObservable.hasObservers()) {
  24435. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24436. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24437. if (pi.skipOnPointerObservable) {
  24438. return;
  24439. }
  24440. }
  24441. if (_this.onKeyboardObservable.hasObservers()) {
  24442. var pi = new BABYLON.KeyboardInfo(type, evt);
  24443. _this.onKeyboardObservable.notifyObservers(pi, type);
  24444. }
  24445. if (_this.actionManager) {
  24446. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24447. }
  24448. };
  24449. this._onKeyUp = function (evt) {
  24450. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24451. if (_this.onPreKeyboardObservable.hasObservers()) {
  24452. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24453. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24454. if (pi.skipOnPointerObservable) {
  24455. return;
  24456. }
  24457. }
  24458. if (_this.onKeyboardObservable.hasObservers()) {
  24459. var pi = new BABYLON.KeyboardInfo(type, evt);
  24460. _this.onKeyboardObservable.notifyObservers(pi, type);
  24461. }
  24462. if (_this.actionManager) {
  24463. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24464. }
  24465. };
  24466. var engine = this.getEngine();
  24467. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24468. if (!canvas) {
  24469. return;
  24470. }
  24471. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24472. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24473. });
  24474. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24475. if (!canvas) {
  24476. return;
  24477. }
  24478. canvas.removeEventListener("keydown", _this._onKeyDown);
  24479. canvas.removeEventListener("keyup", _this._onKeyUp);
  24480. });
  24481. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24482. var canvas = this._engine.getRenderingCanvas();
  24483. if (!canvas) {
  24484. return;
  24485. }
  24486. if (attachMove) {
  24487. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  24488. // Wheel
  24489. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  24490. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  24491. }
  24492. if (attachDown) {
  24493. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  24494. }
  24495. if (attachUp) {
  24496. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  24497. }
  24498. canvas.tabIndex = 1;
  24499. };
  24500. /** Detaches all event handlers*/
  24501. Scene.prototype.detachControl = function () {
  24502. var engine = this.getEngine();
  24503. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24504. var canvas = engine.getRenderingCanvas();
  24505. if (!canvas) {
  24506. return;
  24507. }
  24508. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  24509. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  24510. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  24511. if (this._onCanvasBlurObserver) {
  24512. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  24513. }
  24514. if (this._onCanvasFocusObserver) {
  24515. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  24516. }
  24517. // Wheel
  24518. canvas.removeEventListener('mousewheel', this._onPointerMove);
  24519. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  24520. // Keyboard
  24521. canvas.removeEventListener("keydown", this._onKeyDown);
  24522. canvas.removeEventListener("keyup", this._onKeyUp);
  24523. // Observables
  24524. this.onKeyboardObservable.clear();
  24525. this.onPreKeyboardObservable.clear();
  24526. this.onPointerObservable.clear();
  24527. this.onPrePointerObservable.clear();
  24528. };
  24529. /**
  24530. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  24531. * Delay loaded resources are not taking in account
  24532. * @return true if all required resources are ready
  24533. */
  24534. Scene.prototype.isReady = function () {
  24535. if (this._isDisposed) {
  24536. return false;
  24537. }
  24538. if (this._pendingData.length > 0) {
  24539. return false;
  24540. }
  24541. var index;
  24542. var engine = this.getEngine();
  24543. // Geometries
  24544. for (index = 0; index < this._geometries.length; index++) {
  24545. var geometry = this._geometries[index];
  24546. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24547. return false;
  24548. }
  24549. }
  24550. // Meshes
  24551. for (index = 0; index < this.meshes.length; index++) {
  24552. var mesh = this.meshes[index];
  24553. if (!mesh.isEnabled()) {
  24554. continue;
  24555. }
  24556. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24557. continue;
  24558. }
  24559. if (!mesh.isReady(true)) {
  24560. return false;
  24561. }
  24562. // Effect layers
  24563. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  24564. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  24565. var layer = _a[_i];
  24566. if (!layer.hasMesh(mesh)) {
  24567. continue;
  24568. }
  24569. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24570. var subMesh = _c[_b];
  24571. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  24572. return false;
  24573. }
  24574. }
  24575. }
  24576. }
  24577. // Post-processes
  24578. if (this.activeCameras && this.activeCameras.length > 0) {
  24579. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  24580. var camera = _e[_d];
  24581. if (!camera.isReady(true)) {
  24582. return false;
  24583. }
  24584. }
  24585. }
  24586. else if (this.activeCamera) {
  24587. if (!this.activeCamera.isReady(true)) {
  24588. return false;
  24589. }
  24590. }
  24591. // Particles
  24592. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  24593. var particleSystem = _g[_f];
  24594. if (!particleSystem.isReady()) {
  24595. return false;
  24596. }
  24597. }
  24598. return true;
  24599. };
  24600. /** Resets all cached information relative to material (including effect and visibility) */
  24601. Scene.prototype.resetCachedMaterial = function () {
  24602. this._cachedMaterial = null;
  24603. this._cachedEffect = null;
  24604. this._cachedVisibility = null;
  24605. };
  24606. /**
  24607. * Registers a function to be called before every frame render
  24608. * @param func defines the function to register
  24609. */
  24610. Scene.prototype.registerBeforeRender = function (func) {
  24611. this.onBeforeRenderObservable.add(func);
  24612. };
  24613. /**
  24614. * Unregisters a function called before every frame render
  24615. * @param func defines the function to unregister
  24616. */
  24617. Scene.prototype.unregisterBeforeRender = function (func) {
  24618. this.onBeforeRenderObservable.removeCallback(func);
  24619. };
  24620. /**
  24621. * Registers a function to be called after every frame render
  24622. * @param func defines the function to register
  24623. */
  24624. Scene.prototype.registerAfterRender = function (func) {
  24625. this.onAfterRenderObservable.add(func);
  24626. };
  24627. /**
  24628. * Unregisters a function called after every frame render
  24629. * @param func defines the function to unregister
  24630. */
  24631. Scene.prototype.unregisterAfterRender = function (func) {
  24632. this.onAfterRenderObservable.removeCallback(func);
  24633. };
  24634. Scene.prototype._executeOnceBeforeRender = function (func) {
  24635. var _this = this;
  24636. var execFunc = function () {
  24637. func();
  24638. setTimeout(function () {
  24639. _this.unregisterBeforeRender(execFunc);
  24640. });
  24641. };
  24642. this.registerBeforeRender(execFunc);
  24643. };
  24644. /**
  24645. * The provided function will run before render once and will be disposed afterwards.
  24646. * A timeout delay can be provided so that the function will be executed in N ms.
  24647. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  24648. * @param func The function to be executed.
  24649. * @param timeout optional delay in ms
  24650. */
  24651. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  24652. var _this = this;
  24653. if (timeout !== undefined) {
  24654. setTimeout(function () {
  24655. _this._executeOnceBeforeRender(func);
  24656. }, timeout);
  24657. }
  24658. else {
  24659. this._executeOnceBeforeRender(func);
  24660. }
  24661. };
  24662. /** @ignore */
  24663. Scene.prototype._addPendingData = function (data) {
  24664. this._pendingData.push(data);
  24665. };
  24666. /** @ignore */
  24667. Scene.prototype._removePendingData = function (data) {
  24668. var wasLoading = this.isLoading;
  24669. var index = this._pendingData.indexOf(data);
  24670. if (index !== -1) {
  24671. this._pendingData.splice(index, 1);
  24672. }
  24673. if (wasLoading && !this.isLoading) {
  24674. this.onDataLoadedObservable.notifyObservers(this);
  24675. }
  24676. };
  24677. /**
  24678. * Returns the number of items waiting to be loaded
  24679. * @returns the number of items waiting to be loaded
  24680. */
  24681. Scene.prototype.getWaitingItemsCount = function () {
  24682. return this._pendingData.length;
  24683. };
  24684. Object.defineProperty(Scene.prototype, "isLoading", {
  24685. /**
  24686. * Returns a boolean indicating if the scene is still loading data
  24687. */
  24688. get: function () {
  24689. return this._pendingData.length > 0;
  24690. },
  24691. enumerable: true,
  24692. configurable: true
  24693. });
  24694. /**
  24695. * Registers a function to be executed when the scene is ready
  24696. * @param {Function} func - the function to be executed
  24697. */
  24698. Scene.prototype.executeWhenReady = function (func) {
  24699. var _this = this;
  24700. this.onReadyObservable.add(func);
  24701. if (this._executeWhenReadyTimeoutId !== -1) {
  24702. return;
  24703. }
  24704. this._executeWhenReadyTimeoutId = setTimeout(function () {
  24705. _this._checkIsReady();
  24706. }, 150);
  24707. };
  24708. /**
  24709. * Returns a promise that resolves when the scene is ready
  24710. * @returns A promise that resolves when the scene is ready
  24711. */
  24712. Scene.prototype.whenReadyAsync = function () {
  24713. var _this = this;
  24714. return new Promise(function (resolve) {
  24715. _this.executeWhenReady(function () {
  24716. resolve();
  24717. });
  24718. });
  24719. };
  24720. /** @ignore */
  24721. Scene.prototype._checkIsReady = function () {
  24722. var _this = this;
  24723. if (this.isReady()) {
  24724. this.onReadyObservable.notifyObservers(this);
  24725. this.onReadyObservable.clear();
  24726. this._executeWhenReadyTimeoutId = -1;
  24727. return;
  24728. }
  24729. this._executeWhenReadyTimeoutId = setTimeout(function () {
  24730. _this._checkIsReady();
  24731. }, 150);
  24732. };
  24733. // Animations
  24734. /**
  24735. * Will start the animation sequence of a given target
  24736. * @param target defines the target
  24737. * @param from defines from which frame should animation start
  24738. * @param to defines until which frame should animation run.
  24739. * @param weight defines the weight to apply to the animation (1.0 by default)
  24740. * @param loop defines if the animation loops
  24741. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  24742. * @param onAnimationEnd defines the function to be executed when the animation ends
  24743. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  24744. * @returns the animatable object created for this animation
  24745. */
  24746. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  24747. if (weight === void 0) { weight = 1.0; }
  24748. if (speedRatio === void 0) { speedRatio = 1.0; }
  24749. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  24750. returnedAnimatable.weight = weight;
  24751. return returnedAnimatable;
  24752. };
  24753. /**
  24754. * Will start the animation sequence of a given target
  24755. * @param target defines the target
  24756. * @param from defines from which frame should animation start
  24757. * @param to defines until which frame should animation run.
  24758. * @param loop defines if the animation loops
  24759. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  24760. * @param onAnimationEnd defines the function to be executed when the animation ends
  24761. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  24762. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  24763. * @returns the animatable object created for this animation
  24764. */
  24765. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  24766. if (speedRatio === void 0) { speedRatio = 1.0; }
  24767. if (stopCurrent === void 0) { stopCurrent = true; }
  24768. if (from > to && speedRatio > 0) {
  24769. speedRatio *= -1;
  24770. }
  24771. if (stopCurrent) {
  24772. this.stopAnimation(target);
  24773. }
  24774. if (!animatable) {
  24775. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  24776. }
  24777. // Local animations
  24778. if (target.animations) {
  24779. animatable.appendAnimations(target, target.animations);
  24780. }
  24781. // Children animations
  24782. if (target.getAnimatables) {
  24783. var animatables = target.getAnimatables();
  24784. for (var index = 0; index < animatables.length; index++) {
  24785. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  24786. }
  24787. }
  24788. animatable.reset();
  24789. return animatable;
  24790. };
  24791. /**
  24792. * Begin a new animation on a given node
  24793. * @param target defines the target where the animation will take place
  24794. * @param animations defines the list of animations to start
  24795. * @param from defines the initial value
  24796. * @param to defines the final value
  24797. * @param loop defines if you want animation to loop (off by default)
  24798. * @param speedRatio defines the speed ratio to apply to all animations
  24799. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  24800. * @returns the list of created animatables
  24801. */
  24802. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  24803. if (speedRatio === undefined) {
  24804. speedRatio = 1.0;
  24805. }
  24806. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  24807. return animatable;
  24808. };
  24809. /**
  24810. * Begin a new animation on a given node and its hierarchy
  24811. * @param target defines the root node where the animation will take place
  24812. * @param 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.
  24813. * @param animations defines the list of animations to start
  24814. * @param from defines the initial value
  24815. * @param to defines the final value
  24816. * @param loop defines if you want animation to loop (off by default)
  24817. * @param speedRatio defines the speed ratio to apply to all animations
  24818. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  24819. * @returns the list of animatables created for all nodes
  24820. */
  24821. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  24822. var children = target.getDescendants(directDescendantsOnly);
  24823. var result = [];
  24824. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  24825. var child = children_1[_i];
  24826. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  24827. }
  24828. return result;
  24829. };
  24830. /**
  24831. * Gets the animatable associated with a specific target
  24832. * @param target defines the target of the animatable
  24833. * @returns the required animatable if found
  24834. */
  24835. Scene.prototype.getAnimatableByTarget = function (target) {
  24836. for (var index = 0; index < this._activeAnimatables.length; index++) {
  24837. if (this._activeAnimatables[index].target === target) {
  24838. return this._activeAnimatables[index];
  24839. }
  24840. }
  24841. return null;
  24842. };
  24843. /**
  24844. * Gets all animatables associated with a given target
  24845. * @param target defines the target to look animatables for
  24846. * @returns an array of Animatables
  24847. */
  24848. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  24849. var result = [];
  24850. for (var index = 0; index < this._activeAnimatables.length; index++) {
  24851. if (this._activeAnimatables[index].target === target) {
  24852. result.push(this._activeAnimatables[index]);
  24853. }
  24854. }
  24855. return result;
  24856. };
  24857. Object.defineProperty(Scene.prototype, "animatables", {
  24858. /**
  24859. * Gets all animatable attached to the scene
  24860. */
  24861. get: function () {
  24862. return this._activeAnimatables;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. /**
  24868. * Will stop the animation of the given target
  24869. * @param target - the target
  24870. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  24871. */
  24872. Scene.prototype.stopAnimation = function (target, animationName) {
  24873. var animatables = this.getAllAnimatablesByTarget(target);
  24874. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  24875. var animatable = animatables_1[_i];
  24876. animatable.stop(animationName);
  24877. }
  24878. };
  24879. /**
  24880. * Stops and removes all animations that have been applied to the scene
  24881. */
  24882. Scene.prototype.stopAllAnimations = function () {
  24883. if (this._activeAnimatables) {
  24884. for (var i = 0; i < this._activeAnimatables.length; i++) {
  24885. this._activeAnimatables[i].stop();
  24886. }
  24887. this._activeAnimatables = [];
  24888. }
  24889. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  24890. var group = _a[_i];
  24891. group.stop();
  24892. }
  24893. };
  24894. Scene.prototype._animate = function () {
  24895. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  24896. return;
  24897. }
  24898. // Getting time
  24899. var now = BABYLON.Tools.Now;
  24900. if (!this._animationTimeLast) {
  24901. if (this._pendingData.length > 0) {
  24902. return;
  24903. }
  24904. this._animationTimeLast = now;
  24905. }
  24906. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  24907. this._animationTime += deltaTime;
  24908. this._animationTimeLast = now;
  24909. for (var index = 0; index < this._activeAnimatables.length; index++) {
  24910. this._activeAnimatables[index]._animate(this._animationTime);
  24911. }
  24912. // Late animation bindings
  24913. this._processLateAnimationBindings();
  24914. };
  24915. /** @ignore */
  24916. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  24917. var target = runtimeAnimation.target;
  24918. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  24919. if (!target._lateAnimationHolders) {
  24920. target._lateAnimationHolders = {};
  24921. }
  24922. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  24923. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  24924. totalWeight: 0,
  24925. animations: []
  24926. };
  24927. }
  24928. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  24929. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  24930. };
  24931. Scene.prototype._processLateAnimationBindings = function () {
  24932. if (!this._registeredForLateAnimationBindings.length) {
  24933. return;
  24934. }
  24935. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  24936. var target = this._registeredForLateAnimationBindings.data[index];
  24937. for (var path in target._lateAnimationHolders) {
  24938. var holder = target._lateAnimationHolders[path];
  24939. // Sanity check
  24940. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  24941. continue;
  24942. }
  24943. var normalizer = 1.0;
  24944. var finalValue = void 0;
  24945. if (holder.totalWeight < 1.0) {
  24946. // We need to mix the original value in
  24947. var originalValue = holder.animations[0].originalValue;
  24948. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  24949. }
  24950. else {
  24951. // We need to normalize the weights
  24952. normalizer = holder.totalWeight;
  24953. }
  24954. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  24955. var runtimeAnimation = holder.animations[animIndex];
  24956. if (finalValue) {
  24957. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  24958. }
  24959. else {
  24960. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  24961. }
  24962. }
  24963. runtimeAnimation.target[path] = finalValue;
  24964. }
  24965. target._lateAnimationHolders = {};
  24966. }
  24967. this._registeredForLateAnimationBindings.reset();
  24968. };
  24969. // Matrix
  24970. /** @ignore */
  24971. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  24972. this._useAlternateCameraConfiguration = active;
  24973. };
  24974. /**
  24975. * Gets the current view matrix
  24976. * @returns a Matrix
  24977. */
  24978. Scene.prototype.getViewMatrix = function () {
  24979. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  24980. };
  24981. /**
  24982. * Gets the current projection matrix
  24983. * @returns a Matrix
  24984. */
  24985. Scene.prototype.getProjectionMatrix = function () {
  24986. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  24987. };
  24988. /**
  24989. * Gets the current transform matrix
  24990. * @returns a Matrix made of View * Projection
  24991. */
  24992. Scene.prototype.getTransformMatrix = function () {
  24993. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  24994. };
  24995. /**
  24996. * Sets the current transform matrix
  24997. * @param view defines the View matrix to use
  24998. * @param projection defines the Projection matrix to use
  24999. */
  25000. Scene.prototype.setTransformMatrix = function (view, projection) {
  25001. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25002. return;
  25003. }
  25004. this._viewUpdateFlag = view.updateFlag;
  25005. this._projectionUpdateFlag = projection.updateFlag;
  25006. this._viewMatrix = view;
  25007. this._projectionMatrix = projection;
  25008. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25009. // Update frustum
  25010. if (!this._frustumPlanes) {
  25011. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25012. }
  25013. else {
  25014. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25015. }
  25016. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25017. var otherCamera = this.activeCamera._alternateCamera;
  25018. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25019. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25020. }
  25021. if (this._sceneUbo.useUbo) {
  25022. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25023. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25024. this._sceneUbo.update();
  25025. }
  25026. };
  25027. /** @ignore */
  25028. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25029. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25030. return;
  25031. }
  25032. this._alternateViewUpdateFlag = view.updateFlag;
  25033. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25034. this._alternateViewMatrix = view;
  25035. this._alternateProjectionMatrix = projection;
  25036. if (!this._alternateTransformMatrix) {
  25037. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25038. }
  25039. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25040. if (!this._alternateSceneUbo) {
  25041. this._createAlternateUbo();
  25042. }
  25043. if (this._alternateSceneUbo.useUbo) {
  25044. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25045. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25046. this._alternateSceneUbo.update();
  25047. }
  25048. };
  25049. /**
  25050. * Gets the uniform buffer used to store scene data
  25051. * @returns a UniformBuffer
  25052. */
  25053. Scene.prototype.getSceneUniformBuffer = function () {
  25054. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25055. };
  25056. /**
  25057. * Gets an unique (relatively to the current scene) Id
  25058. * @returns an unique number for the scene
  25059. */
  25060. Scene.prototype.getUniqueId = function () {
  25061. var result = Scene._uniqueIdCounter;
  25062. Scene._uniqueIdCounter++;
  25063. return result;
  25064. };
  25065. /**
  25066. * Add a mesh to the list of scene's meshes
  25067. * @param newMesh defines the mesh to add
  25068. */
  25069. Scene.prototype.addMesh = function (newMesh) {
  25070. this.meshes.push(newMesh);
  25071. //notify the collision coordinator
  25072. if (this.collisionCoordinator) {
  25073. this.collisionCoordinator.onMeshAdded(newMesh);
  25074. }
  25075. newMesh._resyncLightSources();
  25076. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25077. };
  25078. /**
  25079. * Remove a mesh for the list of scene's meshes
  25080. * @param toRemove defines the mesh to remove
  25081. * @returns the index where the mesh was in the mesh list
  25082. */
  25083. Scene.prototype.removeMesh = function (toRemove) {
  25084. var index = this.meshes.indexOf(toRemove);
  25085. if (index !== -1) {
  25086. // Remove from the scene if mesh found
  25087. this.meshes.splice(index, 1);
  25088. }
  25089. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25090. return index;
  25091. };
  25092. /**
  25093. * Add a transform node to the list of scene's transform nodes
  25094. * @param newTransformNode defines the transform node to add
  25095. */
  25096. Scene.prototype.addTransformNode = function (newTransformNode) {
  25097. this.transformNodes.push(newTransformNode);
  25098. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25099. };
  25100. /**
  25101. * Remove a transform node for the list of scene's transform nodes
  25102. * @param toRemove defines the transform node to remove
  25103. * @returns the index where the transform node was in the transform node list
  25104. */
  25105. Scene.prototype.removeTransformNode = function (toRemove) {
  25106. var index = this.transformNodes.indexOf(toRemove);
  25107. if (index !== -1) {
  25108. // Remove from the scene if found
  25109. this.transformNodes.splice(index, 1);
  25110. }
  25111. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25112. return index;
  25113. };
  25114. /**
  25115. * Remove a skeleton for the list of scene's skeletons
  25116. * @param toRemove defines the skeleton to remove
  25117. * @returns the index where the skeleton was in the skeleton list
  25118. */
  25119. Scene.prototype.removeSkeleton = function (toRemove) {
  25120. var index = this.skeletons.indexOf(toRemove);
  25121. if (index !== -1) {
  25122. // Remove from the scene if found
  25123. this.skeletons.splice(index, 1);
  25124. }
  25125. return index;
  25126. };
  25127. /**
  25128. * Remove a morph target for the list of scene's morph targets
  25129. * @param toRemove defines the morph target to remove
  25130. * @returns the index where the morph target was in the morph target list
  25131. */
  25132. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25133. var index = this.morphTargetManagers.indexOf(toRemove);
  25134. if (index !== -1) {
  25135. // Remove from the scene if found
  25136. this.morphTargetManagers.splice(index, 1);
  25137. }
  25138. return index;
  25139. };
  25140. /**
  25141. * Remove a light for the list of scene's lights
  25142. * @param toRemove defines the light to remove
  25143. * @returns the index where the light was in the light list
  25144. */
  25145. Scene.prototype.removeLight = function (toRemove) {
  25146. var index = this.lights.indexOf(toRemove);
  25147. if (index !== -1) {
  25148. // Remove from meshes
  25149. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25150. var mesh = _a[_i];
  25151. mesh._removeLightSource(toRemove);
  25152. }
  25153. // Remove from the scene if mesh found
  25154. this.lights.splice(index, 1);
  25155. this.sortLightsByPriority();
  25156. }
  25157. this.onLightRemovedObservable.notifyObservers(toRemove);
  25158. return index;
  25159. };
  25160. /**
  25161. * Remove a camera for the list of scene's cameras
  25162. * @param toRemove defines the camera to remove
  25163. * @returns the index where the camera was in the camera list
  25164. */
  25165. Scene.prototype.removeCamera = function (toRemove) {
  25166. var index = this.cameras.indexOf(toRemove);
  25167. if (index !== -1) {
  25168. // Remove from the scene if mesh found
  25169. this.cameras.splice(index, 1);
  25170. }
  25171. // Remove from activeCameras
  25172. var index2 = this.activeCameras.indexOf(toRemove);
  25173. if (index2 !== -1) {
  25174. // Remove from the scene if mesh found
  25175. this.activeCameras.splice(index2, 1);
  25176. }
  25177. // Reset the activeCamera
  25178. if (this.activeCamera === toRemove) {
  25179. if (this.cameras.length > 0) {
  25180. this.activeCamera = this.cameras[0];
  25181. }
  25182. else {
  25183. this.activeCamera = null;
  25184. }
  25185. }
  25186. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25187. return index;
  25188. };
  25189. /**
  25190. * Remove a particle system for the list of scene's particle systems
  25191. * @param toRemove defines the particle system to remove
  25192. * @returns the index where the particle system was in the particle system list
  25193. */
  25194. Scene.prototype.removeParticleSystem = function (toRemove) {
  25195. var index = this.particleSystems.indexOf(toRemove);
  25196. if (index !== -1) {
  25197. this.particleSystems.splice(index, 1);
  25198. }
  25199. return index;
  25200. };
  25201. /**
  25202. * Remove a animation for the list of scene's animations
  25203. * @param toRemove defines the animation to remove
  25204. * @returns the index where the animation was in the animation list
  25205. */
  25206. Scene.prototype.removeAnimation = function (toRemove) {
  25207. var index = this.animations.indexOf(toRemove);
  25208. if (index !== -1) {
  25209. this.animations.splice(index, 1);
  25210. }
  25211. return index;
  25212. };
  25213. /**
  25214. * Removes the given animation group from this scene.
  25215. * @param toRemove The animation group to remove
  25216. * @returns The index of the removed animation group
  25217. */
  25218. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25219. var index = this.animationGroups.indexOf(toRemove);
  25220. if (index !== -1) {
  25221. this.animationGroups.splice(index, 1);
  25222. }
  25223. return index;
  25224. };
  25225. /**
  25226. * Removes the given multi-material from this scene.
  25227. * @param toRemove The multi-material to remove
  25228. * @returns The index of the removed multi-material
  25229. */
  25230. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25231. var index = this.multiMaterials.indexOf(toRemove);
  25232. if (index !== -1) {
  25233. this.multiMaterials.splice(index, 1);
  25234. }
  25235. return index;
  25236. };
  25237. /**
  25238. * Removes the given material from this scene.
  25239. * @param toRemove The material to remove
  25240. * @returns The index of the removed material
  25241. */
  25242. Scene.prototype.removeMaterial = function (toRemove) {
  25243. var index = this.materials.indexOf(toRemove);
  25244. if (index !== -1) {
  25245. this.materials.splice(index, 1);
  25246. }
  25247. return index;
  25248. };
  25249. /**
  25250. * Removes the given lens flare system from this scene.
  25251. * @param toRemove The lens flare system to remove
  25252. * @returns The index of the removed lens flare system
  25253. */
  25254. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25255. var index = this.lensFlareSystems.indexOf(toRemove);
  25256. if (index !== -1) {
  25257. this.lensFlareSystems.splice(index, 1);
  25258. }
  25259. return index;
  25260. };
  25261. /**
  25262. * Removes the given action manager from this scene.
  25263. * @param toRemove The action manager to remove
  25264. * @returns The index of the removed action manager
  25265. */
  25266. Scene.prototype.removeActionManager = function (toRemove) {
  25267. var index = this._actionManagers.indexOf(toRemove);
  25268. if (index !== -1) {
  25269. this._actionManagers.splice(index, 1);
  25270. }
  25271. return index;
  25272. };
  25273. /**
  25274. * Removes the given texture from this scene.
  25275. * @param toRemove The texture to remove
  25276. * @returns The index of the removed texture
  25277. */
  25278. Scene.prototype.removeTexture = function (toRemove) {
  25279. var index = this.textures.indexOf(toRemove);
  25280. if (index !== -1) {
  25281. this.textures.splice(index, 1);
  25282. }
  25283. return index;
  25284. };
  25285. /**
  25286. * Adds the given light to this scene
  25287. * @param newLight The light to add
  25288. */
  25289. Scene.prototype.addLight = function (newLight) {
  25290. this.lights.push(newLight);
  25291. this.sortLightsByPriority();
  25292. // Add light to all meshes (To support if the light is removed and then readded)
  25293. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25294. var mesh = _a[_i];
  25295. if (mesh._lightSources.indexOf(newLight) === -1) {
  25296. mesh._lightSources.push(newLight);
  25297. mesh._resyncLightSources();
  25298. }
  25299. }
  25300. this.onNewLightAddedObservable.notifyObservers(newLight);
  25301. };
  25302. /**
  25303. * Sorts the list list based on light priorities
  25304. */
  25305. Scene.prototype.sortLightsByPriority = function () {
  25306. if (this.requireLightSorting) {
  25307. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25308. }
  25309. };
  25310. /**
  25311. * Adds the given camera to this scene
  25312. * @param newCamera The camera to add
  25313. */
  25314. Scene.prototype.addCamera = function (newCamera) {
  25315. this.cameras.push(newCamera);
  25316. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25317. };
  25318. /**
  25319. * Adds the given skeleton to this scene
  25320. * @param newSkeleton The skeleton to add
  25321. */
  25322. Scene.prototype.addSkeleton = function (newSkeleton) {
  25323. this.skeletons.push(newSkeleton);
  25324. };
  25325. /**
  25326. * Adds the given particle system to this scene
  25327. * @param newParticleSystem The particle system to add
  25328. */
  25329. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25330. this.particleSystems.push(newParticleSystem);
  25331. };
  25332. /**
  25333. * Adds the given animation to this scene
  25334. * @param newAnimation The animation to add
  25335. */
  25336. Scene.prototype.addAnimation = function (newAnimation) {
  25337. this.animations.push(newAnimation);
  25338. };
  25339. /**
  25340. * Adds the given animation group to this scene.
  25341. * @param newAnimationGroup The animation group to add
  25342. */
  25343. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25344. this.animationGroups.push(newAnimationGroup);
  25345. };
  25346. /**
  25347. * Adds the given multi-material to this scene
  25348. * @param newMultiMaterial The multi-material to add
  25349. */
  25350. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25351. this.multiMaterials.push(newMultiMaterial);
  25352. };
  25353. /**
  25354. * Adds the given material to this scene
  25355. * @param newMaterial The material to add
  25356. */
  25357. Scene.prototype.addMaterial = function (newMaterial) {
  25358. this.materials.push(newMaterial);
  25359. };
  25360. /**
  25361. * Adds the given morph target to this scene
  25362. * @param newMorphTargetManager The morph target to add
  25363. */
  25364. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25365. this.morphTargetManagers.push(newMorphTargetManager);
  25366. };
  25367. /**
  25368. * Adds the given geometry to this scene
  25369. * @param newGeometry The geometry to add
  25370. */
  25371. Scene.prototype.addGeometry = function (newGeometry) {
  25372. this._geometries.push(newGeometry);
  25373. };
  25374. /**
  25375. * Adds the given lens flare system to this scene
  25376. * @param newLensFlareSystem The lens flare system to add
  25377. */
  25378. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25379. this.lensFlareSystems.push(newLensFlareSystem);
  25380. };
  25381. /**
  25382. * Adds the given action manager to this scene
  25383. * @param newActionManager The action manager to add
  25384. */
  25385. Scene.prototype.addActionManager = function (newActionManager) {
  25386. this._actionManagers.push(newActionManager);
  25387. };
  25388. /**
  25389. * Adds the given texture to this scene.
  25390. * @param newTexture The texture to add
  25391. */
  25392. Scene.prototype.addTexture = function (newTexture) {
  25393. this.textures.push(newTexture);
  25394. };
  25395. /**
  25396. * Switch active camera
  25397. * @param newCamera defines the new active camera
  25398. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25399. */
  25400. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  25401. if (attachControl === void 0) { attachControl = true; }
  25402. var canvas = this._engine.getRenderingCanvas();
  25403. if (!canvas) {
  25404. return;
  25405. }
  25406. if (this.activeCamera) {
  25407. this.activeCamera.detachControl(canvas);
  25408. }
  25409. this.activeCamera = newCamera;
  25410. if (attachControl) {
  25411. newCamera.attachControl(canvas);
  25412. }
  25413. };
  25414. /**
  25415. * sets the active camera of the scene using its ID
  25416. * @param id defines the camera's ID
  25417. * @return the new active camera or null if none found.
  25418. */
  25419. Scene.prototype.setActiveCameraByID = function (id) {
  25420. var camera = this.getCameraByID(id);
  25421. if (camera) {
  25422. this.activeCamera = camera;
  25423. return camera;
  25424. }
  25425. return null;
  25426. };
  25427. /**
  25428. * sets the active camera of the scene using its name
  25429. * @param name defines the camera's name
  25430. * @returns the new active camera or null if none found.
  25431. */
  25432. Scene.prototype.setActiveCameraByName = function (name) {
  25433. var camera = this.getCameraByName(name);
  25434. if (camera) {
  25435. this.activeCamera = camera;
  25436. return camera;
  25437. }
  25438. return null;
  25439. };
  25440. /**
  25441. * get an animation group using its name
  25442. * @param name defines the material's name
  25443. * @return the animation group or null if none found.
  25444. */
  25445. Scene.prototype.getAnimationGroupByName = function (name) {
  25446. for (var index = 0; index < this.animationGroups.length; index++) {
  25447. if (this.animationGroups[index].name === name) {
  25448. return this.animationGroups[index];
  25449. }
  25450. }
  25451. return null;
  25452. };
  25453. /**
  25454. * get a material using its id
  25455. * @param id defines the material's ID
  25456. * @return the material or null if none found.
  25457. */
  25458. Scene.prototype.getMaterialByID = function (id) {
  25459. for (var index = 0; index < this.materials.length; index++) {
  25460. if (this.materials[index].id === id) {
  25461. return this.materials[index];
  25462. }
  25463. }
  25464. return null;
  25465. };
  25466. /**
  25467. * Gets a material using its name
  25468. * @param name defines the material's name
  25469. * @return the material or null if none found.
  25470. */
  25471. Scene.prototype.getMaterialByName = function (name) {
  25472. for (var index = 0; index < this.materials.length; index++) {
  25473. if (this.materials[index].name === name) {
  25474. return this.materials[index];
  25475. }
  25476. }
  25477. return null;
  25478. };
  25479. /**
  25480. * Gets a lens flare system using its name
  25481. * @param name defines the name to look for
  25482. * @returns the lens flare system or null if not found
  25483. */
  25484. Scene.prototype.getLensFlareSystemByName = function (name) {
  25485. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25486. if (this.lensFlareSystems[index].name === name) {
  25487. return this.lensFlareSystems[index];
  25488. }
  25489. }
  25490. return null;
  25491. };
  25492. /**
  25493. * Gets a lens flare system using its id
  25494. * @param id defines the id to look for
  25495. * @returns the lens flare system or null if not found
  25496. */
  25497. Scene.prototype.getLensFlareSystemByID = function (id) {
  25498. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25499. if (this.lensFlareSystems[index].id === id) {
  25500. return this.lensFlareSystems[index];
  25501. }
  25502. }
  25503. return null;
  25504. };
  25505. /**
  25506. * Gets a camera using its id
  25507. * @param id defines the id to look for
  25508. * @returns the camera or null if not found
  25509. */
  25510. Scene.prototype.getCameraByID = function (id) {
  25511. for (var index = 0; index < this.cameras.length; index++) {
  25512. if (this.cameras[index].id === id) {
  25513. return this.cameras[index];
  25514. }
  25515. }
  25516. return null;
  25517. };
  25518. /**
  25519. * Gets a camera using its unique id
  25520. * @param uniqueId defines the unique id to look for
  25521. * @returns the camera or null if not found
  25522. */
  25523. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  25524. for (var index = 0; index < this.cameras.length; index++) {
  25525. if (this.cameras[index].uniqueId === uniqueId) {
  25526. return this.cameras[index];
  25527. }
  25528. }
  25529. return null;
  25530. };
  25531. /**
  25532. * Gets a camera using its name
  25533. * @param name defines the camera's name
  25534. * @return the camera or null if none found.
  25535. */
  25536. Scene.prototype.getCameraByName = function (name) {
  25537. for (var index = 0; index < this.cameras.length; index++) {
  25538. if (this.cameras[index].name === name) {
  25539. return this.cameras[index];
  25540. }
  25541. }
  25542. return null;
  25543. };
  25544. /**
  25545. * Gets a bone using its id
  25546. * @param id defines the bone's id
  25547. * @return the bone or null if not found
  25548. */
  25549. Scene.prototype.getBoneByID = function (id) {
  25550. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25551. var skeleton = this.skeletons[skeletonIndex];
  25552. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25553. if (skeleton.bones[boneIndex].id === id) {
  25554. return skeleton.bones[boneIndex];
  25555. }
  25556. }
  25557. }
  25558. return null;
  25559. };
  25560. /**
  25561. * Gets a bone using its id
  25562. * @param name defines the bone's name
  25563. * @return the bone or null if not found
  25564. */
  25565. Scene.prototype.getBoneByName = function (name) {
  25566. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25567. var skeleton = this.skeletons[skeletonIndex];
  25568. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25569. if (skeleton.bones[boneIndex].name === name) {
  25570. return skeleton.bones[boneIndex];
  25571. }
  25572. }
  25573. }
  25574. return null;
  25575. };
  25576. /**
  25577. * Gets a light node using its name
  25578. * @param name defines the the light's name
  25579. * @return the light or null if none found.
  25580. */
  25581. Scene.prototype.getLightByName = function (name) {
  25582. for (var index = 0; index < this.lights.length; index++) {
  25583. if (this.lights[index].name === name) {
  25584. return this.lights[index];
  25585. }
  25586. }
  25587. return null;
  25588. };
  25589. /**
  25590. * Gets a light node using its id
  25591. * @param id defines the light's id
  25592. * @return the light or null if none found.
  25593. */
  25594. Scene.prototype.getLightByID = function (id) {
  25595. for (var index = 0; index < this.lights.length; index++) {
  25596. if (this.lights[index].id === id) {
  25597. return this.lights[index];
  25598. }
  25599. }
  25600. return null;
  25601. };
  25602. /**
  25603. * Gets a light node using its scene-generated unique ID
  25604. * @param uniqueId defines the light's unique id
  25605. * @return the light or null if none found.
  25606. */
  25607. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  25608. for (var index = 0; index < this.lights.length; index++) {
  25609. if (this.lights[index].uniqueId === uniqueId) {
  25610. return this.lights[index];
  25611. }
  25612. }
  25613. return null;
  25614. };
  25615. /**
  25616. * Gets a particle system by id
  25617. * @param id defines the particle system id
  25618. * @return the corresponding system or null if none found
  25619. */
  25620. Scene.prototype.getParticleSystemByID = function (id) {
  25621. for (var index = 0; index < this.particleSystems.length; index++) {
  25622. if (this.particleSystems[index].id === id) {
  25623. return this.particleSystems[index];
  25624. }
  25625. }
  25626. return null;
  25627. };
  25628. /**
  25629. * Gets a geometry using its ID
  25630. * @param id defines the geometry's id
  25631. * @return the geometry or null if none found.
  25632. */
  25633. Scene.prototype.getGeometryByID = function (id) {
  25634. for (var index = 0; index < this._geometries.length; index++) {
  25635. if (this._geometries[index].id === id) {
  25636. return this._geometries[index];
  25637. }
  25638. }
  25639. return null;
  25640. };
  25641. /**
  25642. * Add a new geometry to this scene
  25643. * @param geometry defines the geometry to be added to the scene.
  25644. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  25645. * @return a boolean defining if the geometry was added or not
  25646. */
  25647. Scene.prototype.pushGeometry = function (geometry, force) {
  25648. if (!force && this.getGeometryByID(geometry.id)) {
  25649. return false;
  25650. }
  25651. this._geometries.push(geometry);
  25652. //notify the collision coordinator
  25653. if (this.collisionCoordinator) {
  25654. this.collisionCoordinator.onGeometryAdded(geometry);
  25655. }
  25656. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  25657. return true;
  25658. };
  25659. /**
  25660. * Removes an existing geometry
  25661. * @param geometry defines the geometry to be removed from the scene
  25662. * @return a boolean defining if the geometry was removed or not
  25663. */
  25664. Scene.prototype.removeGeometry = function (geometry) {
  25665. var index = this._geometries.indexOf(geometry);
  25666. if (index > -1) {
  25667. this._geometries.splice(index, 1);
  25668. //notify the collision coordinator
  25669. if (this.collisionCoordinator) {
  25670. this.collisionCoordinator.onGeometryDeleted(geometry);
  25671. }
  25672. this.onGeometryRemovedObservable.notifyObservers(geometry);
  25673. return true;
  25674. }
  25675. return false;
  25676. };
  25677. /**
  25678. * Gets the list of geometries attached to the scene
  25679. * @returns an array of Geometry
  25680. */
  25681. Scene.prototype.getGeometries = function () {
  25682. return this._geometries;
  25683. };
  25684. /**
  25685. * Gets the first added mesh found of a given ID
  25686. * @param id defines the id to search for
  25687. * @return the mesh found or null if not found at all
  25688. */
  25689. Scene.prototype.getMeshByID = function (id) {
  25690. for (var index = 0; index < this.meshes.length; index++) {
  25691. if (this.meshes[index].id === id) {
  25692. return this.meshes[index];
  25693. }
  25694. }
  25695. return null;
  25696. };
  25697. /**
  25698. * Gets a list of meshes using their id
  25699. * @param id defines the id to search for
  25700. * @returns a list of meshes
  25701. */
  25702. Scene.prototype.getMeshesByID = function (id) {
  25703. return this.meshes.filter(function (m) {
  25704. return m.id === id;
  25705. });
  25706. };
  25707. /**
  25708. * Gets the first added transform node found of a given ID
  25709. * @param id defines the id to search for
  25710. * @return the found transform node or null if not found at all.
  25711. */
  25712. Scene.prototype.getTransformNodeByID = function (id) {
  25713. for (var index = 0; index < this.transformNodes.length; index++) {
  25714. if (this.transformNodes[index].id === id) {
  25715. return this.transformNodes[index];
  25716. }
  25717. }
  25718. return null;
  25719. };
  25720. /**
  25721. * Gets a list of transform nodes using their id
  25722. * @param id defines the id to search for
  25723. * @returns a list of transform nodes
  25724. */
  25725. Scene.prototype.getTransformNodesByID = function (id) {
  25726. return this.transformNodes.filter(function (m) {
  25727. return m.id === id;
  25728. });
  25729. };
  25730. /**
  25731. * Gets a mesh with its auto-generated unique id
  25732. * @param uniqueId defines the unique id to search for
  25733. * @return the found mesh or null if not found at all.
  25734. */
  25735. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  25736. for (var index = 0; index < this.meshes.length; index++) {
  25737. if (this.meshes[index].uniqueId === uniqueId) {
  25738. return this.meshes[index];
  25739. }
  25740. }
  25741. return null;
  25742. };
  25743. /**
  25744. * Gets a the last added mesh using a given id
  25745. * @param id defines the id to search for
  25746. * @return the found mesh or null if not found at all.
  25747. */
  25748. Scene.prototype.getLastMeshByID = function (id) {
  25749. for (var index = this.meshes.length - 1; index >= 0; index--) {
  25750. if (this.meshes[index].id === id) {
  25751. return this.meshes[index];
  25752. }
  25753. }
  25754. return null;
  25755. };
  25756. /**
  25757. * Gets a the last added node (Mesh, Camera, Light) using a given id
  25758. * @param id defines the id to search for
  25759. * @return the found node or null if not found at all
  25760. */
  25761. Scene.prototype.getLastEntryByID = function (id) {
  25762. var index;
  25763. for (index = this.meshes.length - 1; index >= 0; index--) {
  25764. if (this.meshes[index].id === id) {
  25765. return this.meshes[index];
  25766. }
  25767. }
  25768. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  25769. if (this.transformNodes[index].id === id) {
  25770. return this.transformNodes[index];
  25771. }
  25772. }
  25773. for (index = this.cameras.length - 1; index >= 0; index--) {
  25774. if (this.cameras[index].id === id) {
  25775. return this.cameras[index];
  25776. }
  25777. }
  25778. for (index = this.lights.length - 1; index >= 0; index--) {
  25779. if (this.lights[index].id === id) {
  25780. return this.lights[index];
  25781. }
  25782. }
  25783. return null;
  25784. };
  25785. /**
  25786. * Gets a node (Mesh, Camera, Light) using a given id
  25787. * @param id defines the id to search for
  25788. * @return the found node or null if not found at all
  25789. */
  25790. Scene.prototype.getNodeByID = function (id) {
  25791. var mesh = this.getMeshByID(id);
  25792. if (mesh) {
  25793. return mesh;
  25794. }
  25795. var light = this.getLightByID(id);
  25796. if (light) {
  25797. return light;
  25798. }
  25799. var camera = this.getCameraByID(id);
  25800. if (camera) {
  25801. return camera;
  25802. }
  25803. var bone = this.getBoneByID(id);
  25804. return bone;
  25805. };
  25806. /**
  25807. * Gets a node (Mesh, Camera, Light) using a given name
  25808. * @param name defines the name to search for
  25809. * @return the found node or null if not found at all.
  25810. */
  25811. Scene.prototype.getNodeByName = function (name) {
  25812. var mesh = this.getMeshByName(name);
  25813. if (mesh) {
  25814. return mesh;
  25815. }
  25816. var light = this.getLightByName(name);
  25817. if (light) {
  25818. return light;
  25819. }
  25820. var camera = this.getCameraByName(name);
  25821. if (camera) {
  25822. return camera;
  25823. }
  25824. var bone = this.getBoneByName(name);
  25825. return bone;
  25826. };
  25827. /**
  25828. * Gets a mesh using a given name
  25829. * @param name defines the name to search for
  25830. * @return the found mesh or null if not found at all.
  25831. */
  25832. Scene.prototype.getMeshByName = function (name) {
  25833. for (var index = 0; index < this.meshes.length; index++) {
  25834. if (this.meshes[index].name === name) {
  25835. return this.meshes[index];
  25836. }
  25837. }
  25838. return null;
  25839. };
  25840. /**
  25841. * Gets a transform node using a given name
  25842. * @param name defines the name to search for
  25843. * @return the found transform node or null if not found at all.
  25844. */
  25845. Scene.prototype.getTransformNodeByName = function (name) {
  25846. for (var index = 0; index < this.transformNodes.length; index++) {
  25847. if (this.transformNodes[index].name === name) {
  25848. return this.transformNodes[index];
  25849. }
  25850. }
  25851. return null;
  25852. };
  25853. /**
  25854. * Gets a sound using a given name
  25855. * @param name defines the name to search for
  25856. * @return the found sound or null if not found at all.
  25857. */
  25858. Scene.prototype.getSoundByName = function (name) {
  25859. var index;
  25860. if (BABYLON.AudioEngine) {
  25861. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  25862. if (this.mainSoundTrack.soundCollection[index].name === name) {
  25863. return this.mainSoundTrack.soundCollection[index];
  25864. }
  25865. }
  25866. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  25867. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  25868. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  25869. return this.soundTracks[sdIndex].soundCollection[index];
  25870. }
  25871. }
  25872. }
  25873. }
  25874. return null;
  25875. };
  25876. /**
  25877. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  25878. * @param id defines the id to search for
  25879. * @return the found skeleton or null if not found at all.
  25880. */
  25881. Scene.prototype.getLastSkeletonByID = function (id) {
  25882. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  25883. if (this.skeletons[index].id === id) {
  25884. return this.skeletons[index];
  25885. }
  25886. }
  25887. return null;
  25888. };
  25889. /**
  25890. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  25891. * @param id defines the id to search for
  25892. * @return the found skeleton or null if not found at all.
  25893. */
  25894. Scene.prototype.getSkeletonById = function (id) {
  25895. for (var index = 0; index < this.skeletons.length; index++) {
  25896. if (this.skeletons[index].id === id) {
  25897. return this.skeletons[index];
  25898. }
  25899. }
  25900. return null;
  25901. };
  25902. /**
  25903. * Gets a skeleton using a given name
  25904. * @param name defines the name to search for
  25905. * @return the found skeleton or null if not found at all.
  25906. */
  25907. Scene.prototype.getSkeletonByName = function (name) {
  25908. for (var index = 0; index < this.skeletons.length; index++) {
  25909. if (this.skeletons[index].name === name) {
  25910. return this.skeletons[index];
  25911. }
  25912. }
  25913. return null;
  25914. };
  25915. /**
  25916. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  25917. * @param id defines the id to search for
  25918. * @return the found morph target manager or null if not found at all.
  25919. */
  25920. Scene.prototype.getMorphTargetManagerById = function (id) {
  25921. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  25922. if (this.morphTargetManagers[index].uniqueId === id) {
  25923. return this.morphTargetManagers[index];
  25924. }
  25925. }
  25926. return null;
  25927. };
  25928. /**
  25929. * Gets a boolean indicating if the given mesh is active
  25930. * @param mesh defines the mesh to look for
  25931. * @returns true if the mesh is in the active list
  25932. */
  25933. Scene.prototype.isActiveMesh = function (mesh) {
  25934. return (this._activeMeshes.indexOf(mesh) !== -1);
  25935. };
  25936. /**
  25937. * Return a the first highlight layer of the scene with a given name.
  25938. * @param name The name of the highlight layer to look for.
  25939. * @return The highlight layer if found otherwise null.
  25940. */
  25941. Scene.prototype.getHighlightLayerByName = function (name) {
  25942. for (var index = 0; index < this.effectLayers.length; index++) {
  25943. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  25944. return this.effectLayers[index];
  25945. }
  25946. }
  25947. return null;
  25948. };
  25949. /**
  25950. * Return a the first highlight layer of the scene with a given name.
  25951. * @param name The name of the highlight layer to look for.
  25952. * @return The highlight layer if found otherwise null.
  25953. */
  25954. Scene.prototype.getGlowLayerByName = function (name) {
  25955. for (var index = 0; index < this.effectLayers.length; index++) {
  25956. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  25957. return this.effectLayers[index];
  25958. }
  25959. }
  25960. return null;
  25961. };
  25962. Object.defineProperty(Scene.prototype, "uid", {
  25963. /**
  25964. * Return a unique id as a string which can serve as an identifier for the scene
  25965. */
  25966. get: function () {
  25967. if (!this._uid) {
  25968. this._uid = BABYLON.Tools.RandomId();
  25969. }
  25970. return this._uid;
  25971. },
  25972. enumerable: true,
  25973. configurable: true
  25974. });
  25975. /**
  25976. * Add an externaly attached data from its key.
  25977. * This method call will fail and return false, if such key already exists.
  25978. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  25979. * @param key the unique key that identifies the data
  25980. * @param data the data object to associate to the key for this Engine instance
  25981. * @return true if no such key were already present and the data was added successfully, false otherwise
  25982. */
  25983. Scene.prototype.addExternalData = function (key, data) {
  25984. if (!this._externalData) {
  25985. this._externalData = new BABYLON.StringDictionary();
  25986. }
  25987. return this._externalData.add(key, data);
  25988. };
  25989. /**
  25990. * Get an externaly attached data from its key
  25991. * @param key the unique key that identifies the data
  25992. * @return the associated data, if present (can be null), or undefined if not present
  25993. */
  25994. Scene.prototype.getExternalData = function (key) {
  25995. if (!this._externalData) {
  25996. return null;
  25997. }
  25998. return this._externalData.get(key);
  25999. };
  26000. /**
  26001. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26002. * @param key the unique key that identifies the data
  26003. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26004. * @return the associated data, can be null if the factory returned null.
  26005. */
  26006. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26007. if (!this._externalData) {
  26008. this._externalData = new BABYLON.StringDictionary();
  26009. }
  26010. return this._externalData.getOrAddWithFactory(key, factory);
  26011. };
  26012. /**
  26013. * Remove an externaly attached data from the Engine instance
  26014. * @param key the unique key that identifies the data
  26015. * @return true if the data was successfully removed, false if it doesn't exist
  26016. */
  26017. Scene.prototype.removeExternalData = function (key) {
  26018. return this._externalData.remove(key);
  26019. };
  26020. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26021. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26022. if (mesh.showSubMeshesBoundingBox) {
  26023. var boundingInfo = subMesh.getBoundingInfo();
  26024. if (boundingInfo !== null && boundingInfo !== undefined) {
  26025. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26026. }
  26027. }
  26028. var material = subMesh.getMaterial();
  26029. if (material !== null && material !== undefined) {
  26030. // Render targets
  26031. if (material.getRenderTargetTextures !== undefined) {
  26032. if (this._processedMaterials.indexOf(material) === -1) {
  26033. this._processedMaterials.push(material);
  26034. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26035. }
  26036. }
  26037. // Dispatch
  26038. this._activeIndices.addCount(subMesh.indexCount, false);
  26039. this._renderingManager.dispatch(subMesh, mesh, material);
  26040. }
  26041. }
  26042. };
  26043. /**
  26044. * Clear the processed materials smart array preventing retention point in material dispose.
  26045. */
  26046. Scene.prototype.freeProcessedMaterials = function () {
  26047. this._processedMaterials.dispose();
  26048. };
  26049. /**
  26050. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26051. */
  26052. Scene.prototype.freeActiveMeshes = function () {
  26053. this._activeMeshes.dispose();
  26054. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26055. this.activeCamera._activeMeshes.dispose();
  26056. }
  26057. if (this.activeCameras) {
  26058. for (var i = 0; i < this.activeCameras.length; i++) {
  26059. var activeCamera = this.activeCameras[i];
  26060. if (activeCamera && activeCamera._activeMeshes) {
  26061. activeCamera._activeMeshes.dispose();
  26062. }
  26063. }
  26064. }
  26065. };
  26066. /**
  26067. * Clear the info related to rendering groups preventing retention points during dispose.
  26068. */
  26069. Scene.prototype.freeRenderingGroups = function () {
  26070. if (this._renderingManager) {
  26071. this._renderingManager.freeRenderingGroups();
  26072. }
  26073. if (this.textures) {
  26074. for (var i = 0; i < this.textures.length; i++) {
  26075. var texture = this.textures[i];
  26076. if (texture && texture.renderList) {
  26077. texture.freeRenderingGroups();
  26078. }
  26079. }
  26080. }
  26081. };
  26082. /** @ignore */
  26083. Scene.prototype._isInIntermediateRendering = function () {
  26084. return this._intermediateRendering;
  26085. };
  26086. /**
  26087. * Defines the current active mesh candidate provider
  26088. * @param provider defines the provider to use
  26089. */
  26090. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26091. this._activeMeshCandidateProvider = provider;
  26092. };
  26093. /**
  26094. * Gets the current active mesh candidate provider
  26095. * @returns the current active mesh candidate provider
  26096. */
  26097. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26098. return this._activeMeshCandidateProvider;
  26099. };
  26100. /**
  26101. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26102. * @returns the current scene
  26103. */
  26104. Scene.prototype.freezeActiveMeshes = function () {
  26105. if (!this.activeCamera) {
  26106. return this;
  26107. }
  26108. if (!this._frustumPlanes) {
  26109. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26110. }
  26111. this._evaluateActiveMeshes();
  26112. this._activeMeshesFrozen = true;
  26113. return this;
  26114. };
  26115. /**
  26116. * Use this function to restart evaluating active meshes on every frame
  26117. * @returns the current scene
  26118. */
  26119. Scene.prototype.unfreezeActiveMeshes = function () {
  26120. this._activeMeshesFrozen = false;
  26121. return this;
  26122. };
  26123. Scene.prototype._evaluateActiveMeshes = function () {
  26124. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26125. return;
  26126. }
  26127. if (!this.activeCamera) {
  26128. return;
  26129. }
  26130. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26131. this.activeCamera._activeMeshes.reset();
  26132. this._activeMeshes.reset();
  26133. this._renderingManager.reset();
  26134. this._processedMaterials.reset();
  26135. this._activeParticleSystems.reset();
  26136. this._activeSkeletons.reset();
  26137. this._softwareSkinnedMeshes.reset();
  26138. if (this._boundingBoxRenderer) {
  26139. this._boundingBoxRenderer.reset();
  26140. }
  26141. // Meshes
  26142. var meshes;
  26143. var len;
  26144. var checkIsEnabled = true;
  26145. // Determine mesh candidates
  26146. if (this._activeMeshCandidateProvider !== undefined) {
  26147. // Use _activeMeshCandidateProvider
  26148. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26149. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26150. if (meshes !== undefined) {
  26151. len = meshes.length;
  26152. }
  26153. else {
  26154. len = 0;
  26155. }
  26156. }
  26157. else if (this._selectionOctree !== undefined) {
  26158. // Octree
  26159. var selection = this._selectionOctree.select(this._frustumPlanes);
  26160. meshes = selection.data;
  26161. len = selection.length;
  26162. }
  26163. else {
  26164. // Full scene traversal
  26165. len = this.meshes.length;
  26166. meshes = this.meshes;
  26167. }
  26168. // Check each mesh
  26169. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26170. mesh = meshes[meshIndex];
  26171. if (mesh.isBlocked) {
  26172. continue;
  26173. }
  26174. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26175. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26176. continue;
  26177. }
  26178. mesh.computeWorldMatrix();
  26179. // Intersections
  26180. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26181. this._meshesForIntersections.pushNoDuplicate(mesh);
  26182. }
  26183. // Switch to current LOD
  26184. meshLOD = mesh.getLOD(this.activeCamera);
  26185. if (meshLOD === undefined || meshLOD === null) {
  26186. continue;
  26187. }
  26188. mesh._preActivate();
  26189. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26190. this._activeMeshes.push(mesh);
  26191. this.activeCamera._activeMeshes.push(mesh);
  26192. mesh._activate(this._renderId);
  26193. if (meshLOD !== mesh) {
  26194. meshLOD._activate(this._renderId);
  26195. }
  26196. this._activeMesh(mesh, meshLOD);
  26197. }
  26198. }
  26199. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26200. // Particle systems
  26201. if (this.particlesEnabled) {
  26202. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26203. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26204. var particleSystem = this.particleSystems[particleIndex];
  26205. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26206. continue;
  26207. }
  26208. var emitter = particleSystem.emitter;
  26209. if (!emitter.position || emitter.isEnabled()) {
  26210. this._activeParticleSystems.push(particleSystem);
  26211. particleSystem.animate();
  26212. this._renderingManager.dispatchParticles(particleSystem);
  26213. }
  26214. }
  26215. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26216. }
  26217. };
  26218. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26219. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26220. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26221. mesh.skeleton.prepare();
  26222. }
  26223. if (!mesh.computeBonesUsingShaders) {
  26224. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26225. }
  26226. }
  26227. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26228. var boundingInfo = sourceMesh.getBoundingInfo();
  26229. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26230. }
  26231. if (mesh !== undefined && mesh !== null
  26232. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26233. // Submeshes Octrees
  26234. var len;
  26235. var subMeshes;
  26236. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26237. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26238. len = intersections.length;
  26239. subMeshes = intersections.data;
  26240. }
  26241. else {
  26242. subMeshes = mesh.subMeshes;
  26243. len = subMeshes.length;
  26244. }
  26245. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26246. subMesh = subMeshes[subIndex];
  26247. this._evaluateSubMesh(subMesh, mesh);
  26248. }
  26249. }
  26250. };
  26251. /**
  26252. * Update the transform matrix to update from the current active camera
  26253. * @param force defines a boolean used to force the update even if cache is up to date
  26254. */
  26255. Scene.prototype.updateTransformMatrix = function (force) {
  26256. if (!this.activeCamera) {
  26257. return;
  26258. }
  26259. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26260. };
  26261. /**
  26262. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  26263. * @param alternateCamera defines the camera to use
  26264. */
  26265. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26266. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26267. };
  26268. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26269. if (camera && camera._skipRendering) {
  26270. return;
  26271. }
  26272. var engine = this._engine;
  26273. this.activeCamera = camera;
  26274. if (!this.activeCamera)
  26275. throw new Error("Active camera not set");
  26276. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26277. // Viewport
  26278. engine.setViewport(this.activeCamera.viewport);
  26279. // Camera
  26280. this.resetCachedMaterial();
  26281. this._renderId++;
  26282. this.updateTransformMatrix();
  26283. if (camera._alternateCamera) {
  26284. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26285. this._alternateRendering = true;
  26286. }
  26287. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26288. // Meshes
  26289. this._evaluateActiveMeshes();
  26290. // Software skinning
  26291. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26292. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26293. mesh.applySkeleton(mesh.skeleton);
  26294. }
  26295. // Render targets
  26296. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26297. var needsRestoreFrameBuffer = false;
  26298. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26299. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26300. }
  26301. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26302. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26303. }
  26304. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26305. this._intermediateRendering = true;
  26306. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26307. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26308. var renderTarget = this._renderTargets.data[renderIndex];
  26309. if (renderTarget._shouldRender()) {
  26310. this._renderId++;
  26311. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26312. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26313. }
  26314. }
  26315. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26316. this._intermediateRendering = false;
  26317. this._renderId++;
  26318. needsRestoreFrameBuffer = true; // Restore back buffer
  26319. }
  26320. // Render EffecttLayer Texture
  26321. var stencilState = this._engine.getStencilBuffer();
  26322. var renderEffects = false;
  26323. var needStencil = false;
  26324. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26325. this._intermediateRendering = true;
  26326. for (var i = 0; i < this.effectLayers.length; i++) {
  26327. var effectLayer = this.effectLayers[i];
  26328. if (effectLayer.shouldRender() &&
  26329. (!effectLayer.camera ||
  26330. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26331. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26332. renderEffects = true;
  26333. needStencil = needStencil || effectLayer.needStencil();
  26334. var renderTarget = effectLayer._mainTexture;
  26335. if (renderTarget._shouldRender()) {
  26336. this._renderId++;
  26337. renderTarget.render(false, false);
  26338. needsRestoreFrameBuffer = true;
  26339. }
  26340. }
  26341. }
  26342. this._intermediateRendering = false;
  26343. this._renderId++;
  26344. }
  26345. if (needsRestoreFrameBuffer) {
  26346. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26347. }
  26348. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26349. // Prepare Frame
  26350. this.postProcessManager._prepareFrame();
  26351. // Backgrounds
  26352. var layerIndex;
  26353. var layer;
  26354. if (this.layers.length) {
  26355. engine.setDepthBuffer(false);
  26356. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26357. layer = this.layers[layerIndex];
  26358. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26359. layer.render();
  26360. }
  26361. }
  26362. engine.setDepthBuffer(true);
  26363. }
  26364. // Activate effect Layer stencil
  26365. if (needStencil) {
  26366. this._engine.setStencilBuffer(true);
  26367. }
  26368. // Render
  26369. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26370. this._renderingManager.render(null, null, true, true);
  26371. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26372. // Restore effect Layer stencil
  26373. if (needStencil) {
  26374. this._engine.setStencilBuffer(stencilState);
  26375. }
  26376. // Bounding boxes
  26377. if (this._boundingBoxRenderer) {
  26378. this._boundingBoxRenderer.render();
  26379. }
  26380. // Lens flares
  26381. if (this.lensFlaresEnabled) {
  26382. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26383. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26384. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26385. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26386. lensFlareSystem.render();
  26387. }
  26388. }
  26389. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26390. }
  26391. // Effect Layer
  26392. if (renderEffects) {
  26393. engine.setDepthBuffer(false);
  26394. for (var i = 0; i < this.effectLayers.length; i++) {
  26395. if (this.effectLayers[i].shouldRender()) {
  26396. this.effectLayers[i].render();
  26397. }
  26398. }
  26399. engine.setDepthBuffer(true);
  26400. }
  26401. // Foregrounds
  26402. if (this.layers.length) {
  26403. engine.setDepthBuffer(false);
  26404. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26405. layer = this.layers[layerIndex];
  26406. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26407. layer.render();
  26408. }
  26409. }
  26410. engine.setDepthBuffer(true);
  26411. }
  26412. // Finalize frame
  26413. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  26414. // Reset some special arrays
  26415. this._renderTargets.reset();
  26416. this._alternateRendering = false;
  26417. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  26418. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26419. };
  26420. Scene.prototype._processSubCameras = function (camera) {
  26421. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  26422. this._renderForCamera(camera);
  26423. return;
  26424. }
  26425. // rig cameras
  26426. for (var index = 0; index < camera._rigCameras.length; index++) {
  26427. this._renderForCamera(camera._rigCameras[index], camera);
  26428. }
  26429. this.activeCamera = camera;
  26430. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26431. };
  26432. Scene.prototype._checkIntersections = function () {
  26433. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  26434. var sourceMesh = this._meshesForIntersections.data[index];
  26435. if (!sourceMesh.actionManager) {
  26436. continue;
  26437. }
  26438. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  26439. var action = sourceMesh.actionManager.actions[actionIndex];
  26440. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26441. var parameters = action.getTriggerParameter();
  26442. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  26443. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  26444. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  26445. if (areIntersecting && currentIntersectionInProgress === -1) {
  26446. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  26447. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26448. sourceMesh._intersectionsInProgress.push(otherMesh);
  26449. }
  26450. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26451. sourceMesh._intersectionsInProgress.push(otherMesh);
  26452. }
  26453. }
  26454. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  26455. //They intersected, and now they don't.
  26456. //is this trigger an exit trigger? execute an event.
  26457. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26458. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26459. }
  26460. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  26461. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26462. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  26463. }
  26464. }
  26465. }
  26466. }
  26467. }
  26468. };
  26469. /**
  26470. * Render the scene
  26471. */
  26472. Scene.prototype.render = function () {
  26473. if (this.isDisposed) {
  26474. return;
  26475. }
  26476. this._activeParticles.fetchNewFrame();
  26477. this._totalVertices.fetchNewFrame();
  26478. this._activeIndices.fetchNewFrame();
  26479. this._activeBones.fetchNewFrame();
  26480. this._meshesForIntersections.reset();
  26481. this.resetCachedMaterial();
  26482. this.onBeforeAnimationsObservable.notifyObservers(this);
  26483. // Actions
  26484. if (this.actionManager) {
  26485. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  26486. }
  26487. //Simplification Queue
  26488. if (this.simplificationQueue && !this.simplificationQueue.running) {
  26489. this.simplificationQueue.executeNext();
  26490. }
  26491. if (this._engine.isDeterministicLockStep()) {
  26492. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  26493. var defaultFPS = (60.0 / 1000.0);
  26494. var defaultFrameTime = 1000 / 60; // frame time in MS
  26495. if (this._physicsEngine) {
  26496. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  26497. }
  26498. var stepsTaken = 0;
  26499. var maxSubSteps = this._engine.getLockstepMaxSteps();
  26500. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  26501. internalSteps = Math.min(internalSteps, maxSubSteps);
  26502. do {
  26503. this.onBeforeStepObservable.notifyObservers(this);
  26504. // Animations
  26505. this._animationRatio = defaultFrameTime * defaultFPS;
  26506. this._animate();
  26507. this.onAfterAnimationsObservable.notifyObservers(this);
  26508. // Physics
  26509. if (this._physicsEngine) {
  26510. this.onBeforePhysicsObservable.notifyObservers(this);
  26511. this._physicsEngine._step(defaultFrameTime / 1000);
  26512. this.onAfterPhysicsObservable.notifyObservers(this);
  26513. }
  26514. this.onAfterStepObservable.notifyObservers(this);
  26515. this._currentStepId++;
  26516. stepsTaken++;
  26517. deltaTime -= defaultFrameTime;
  26518. } while (deltaTime > 0 && stepsTaken < internalSteps);
  26519. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  26520. }
  26521. else {
  26522. // Animations
  26523. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  26524. this._animationRatio = deltaTime * (60.0 / 1000.0);
  26525. this._animate();
  26526. this.onAfterAnimationsObservable.notifyObservers(this);
  26527. // Physics
  26528. if (this._physicsEngine) {
  26529. this.onBeforePhysicsObservable.notifyObservers(this);
  26530. this._physicsEngine._step(deltaTime / 1000.0);
  26531. this.onAfterPhysicsObservable.notifyObservers(this);
  26532. }
  26533. }
  26534. // update gamepad manager
  26535. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  26536. this._gamepadManager._checkGamepadsStatus();
  26537. }
  26538. // Update Cameras
  26539. if (this.activeCameras.length > 0) {
  26540. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26541. var camera = this.activeCameras[cameraIndex];
  26542. camera.update();
  26543. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26544. // rig cameras
  26545. for (var index = 0; index < camera._rigCameras.length; index++) {
  26546. camera._rigCameras[index].update();
  26547. }
  26548. }
  26549. }
  26550. }
  26551. else if (this.activeCamera) {
  26552. this.activeCamera.update();
  26553. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26554. // rig cameras
  26555. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  26556. this.activeCamera._rigCameras[index].update();
  26557. }
  26558. }
  26559. }
  26560. // Before render
  26561. this.onBeforeRenderObservable.notifyObservers(this);
  26562. // Customs render targets
  26563. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26564. var engine = this.getEngine();
  26565. var currentActiveCamera = this.activeCamera;
  26566. if (this.renderTargetsEnabled) {
  26567. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26568. this._intermediateRendering = true;
  26569. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  26570. var renderTarget = this.customRenderTargets[customIndex];
  26571. if (renderTarget._shouldRender()) {
  26572. this._renderId++;
  26573. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  26574. if (!this.activeCamera)
  26575. throw new Error("Active camera not set");
  26576. // Viewport
  26577. engine.setViewport(this.activeCamera.viewport);
  26578. // Camera
  26579. this.updateTransformMatrix();
  26580. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  26581. }
  26582. }
  26583. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26584. this._intermediateRendering = false;
  26585. this._renderId++;
  26586. }
  26587. // Restore back buffer
  26588. if (this.customRenderTargets.length > 0) {
  26589. engine.restoreDefaultFramebuffer();
  26590. }
  26591. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26592. this.activeCamera = currentActiveCamera;
  26593. // Procedural textures
  26594. if (this.proceduralTexturesEnabled) {
  26595. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26596. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  26597. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  26598. if (proceduralTexture._shouldRender()) {
  26599. proceduralTexture.render();
  26600. }
  26601. }
  26602. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26603. }
  26604. // Clear
  26605. if (this.autoClearDepthAndStencil || this.autoClear) {
  26606. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  26607. }
  26608. // Shadows
  26609. if (this.shadowsEnabled) {
  26610. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  26611. var light = this.lights[lightIndex];
  26612. var shadowGenerator = light.getShadowGenerator();
  26613. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  26614. var shadowMap = (shadowGenerator.getShadowMap());
  26615. if (this.textures.indexOf(shadowMap) !== -1) {
  26616. this._renderTargets.push(shadowMap);
  26617. }
  26618. }
  26619. }
  26620. }
  26621. // Depth renderer
  26622. for (var key in this._depthRenderer) {
  26623. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  26624. }
  26625. // Geometry renderer
  26626. if (this._geometryBufferRenderer) {
  26627. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  26628. }
  26629. // RenderPipeline
  26630. if (this._postProcessRenderPipelineManager) {
  26631. this._postProcessRenderPipelineManager.update();
  26632. }
  26633. // Multi-cameras?
  26634. if (this.activeCameras.length > 0) {
  26635. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26636. if (cameraIndex > 0) {
  26637. this._engine.clear(null, false, true, true);
  26638. }
  26639. this._processSubCameras(this.activeCameras[cameraIndex]);
  26640. }
  26641. }
  26642. else {
  26643. if (!this.activeCamera) {
  26644. throw new Error("No camera defined");
  26645. }
  26646. this._processSubCameras(this.activeCamera);
  26647. }
  26648. // Intersection checks
  26649. this._checkIntersections();
  26650. // Update the audio listener attached to the camera
  26651. if (BABYLON.AudioEngine) {
  26652. this._updateAudioParameters();
  26653. }
  26654. // After render
  26655. if (this.afterRender) {
  26656. this.afterRender();
  26657. }
  26658. this.onAfterRenderObservable.notifyObservers(this);
  26659. // Cleaning
  26660. for (var index = 0; index < this._toBeDisposed.length; index++) {
  26661. var data = this._toBeDisposed.data[index];
  26662. if (data) {
  26663. data.dispose();
  26664. }
  26665. this._toBeDisposed[index] = null;
  26666. }
  26667. this._toBeDisposed.reset();
  26668. if (this.dumpNextRenderTargets) {
  26669. this.dumpNextRenderTargets = false;
  26670. }
  26671. this._activeBones.addCount(0, true);
  26672. this._activeIndices.addCount(0, true);
  26673. this._activeParticles.addCount(0, true);
  26674. };
  26675. Scene.prototype._updateAudioParameters = function () {
  26676. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  26677. return;
  26678. }
  26679. var listeningCamera;
  26680. var audioEngine = BABYLON.Engine.audioEngine;
  26681. if (this.activeCameras.length > 0) {
  26682. listeningCamera = this.activeCameras[0];
  26683. }
  26684. else {
  26685. listeningCamera = this.activeCamera;
  26686. }
  26687. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  26688. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  26689. // for VR cameras
  26690. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  26691. listeningCamera = listeningCamera.rigCameras[0];
  26692. }
  26693. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  26694. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  26695. cameraDirection.normalize();
  26696. // To avoid some errors on GearVR
  26697. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  26698. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  26699. }
  26700. var i;
  26701. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26702. var sound = this.mainSoundTrack.soundCollection[i];
  26703. if (sound.useCustomAttenuation) {
  26704. sound.updateDistanceFromListener();
  26705. }
  26706. }
  26707. for (i = 0; i < this.soundTracks.length; i++) {
  26708. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26709. sound = this.soundTracks[i].soundCollection[j];
  26710. if (sound.useCustomAttenuation) {
  26711. sound.updateDistanceFromListener();
  26712. }
  26713. }
  26714. }
  26715. }
  26716. };
  26717. Object.defineProperty(Scene.prototype, "audioEnabled", {
  26718. // Audio
  26719. /**
  26720. * Gets or sets if audio support is enabled
  26721. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  26722. */
  26723. get: function () {
  26724. return this._audioEnabled;
  26725. },
  26726. set: function (value) {
  26727. this._audioEnabled = value;
  26728. if (BABYLON.AudioEngine) {
  26729. if (this._audioEnabled) {
  26730. this._enableAudio();
  26731. }
  26732. else {
  26733. this._disableAudio();
  26734. }
  26735. }
  26736. },
  26737. enumerable: true,
  26738. configurable: true
  26739. });
  26740. Scene.prototype._disableAudio = function () {
  26741. var i;
  26742. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26743. this.mainSoundTrack.soundCollection[i].pause();
  26744. }
  26745. for (i = 0; i < this.soundTracks.length; i++) {
  26746. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26747. this.soundTracks[i].soundCollection[j].pause();
  26748. }
  26749. }
  26750. };
  26751. Scene.prototype._enableAudio = function () {
  26752. var i;
  26753. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  26754. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  26755. this.mainSoundTrack.soundCollection[i].play();
  26756. }
  26757. }
  26758. for (i = 0; i < this.soundTracks.length; i++) {
  26759. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  26760. if (this.soundTracks[i].soundCollection[j].isPaused) {
  26761. this.soundTracks[i].soundCollection[j].play();
  26762. }
  26763. }
  26764. }
  26765. };
  26766. Object.defineProperty(Scene.prototype, "headphone", {
  26767. /**
  26768. * Gets or sets if audio will be output to headphones
  26769. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  26770. */
  26771. get: function () {
  26772. return this._headphone;
  26773. },
  26774. set: function (value) {
  26775. this._headphone = value;
  26776. if (BABYLON.AudioEngine) {
  26777. if (this._headphone) {
  26778. this._switchAudioModeForHeadphones();
  26779. }
  26780. else {
  26781. this._switchAudioModeForNormalSpeakers();
  26782. }
  26783. }
  26784. },
  26785. enumerable: true,
  26786. configurable: true
  26787. });
  26788. Scene.prototype._switchAudioModeForHeadphones = function () {
  26789. this.mainSoundTrack.switchPanningModelToHRTF();
  26790. for (var i = 0; i < this.soundTracks.length; i++) {
  26791. this.soundTracks[i].switchPanningModelToHRTF();
  26792. }
  26793. };
  26794. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  26795. this.mainSoundTrack.switchPanningModelToEqualPower();
  26796. for (var i = 0; i < this.soundTracks.length; i++) {
  26797. this.soundTracks[i].switchPanningModelToEqualPower();
  26798. }
  26799. };
  26800. /**
  26801. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  26802. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  26803. * @returns the created depth renderer
  26804. */
  26805. Scene.prototype.enableDepthRenderer = function (camera) {
  26806. camera = camera || this.activeCamera;
  26807. if (!camera) {
  26808. throw "No camera available to enable depth renderer";
  26809. }
  26810. if (!this._depthRenderer[camera.id]) {
  26811. var textureType = 0;
  26812. if (this._engine.getCaps().textureHalfFloatRender) {
  26813. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  26814. }
  26815. else if (this._engine.getCaps().textureFloatRender) {
  26816. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  26817. }
  26818. else {
  26819. throw "Depth renderer does not support int texture type";
  26820. }
  26821. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  26822. }
  26823. return this._depthRenderer[camera.id];
  26824. };
  26825. /**
  26826. * Disables a depth renderer for a given camera
  26827. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  26828. */
  26829. Scene.prototype.disableDepthRenderer = function (camera) {
  26830. camera = camera || this.activeCamera;
  26831. if (!camera || !this._depthRenderer[camera.id]) {
  26832. return;
  26833. }
  26834. this._depthRenderer[camera.id].dispose();
  26835. delete this._depthRenderer[camera.id];
  26836. };
  26837. /**
  26838. * Enables a GeometryBufferRender and associates it with the scene
  26839. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  26840. * @returns the GeometryBufferRenderer
  26841. */
  26842. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  26843. if (ratio === void 0) { ratio = 1; }
  26844. if (this._geometryBufferRenderer) {
  26845. return this._geometryBufferRenderer;
  26846. }
  26847. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  26848. if (!this._geometryBufferRenderer.isSupported) {
  26849. this._geometryBufferRenderer = null;
  26850. }
  26851. return this._geometryBufferRenderer;
  26852. };
  26853. /**
  26854. * Disables the GeometryBufferRender associated with the scene
  26855. */
  26856. Scene.prototype.disableGeometryBufferRenderer = function () {
  26857. if (!this._geometryBufferRenderer) {
  26858. return;
  26859. }
  26860. this._geometryBufferRenderer.dispose();
  26861. this._geometryBufferRenderer = null;
  26862. };
  26863. /**
  26864. * Freeze all materials
  26865. * A frozen material will not be updatable but should be faster to render
  26866. */
  26867. Scene.prototype.freezeMaterials = function () {
  26868. for (var i = 0; i < this.materials.length; i++) {
  26869. this.materials[i].freeze();
  26870. }
  26871. };
  26872. /**
  26873. * Unfreeze all materials
  26874. * A frozen material will not be updatable but should be faster to render
  26875. */
  26876. Scene.prototype.unfreezeMaterials = function () {
  26877. for (var i = 0; i < this.materials.length; i++) {
  26878. this.materials[i].unfreeze();
  26879. }
  26880. };
  26881. /**
  26882. * Releases all held ressources
  26883. */
  26884. Scene.prototype.dispose = function () {
  26885. this.beforeRender = null;
  26886. this.afterRender = null;
  26887. this.skeletons = [];
  26888. this.morphTargetManagers = [];
  26889. this.importedMeshesFiles = new Array();
  26890. this.stopAllAnimations();
  26891. this.resetCachedMaterial();
  26892. for (var key in this._depthRenderer) {
  26893. this._depthRenderer[key].dispose();
  26894. }
  26895. if (this._gamepadManager) {
  26896. this._gamepadManager.dispose();
  26897. this._gamepadManager = null;
  26898. }
  26899. // Smart arrays
  26900. if (this.activeCamera) {
  26901. this.activeCamera._activeMeshes.dispose();
  26902. this.activeCamera = null;
  26903. }
  26904. this._activeMeshes.dispose();
  26905. this._renderingManager.dispose();
  26906. this._processedMaterials.dispose();
  26907. this._activeParticleSystems.dispose();
  26908. this._activeSkeletons.dispose();
  26909. this._softwareSkinnedMeshes.dispose();
  26910. this._renderTargets.dispose();
  26911. this._registeredForLateAnimationBindings.dispose();
  26912. if (this._boundingBoxRenderer) {
  26913. this._boundingBoxRenderer.dispose();
  26914. }
  26915. this._meshesForIntersections.dispose();
  26916. this._toBeDisposed.dispose();
  26917. // Abort active requests
  26918. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  26919. var request = _a[_i];
  26920. request.abort();
  26921. }
  26922. // Debug layer
  26923. if (this._debugLayer) {
  26924. this._debugLayer.hide();
  26925. }
  26926. // Events
  26927. this.onDisposeObservable.notifyObservers(this);
  26928. this.onDisposeObservable.clear();
  26929. this.onBeforeRenderObservable.clear();
  26930. this.onAfterRenderObservable.clear();
  26931. this.onBeforeRenderTargetsRenderObservable.clear();
  26932. this.onAfterRenderTargetsRenderObservable.clear();
  26933. this.onAfterStepObservable.clear();
  26934. this.onBeforeStepObservable.clear();
  26935. this.onBeforeActiveMeshesEvaluationObservable.clear();
  26936. this.onAfterActiveMeshesEvaluationObservable.clear();
  26937. this.onBeforeParticlesRenderingObservable.clear();
  26938. this.onAfterParticlesRenderingObservable.clear();
  26939. this.onBeforeSpritesRenderingObservable.clear();
  26940. this.onAfterSpritesRenderingObservable.clear();
  26941. this.onBeforeDrawPhaseObservable.clear();
  26942. this.onAfterDrawPhaseObservable.clear();
  26943. this.onBeforePhysicsObservable.clear();
  26944. this.onAfterPhysicsObservable.clear();
  26945. this.onBeforeAnimationsObservable.clear();
  26946. this.onAfterAnimationsObservable.clear();
  26947. this.onDataLoadedObservable.clear();
  26948. this.detachControl();
  26949. // Release sounds & sounds tracks
  26950. if (BABYLON.AudioEngine) {
  26951. this.disposeSounds();
  26952. }
  26953. // VR Helper
  26954. if (this.VRHelper) {
  26955. this.VRHelper.dispose();
  26956. }
  26957. // Detach cameras
  26958. var canvas = this._engine.getRenderingCanvas();
  26959. if (canvas) {
  26960. var index;
  26961. for (index = 0; index < this.cameras.length; index++) {
  26962. this.cameras[index].detachControl(canvas);
  26963. }
  26964. }
  26965. // Release animation groups
  26966. while (this.animationGroups.length) {
  26967. this.animationGroups[0].dispose();
  26968. }
  26969. // Release lights
  26970. while (this.lights.length) {
  26971. this.lights[0].dispose();
  26972. }
  26973. // Release meshes
  26974. while (this.meshes.length) {
  26975. this.meshes[0].dispose(true);
  26976. }
  26977. while (this.transformNodes.length) {
  26978. this.removeTransformNode(this.transformNodes[0]);
  26979. }
  26980. // Release cameras
  26981. while (this.cameras.length) {
  26982. this.cameras[0].dispose();
  26983. }
  26984. // Release materials
  26985. if (this.defaultMaterial) {
  26986. this.defaultMaterial.dispose();
  26987. }
  26988. while (this.multiMaterials.length) {
  26989. this.multiMaterials[0].dispose();
  26990. }
  26991. while (this.materials.length) {
  26992. this.materials[0].dispose();
  26993. }
  26994. // Release particles
  26995. while (this.particleSystems.length) {
  26996. this.particleSystems[0].dispose();
  26997. }
  26998. // Release sprites
  26999. while (this.spriteManagers.length) {
  27000. this.spriteManagers[0].dispose();
  27001. }
  27002. // Release postProcesses
  27003. while (this.postProcesses.length) {
  27004. this.postProcesses[0].dispose();
  27005. }
  27006. // Release layers
  27007. while (this.layers.length) {
  27008. this.layers[0].dispose();
  27009. }
  27010. while (this.effectLayers.length) {
  27011. this.effectLayers[0].dispose();
  27012. }
  27013. // Release textures
  27014. while (this.textures.length) {
  27015. this.textures[0].dispose();
  27016. }
  27017. // Release UBO
  27018. this._sceneUbo.dispose();
  27019. if (this._alternateSceneUbo) {
  27020. this._alternateSceneUbo.dispose();
  27021. }
  27022. // Post-processes
  27023. this.postProcessManager.dispose();
  27024. if (this._postProcessRenderPipelineManager) {
  27025. this._postProcessRenderPipelineManager.dispose();
  27026. }
  27027. // Physics
  27028. if (this._physicsEngine) {
  27029. this.disablePhysicsEngine();
  27030. }
  27031. // Remove from engine
  27032. index = this._engine.scenes.indexOf(this);
  27033. if (index > -1) {
  27034. this._engine.scenes.splice(index, 1);
  27035. }
  27036. this._engine.wipeCaches(true);
  27037. this._isDisposed = true;
  27038. };
  27039. Object.defineProperty(Scene.prototype, "isDisposed", {
  27040. /**
  27041. * Gets if the scene is already disposed
  27042. */
  27043. get: function () {
  27044. return this._isDisposed;
  27045. },
  27046. enumerable: true,
  27047. configurable: true
  27048. });
  27049. /**
  27050. * Releases sounds & soundtracks
  27051. */
  27052. Scene.prototype.disposeSounds = function () {
  27053. if (!this._mainSoundTrack) {
  27054. return;
  27055. }
  27056. this.mainSoundTrack.dispose();
  27057. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27058. this.soundTracks[scIndex].dispose();
  27059. }
  27060. };
  27061. // Octrees
  27062. /**
  27063. * Get the world extend vectors with an optional filter
  27064. *
  27065. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27066. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27067. */
  27068. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27069. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27070. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27071. filterPredicate = filterPredicate || (function () { return true; });
  27072. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27073. mesh.computeWorldMatrix(true);
  27074. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27075. return;
  27076. }
  27077. var boundingInfo = mesh.getBoundingInfo();
  27078. var minBox = boundingInfo.boundingBox.minimumWorld;
  27079. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27080. BABYLON.Tools.CheckExtends(minBox, min, max);
  27081. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27082. });
  27083. return {
  27084. min: min,
  27085. max: max
  27086. };
  27087. };
  27088. /**
  27089. * Creates or updates the octree used to boost selection (picking)
  27090. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27091. * @param maxCapacity defines the maximum capacity per leaf
  27092. * @param maxDepth defines the maximum depth of the octree
  27093. * @returns an octree of AbstractMesh
  27094. */
  27095. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27096. if (maxCapacity === void 0) { maxCapacity = 64; }
  27097. if (maxDepth === void 0) { maxDepth = 2; }
  27098. if (!this._selectionOctree) {
  27099. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27100. }
  27101. var worldExtends = this.getWorldExtends();
  27102. // Update octree
  27103. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27104. return this._selectionOctree;
  27105. };
  27106. // Picking
  27107. /**
  27108. * Creates a ray that can be used to pick in the scene
  27109. * @param x defines the x coordinate of the origin (on-screen)
  27110. * @param y defines the y coordinate of the origin (on-screen)
  27111. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27112. * @param camera defines the camera to use for the picking
  27113. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27114. * @returns a Ray
  27115. */
  27116. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27117. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27118. var result = BABYLON.Ray.Zero();
  27119. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27120. return result;
  27121. };
  27122. /**
  27123. * Creates a ray that can be used to pick in the scene
  27124. * @param x defines the x coordinate of the origin (on-screen)
  27125. * @param y defines the y coordinate of the origin (on-screen)
  27126. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27127. * @param result defines the ray where to store the picking ray
  27128. * @param camera defines the camera to use for the picking
  27129. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27130. * @returns the current scene
  27131. */
  27132. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27133. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27134. var engine = this._engine;
  27135. if (!camera) {
  27136. if (!this.activeCamera)
  27137. throw new Error("Active camera not set");
  27138. camera = this.activeCamera;
  27139. }
  27140. var cameraViewport = camera.viewport;
  27141. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27142. // Moving coordinates to local viewport world
  27143. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27144. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27145. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27146. return this;
  27147. };
  27148. /**
  27149. * Creates a ray that can be used to pick in the scene
  27150. * @param x defines the x coordinate of the origin (on-screen)
  27151. * @param y defines the y coordinate of the origin (on-screen)
  27152. * @param camera defines the camera to use for the picking
  27153. * @returns a Ray
  27154. */
  27155. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27156. var result = BABYLON.Ray.Zero();
  27157. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27158. return result;
  27159. };
  27160. /**
  27161. * Creates a ray that can be used to pick in the scene
  27162. * @param x defines the x coordinate of the origin (on-screen)
  27163. * @param y defines the y coordinate of the origin (on-screen)
  27164. * @param result defines the ray where to store the picking ray
  27165. * @param camera defines the camera to use for the picking
  27166. * @returns the current scene
  27167. */
  27168. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27169. if (!BABYLON.PickingInfo) {
  27170. return this;
  27171. }
  27172. var engine = this._engine;
  27173. if (!camera) {
  27174. if (!this.activeCamera)
  27175. throw new Error("Active camera not set");
  27176. camera = this.activeCamera;
  27177. }
  27178. var cameraViewport = camera.viewport;
  27179. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27180. var identity = BABYLON.Matrix.Identity();
  27181. // Moving coordinates to local viewport world
  27182. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27183. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27184. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27185. return this;
  27186. };
  27187. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27188. if (!BABYLON.PickingInfo) {
  27189. return null;
  27190. }
  27191. var pickingInfo = null;
  27192. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27193. var mesh = this.meshes[meshIndex];
  27194. if (predicate) {
  27195. if (!predicate(mesh)) {
  27196. continue;
  27197. }
  27198. }
  27199. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27200. continue;
  27201. }
  27202. var world = mesh.getWorldMatrix();
  27203. var ray = rayFunction(world);
  27204. var result = mesh.intersects(ray, fastCheck);
  27205. if (!result || !result.hit)
  27206. continue;
  27207. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27208. continue;
  27209. pickingInfo = result;
  27210. if (fastCheck) {
  27211. break;
  27212. }
  27213. }
  27214. return pickingInfo || new BABYLON.PickingInfo();
  27215. };
  27216. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27217. if (!BABYLON.PickingInfo) {
  27218. return null;
  27219. }
  27220. var pickingInfos = new Array();
  27221. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27222. var mesh = this.meshes[meshIndex];
  27223. if (predicate) {
  27224. if (!predicate(mesh)) {
  27225. continue;
  27226. }
  27227. }
  27228. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27229. continue;
  27230. }
  27231. var world = mesh.getWorldMatrix();
  27232. var ray = rayFunction(world);
  27233. var result = mesh.intersects(ray, false);
  27234. if (!result || !result.hit)
  27235. continue;
  27236. pickingInfos.push(result);
  27237. }
  27238. return pickingInfos;
  27239. };
  27240. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27241. if (!BABYLON.PickingInfo) {
  27242. return null;
  27243. }
  27244. var pickingInfo = null;
  27245. if (!camera) {
  27246. if (!this.activeCamera) {
  27247. return null;
  27248. }
  27249. camera = this.activeCamera;
  27250. }
  27251. if (this.spriteManagers.length > 0) {
  27252. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27253. var spriteManager = this.spriteManagers[spriteIndex];
  27254. if (!spriteManager.isPickable) {
  27255. continue;
  27256. }
  27257. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27258. if (!result || !result.hit)
  27259. continue;
  27260. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27261. continue;
  27262. pickingInfo = result;
  27263. if (fastCheck) {
  27264. break;
  27265. }
  27266. }
  27267. }
  27268. return pickingInfo || new BABYLON.PickingInfo();
  27269. };
  27270. /** Launch a ray to try to pick a mesh in the scene
  27271. * @param x position on screen
  27272. * @param y position on screen
  27273. * @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
  27274. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27275. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27276. * @returns a PickingInfo
  27277. */
  27278. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27279. var _this = this;
  27280. if (!BABYLON.PickingInfo) {
  27281. return null;
  27282. }
  27283. return this._internalPick(function (world) {
  27284. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27285. return _this._tempPickingRay;
  27286. }, predicate, fastCheck);
  27287. };
  27288. /** Launch a ray to try to pick a sprite in the scene
  27289. * @param x position on screen
  27290. * @param y position on screen
  27291. * @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
  27292. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27293. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27294. * @returns a PickingInfo
  27295. */
  27296. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27297. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27298. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27299. };
  27300. /** Use the given ray to pick a mesh in the scene
  27301. * @param ray The ray to use to pick meshes
  27302. * @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
  27303. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27304. * @returns a PickingInfo
  27305. */
  27306. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27307. var _this = this;
  27308. return this._internalPick(function (world) {
  27309. if (!_this._pickWithRayInverseMatrix) {
  27310. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27311. }
  27312. world.invertToRef(_this._pickWithRayInverseMatrix);
  27313. if (!_this._cachedRayForTransform) {
  27314. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27315. }
  27316. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27317. return _this._cachedRayForTransform;
  27318. }, predicate, fastCheck);
  27319. };
  27320. /**
  27321. * Launch a ray to try to pick a mesh in the scene
  27322. * @param x X position on screen
  27323. * @param y Y position on screen
  27324. * @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
  27325. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27326. * @returns an array of PickingInfo
  27327. */
  27328. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27329. var _this = this;
  27330. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27331. };
  27332. /**
  27333. * Launch a ray to try to pick a mesh in the scene
  27334. * @param ray Ray to use
  27335. * @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
  27336. * @returns an array of PickingInfo
  27337. */
  27338. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27339. var _this = this;
  27340. return this._internalMultiPick(function (world) {
  27341. if (!_this._pickWithRayInverseMatrix) {
  27342. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27343. }
  27344. world.invertToRef(_this._pickWithRayInverseMatrix);
  27345. if (!_this._cachedRayForTransform) {
  27346. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27347. }
  27348. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27349. return _this._cachedRayForTransform;
  27350. }, predicate);
  27351. };
  27352. /**
  27353. * Force the value of meshUnderPointer
  27354. * @param mesh defines the mesh to use
  27355. */
  27356. Scene.prototype.setPointerOverMesh = function (mesh) {
  27357. if (this._pointerOverMesh === mesh) {
  27358. return;
  27359. }
  27360. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27361. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27362. }
  27363. this._pointerOverMesh = mesh;
  27364. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27365. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27366. }
  27367. };
  27368. /**
  27369. * Gets the mesh under the pointer
  27370. * @returns a Mesh or null if no mesh is under the pointer
  27371. */
  27372. Scene.prototype.getPointerOverMesh = function () {
  27373. return this._pointerOverMesh;
  27374. };
  27375. /**
  27376. * Force the sprite under the pointer
  27377. * @param sprite defines the sprite to use
  27378. */
  27379. Scene.prototype.setPointerOverSprite = function (sprite) {
  27380. if (this._pointerOverSprite === sprite) {
  27381. return;
  27382. }
  27383. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27384. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27385. }
  27386. this._pointerOverSprite = sprite;
  27387. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27388. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27389. }
  27390. };
  27391. /**
  27392. * Gets the sprite under the pointer
  27393. * @returns a Sprite or null if no sprite is under the pointer
  27394. */
  27395. Scene.prototype.getPointerOverSprite = function () {
  27396. return this._pointerOverSprite;
  27397. };
  27398. // Physics
  27399. /**
  27400. * Gets the current physics engine
  27401. * @returns a PhysicsEngine or null if none attached
  27402. */
  27403. Scene.prototype.getPhysicsEngine = function () {
  27404. return this._physicsEngine;
  27405. };
  27406. /**
  27407. * Enables physics to the current scene
  27408. * @param gravity defines the scene's gravity for the physics engine
  27409. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  27410. * @return a boolean indicating if the physics engine was initialized
  27411. */
  27412. Scene.prototype.enablePhysics = function (gravity, plugin) {
  27413. if (gravity === void 0) { gravity = null; }
  27414. if (this._physicsEngine) {
  27415. return true;
  27416. }
  27417. try {
  27418. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  27419. return true;
  27420. }
  27421. catch (e) {
  27422. BABYLON.Tools.Error(e.message);
  27423. return false;
  27424. }
  27425. };
  27426. /**
  27427. * Disables and disposes the physics engine associated with the scene
  27428. */
  27429. Scene.prototype.disablePhysicsEngine = function () {
  27430. if (!this._physicsEngine) {
  27431. return;
  27432. }
  27433. this._physicsEngine.dispose();
  27434. this._physicsEngine = null;
  27435. };
  27436. /**
  27437. * Gets a boolean indicating if there is an active physics engine
  27438. * @returns a boolean indicating if there is an active physics engine
  27439. */
  27440. Scene.prototype.isPhysicsEnabled = function () {
  27441. return this._physicsEngine !== undefined;
  27442. };
  27443. /**
  27444. * Deletes a physics compound impostor
  27445. * @param compound defines the compound to delete
  27446. */
  27447. Scene.prototype.deleteCompoundImpostor = function (compound) {
  27448. var mesh = compound.parts[0].mesh;
  27449. if (mesh.physicsImpostor) {
  27450. mesh.physicsImpostor.dispose();
  27451. mesh.physicsImpostor = null;
  27452. }
  27453. };
  27454. // Misc.
  27455. /** @ignore */
  27456. Scene.prototype._rebuildGeometries = function () {
  27457. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  27458. var geometry = _a[_i];
  27459. geometry._rebuild();
  27460. }
  27461. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  27462. var mesh = _c[_b];
  27463. mesh._rebuild();
  27464. }
  27465. if (this.postProcessManager) {
  27466. this.postProcessManager._rebuild();
  27467. }
  27468. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  27469. var layer = _e[_d];
  27470. layer._rebuild();
  27471. }
  27472. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  27473. var effectLayer = _g[_f];
  27474. effectLayer._rebuild();
  27475. }
  27476. if (this._boundingBoxRenderer) {
  27477. this._boundingBoxRenderer._rebuild();
  27478. }
  27479. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  27480. var system = _j[_h];
  27481. system.rebuild();
  27482. }
  27483. if (this._postProcessRenderPipelineManager) {
  27484. this._postProcessRenderPipelineManager._rebuild();
  27485. }
  27486. };
  27487. /** @ignore */
  27488. Scene.prototype._rebuildTextures = function () {
  27489. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27490. var texture = _a[_i];
  27491. texture._rebuild();
  27492. }
  27493. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27494. };
  27495. /**
  27496. * Creates a default light for the scene.
  27497. * @param replace Whether to replace the existing lights in the scene.
  27498. */
  27499. Scene.prototype.createDefaultLight = function (replace) {
  27500. if (replace === void 0) { replace = false; }
  27501. // Dispose existing light in replace mode.
  27502. if (replace) {
  27503. if (this.lights) {
  27504. for (var i = 0; i < this.lights.length; i++) {
  27505. this.lights[i].dispose();
  27506. }
  27507. }
  27508. }
  27509. // Light
  27510. if (this.lights.length === 0) {
  27511. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  27512. }
  27513. };
  27514. /**
  27515. * Creates a default camera for the scene.
  27516. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  27517. * @param replace Whether to replace the existing active camera in the scene.
  27518. * @param attachCameraControls Whether to attach camera controls to the canvas.
  27519. */
  27520. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  27521. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27522. if (replace === void 0) { replace = false; }
  27523. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27524. // Dispose existing camera in replace mode.
  27525. if (replace) {
  27526. if (this.activeCamera) {
  27527. this.activeCamera.dispose();
  27528. this.activeCamera = null;
  27529. }
  27530. }
  27531. // Camera
  27532. if (!this.activeCamera) {
  27533. var worldExtends = this.getWorldExtends();
  27534. var worldSize = worldExtends.max.subtract(worldExtends.min);
  27535. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  27536. var camera;
  27537. var radius = worldSize.length() * 1.5;
  27538. // empty scene scenario!
  27539. if (!isFinite(radius)) {
  27540. radius = 1;
  27541. worldCenter.copyFromFloats(0, 0, 0);
  27542. }
  27543. if (createArcRotateCamera) {
  27544. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  27545. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  27546. arcRotateCamera.wheelPrecision = 100 / radius;
  27547. camera = arcRotateCamera;
  27548. }
  27549. else {
  27550. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  27551. freeCamera.setTarget(worldCenter);
  27552. camera = freeCamera;
  27553. }
  27554. camera.minZ = radius * 0.01;
  27555. camera.maxZ = radius * 1000;
  27556. camera.speed = radius * 0.2;
  27557. this.activeCamera = camera;
  27558. var canvas = this.getEngine().getRenderingCanvas();
  27559. if (attachCameraControls && canvas) {
  27560. camera.attachControl(canvas);
  27561. }
  27562. }
  27563. };
  27564. /**
  27565. * Creates a default camera and a default light
  27566. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  27567. * @param replace defines if the camera and/or light will replace the existing ones
  27568. * @param attachCameraControls defines if attachControl will be called on the new camera
  27569. */
  27570. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  27571. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27572. if (replace === void 0) { replace = false; }
  27573. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27574. this.createDefaultLight(replace);
  27575. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  27576. };
  27577. /**
  27578. * Creates a new sky box
  27579. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27580. * @param environmentTexture defines the texture to use as environment texture
  27581. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  27582. * @param scale defines the overall scale of the skybox
  27583. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  27584. * @returns a new mesh holding the sky box
  27585. */
  27586. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  27587. if (pbr === void 0) { pbr = false; }
  27588. if (scale === void 0) { scale = 1000; }
  27589. if (blur === void 0) { blur = 0; }
  27590. if (environmentTexture) {
  27591. this.environmentTexture = environmentTexture;
  27592. }
  27593. if (!this.environmentTexture) {
  27594. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  27595. return null;
  27596. }
  27597. // Skybox
  27598. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  27599. if (pbr) {
  27600. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  27601. hdrSkyboxMaterial.backFaceCulling = false;
  27602. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27603. if (hdrSkyboxMaterial.reflectionTexture) {
  27604. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27605. }
  27606. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  27607. hdrSkyboxMaterial.disableLighting = true;
  27608. hdrSkyboxMaterial.twoSidedLighting = true;
  27609. hdrSkybox.infiniteDistance = true;
  27610. hdrSkybox.material = hdrSkyboxMaterial;
  27611. }
  27612. else {
  27613. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  27614. skyboxMaterial.backFaceCulling = false;
  27615. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27616. if (skyboxMaterial.reflectionTexture) {
  27617. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27618. }
  27619. skyboxMaterial.disableLighting = true;
  27620. hdrSkybox.infiniteDistance = true;
  27621. hdrSkybox.material = skyboxMaterial;
  27622. }
  27623. return hdrSkybox;
  27624. };
  27625. /**
  27626. * Creates a new environment
  27627. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27628. * @param options defines the options you can use to configure the environment
  27629. * @returns the new EnvironmentHelper
  27630. */
  27631. Scene.prototype.createDefaultEnvironment = function (options) {
  27632. if (BABYLON.EnvironmentHelper) {
  27633. return new BABYLON.EnvironmentHelper(options, this);
  27634. }
  27635. return null;
  27636. };
  27637. /**
  27638. * Creates a new VREXperienceHelper
  27639. * @see http://doc.babylonjs.com/how_to/webvr_helper
  27640. * @param webVROptions defines the options used to create the new VREXperienceHelper
  27641. * @returns a new VREXperienceHelper
  27642. */
  27643. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  27644. if (webVROptions === void 0) { webVROptions = {}; }
  27645. return new BABYLON.VRExperienceHelper(this, webVROptions);
  27646. };
  27647. // Tags
  27648. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  27649. if (tagsQuery === undefined) {
  27650. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  27651. return list;
  27652. }
  27653. var listByTags = [];
  27654. forEach = forEach || (function (item) { return; });
  27655. for (var i in list) {
  27656. var item = list[i];
  27657. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  27658. listByTags.push(item);
  27659. forEach(item);
  27660. }
  27661. }
  27662. return listByTags;
  27663. };
  27664. /**
  27665. * Get a list of meshes by tags
  27666. * @param tagsQuery defines the tags query to use
  27667. * @param forEach defines a predicate used to filter results
  27668. * @returns an array of Mesh
  27669. */
  27670. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  27671. return this._getByTags(this.meshes, tagsQuery, forEach);
  27672. };
  27673. /**
  27674. * Get a list of cameras by tags
  27675. * @param tagsQuery defines the tags query to use
  27676. * @param forEach defines a predicate used to filter results
  27677. * @returns an array of Camera
  27678. */
  27679. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  27680. return this._getByTags(this.cameras, tagsQuery, forEach);
  27681. };
  27682. /**
  27683. * Get a list of lights by tags
  27684. * @param tagsQuery defines the tags query to use
  27685. * @param forEach defines a predicate used to filter results
  27686. * @returns an array of Light
  27687. */
  27688. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  27689. return this._getByTags(this.lights, tagsQuery, forEach);
  27690. };
  27691. /**
  27692. * Get a list of materials by tags
  27693. * @param tagsQuery defines the tags query to use
  27694. * @param forEach defines a predicate used to filter results
  27695. * @returns an array of Material
  27696. */
  27697. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  27698. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  27699. };
  27700. /**
  27701. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27702. * This allowed control for front to back rendering or reversly depending of the special needs.
  27703. *
  27704. * @param renderingGroupId The rendering group id corresponding to its index
  27705. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27706. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27707. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27708. */
  27709. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27710. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27711. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27712. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27713. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27714. };
  27715. /**
  27716. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27717. *
  27718. * @param renderingGroupId The rendering group id corresponding to its index
  27719. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27720. * @param depth Automatically clears depth between groups if true and autoClear is true.
  27721. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  27722. */
  27723. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  27724. if (depth === void 0) { depth = true; }
  27725. if (stencil === void 0) { stencil = true; }
  27726. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  27727. };
  27728. /**
  27729. * Will flag all materials as dirty to trigger new shader compilation
  27730. * @param flag defines the flag used to specify which material part must be marked as dirty
  27731. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  27732. */
  27733. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  27734. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  27735. var material = _a[_i];
  27736. if (predicate && !predicate(material)) {
  27737. continue;
  27738. }
  27739. material.markAsDirty(flag);
  27740. }
  27741. };
  27742. /** @ignore */
  27743. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  27744. var _this = this;
  27745. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  27746. this._activeRequests.push(request);
  27747. request.onCompleteObservable.add(function (request) {
  27748. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  27749. });
  27750. return request;
  27751. };
  27752. /** @ignore */
  27753. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  27754. var _this = this;
  27755. return new Promise(function (resolve, reject) {
  27756. _this._loadFile(url, function (data) {
  27757. resolve(data);
  27758. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  27759. reject(exception);
  27760. });
  27761. });
  27762. };
  27763. // Statics
  27764. Scene._FOGMODE_NONE = 0;
  27765. Scene._FOGMODE_EXP = 1;
  27766. Scene._FOGMODE_EXP2 = 2;
  27767. Scene._FOGMODE_LINEAR = 3;
  27768. Scene._uniqueIdCounter = 0;
  27769. /**
  27770. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  27771. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  27772. */
  27773. Scene.MinDeltaTime = 1.0;
  27774. /**
  27775. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  27776. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  27777. */
  27778. Scene.MaxDeltaTime = 1000.0;
  27779. /** The distance in pixel that you have to move to prevent some events */
  27780. Scene.DragMovementThreshold = 10; // in pixels
  27781. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  27782. Scene.LongPressDelay = 500; // in milliseconds
  27783. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  27784. Scene.DoubleClickDelay = 300; // in milliseconds
  27785. /** If you need to check double click without raising a single click at first click, enable this flag */
  27786. Scene.ExclusiveDoubleClickMode = false;
  27787. return Scene;
  27788. }());
  27789. BABYLON.Scene = Scene;
  27790. })(BABYLON || (BABYLON = {}));
  27791. //# sourceMappingURL=babylon.scene.js.map
  27792. "use strict";
  27793. var BABYLON;
  27794. (function (BABYLON) {
  27795. /**
  27796. * Set of assets to keep when moving a scene into an asset container.
  27797. */
  27798. var KeepAssets = /** @class */ (function () {
  27799. function KeepAssets() {
  27800. /**
  27801. * Cameras to keep.
  27802. */
  27803. this.cameras = new Array();
  27804. /**
  27805. * Lights to keep.
  27806. */
  27807. this.lights = new Array();
  27808. /**
  27809. * Meshes to keep.
  27810. */
  27811. this.meshes = new Array();
  27812. /**
  27813. * Skeletons to keep.
  27814. */
  27815. this.skeletons = new Array();
  27816. /**
  27817. * ParticleSystems to keep.
  27818. */
  27819. this.particleSystems = new Array();
  27820. /**
  27821. * Animations to keep.
  27822. */
  27823. this.animations = new Array();
  27824. /**
  27825. * AnimationGroups to keep.
  27826. */
  27827. this.animationGroups = new Array();
  27828. /**
  27829. * MultiMaterials to keep.
  27830. */
  27831. this.multiMaterials = new Array();
  27832. /**
  27833. * Materials to keep.
  27834. */
  27835. this.materials = new Array();
  27836. /**
  27837. * MorphTargetManagers to keep.
  27838. */
  27839. this.morphTargetManagers = new Array();
  27840. /**
  27841. * Geometries to keep.
  27842. */
  27843. this.geometries = new Array();
  27844. /**
  27845. * TransformNodes to keep.
  27846. */
  27847. this.transformNodes = new Array();
  27848. /**
  27849. * LensFlareSystems to keep.
  27850. */
  27851. this.lensFlareSystems = new Array();
  27852. /**
  27853. * ShadowGenerators to keep.
  27854. */
  27855. this.shadowGenerators = new Array();
  27856. /**
  27857. * ActionManagers to keep.
  27858. */
  27859. this.actionManagers = new Array();
  27860. /**
  27861. * Sounds to keep.
  27862. */
  27863. this.sounds = new Array();
  27864. /**
  27865. * Textures to keep.
  27866. */
  27867. this.textures = new Array();
  27868. }
  27869. return KeepAssets;
  27870. }());
  27871. BABYLON.KeepAssets = KeepAssets;
  27872. /**
  27873. * Container with a set of assets that can be added or removed from a scene.
  27874. */
  27875. var AssetContainer = /** @class */ (function () {
  27876. /**
  27877. * Instantiates an AssetContainer.
  27878. * @param scene The scene the AssetContainer belongs to.
  27879. */
  27880. function AssetContainer(scene) {
  27881. // Objects
  27882. /**
  27883. * Cameras populated in the container.
  27884. */
  27885. this.cameras = new Array();
  27886. /**
  27887. * Lights populated in the container.
  27888. */
  27889. this.lights = new Array();
  27890. /**
  27891. * Meshes populated in the container.
  27892. */
  27893. this.meshes = new Array();
  27894. /**
  27895. * Skeletons populated in the container.
  27896. */
  27897. this.skeletons = new Array();
  27898. /**
  27899. * ParticleSystems populated in the container.
  27900. */
  27901. this.particleSystems = new Array();
  27902. /**
  27903. * Animations populated in the container.
  27904. */
  27905. this.animations = new Array();
  27906. /**
  27907. * AnimationGroups populated in the container.
  27908. */
  27909. this.animationGroups = new Array();
  27910. /**
  27911. * MultiMaterials populated in the container.
  27912. */
  27913. this.multiMaterials = new Array();
  27914. /**
  27915. * Materials populated in the container.
  27916. */
  27917. this.materials = new Array();
  27918. /**
  27919. * MorphTargetManagers populated in the container.
  27920. */
  27921. this.morphTargetManagers = new Array();
  27922. /**
  27923. * Geometries populated in the container.
  27924. */
  27925. this.geometries = new Array();
  27926. /**
  27927. * TransformNodes populated in the container.
  27928. */
  27929. this.transformNodes = new Array();
  27930. /**
  27931. * LensFlareSystems populated in the container.
  27932. */
  27933. this.lensFlareSystems = new Array();
  27934. /**
  27935. * ShadowGenerators populated in the container.
  27936. */
  27937. this.shadowGenerators = new Array();
  27938. /**
  27939. * ActionManagers populated in the container.
  27940. */
  27941. this.actionManagers = new Array();
  27942. /**
  27943. * Sounds populated in the container.
  27944. */
  27945. this.sounds = new Array();
  27946. /**
  27947. * Textures populated in the container.
  27948. */
  27949. this.textures = new Array();
  27950. this.scene = scene;
  27951. }
  27952. /**
  27953. * Adds all the assets from the container to the scene.
  27954. */
  27955. AssetContainer.prototype.addAllToScene = function () {
  27956. var _this = this;
  27957. this.cameras.forEach(function (o) {
  27958. _this.scene.addCamera(o);
  27959. });
  27960. this.lights.forEach(function (o) {
  27961. _this.scene.addLight(o);
  27962. });
  27963. this.meshes.forEach(function (o) {
  27964. _this.scene.addMesh(o);
  27965. });
  27966. this.skeletons.forEach(function (o) {
  27967. _this.scene.addSkeleton(o);
  27968. });
  27969. this.particleSystems.forEach(function (o) {
  27970. _this.scene.addParticleSystem(o);
  27971. });
  27972. this.animations.forEach(function (o) {
  27973. _this.scene.addAnimation(o);
  27974. });
  27975. this.animationGroups.forEach(function (o) {
  27976. _this.scene.addAnimationGroup(o);
  27977. });
  27978. this.multiMaterials.forEach(function (o) {
  27979. _this.scene.addMultiMaterial(o);
  27980. });
  27981. this.materials.forEach(function (o) {
  27982. _this.scene.addMaterial(o);
  27983. });
  27984. this.morphTargetManagers.forEach(function (o) {
  27985. _this.scene.addMorphTargetManager(o);
  27986. });
  27987. this.geometries.forEach(function (o) {
  27988. _this.scene.addGeometry(o);
  27989. });
  27990. this.transformNodes.forEach(function (o) {
  27991. _this.scene.addTransformNode(o);
  27992. });
  27993. this.lensFlareSystems.forEach(function (o) {
  27994. _this.scene.addLensFlareSystem(o);
  27995. });
  27996. this.actionManagers.forEach(function (o) {
  27997. _this.scene.addActionManager(o);
  27998. });
  27999. this.sounds.forEach(function (o) {
  28000. o.play();
  28001. o.autoplay = true;
  28002. _this.scene.mainSoundTrack.AddSound(o);
  28003. });
  28004. this.textures.forEach(function (o) {
  28005. _this.scene.addTexture;
  28006. });
  28007. };
  28008. /**
  28009. * Removes all the assets in the container from the scene
  28010. */
  28011. AssetContainer.prototype.removeAllFromScene = function () {
  28012. var _this = this;
  28013. this.cameras.forEach(function (o) {
  28014. _this.scene.removeCamera(o);
  28015. });
  28016. this.lights.forEach(function (o) {
  28017. _this.scene.removeLight(o);
  28018. });
  28019. this.meshes.forEach(function (o) {
  28020. _this.scene.removeMesh(o);
  28021. });
  28022. this.skeletons.forEach(function (o) {
  28023. _this.scene.removeSkeleton(o);
  28024. });
  28025. this.particleSystems.forEach(function (o) {
  28026. _this.scene.removeParticleSystem(o);
  28027. });
  28028. this.animations.forEach(function (o) {
  28029. _this.scene.removeAnimation(o);
  28030. });
  28031. this.animationGroups.forEach(function (o) {
  28032. _this.scene.removeAnimationGroup(o);
  28033. });
  28034. this.multiMaterials.forEach(function (o) {
  28035. _this.scene.removeMultiMaterial(o);
  28036. });
  28037. this.materials.forEach(function (o) {
  28038. _this.scene.removeMaterial(o);
  28039. });
  28040. this.morphTargetManagers.forEach(function (o) {
  28041. _this.scene.removeMorphTargetManager(o);
  28042. });
  28043. this.geometries.forEach(function (o) {
  28044. _this.scene.removeGeometry(o);
  28045. });
  28046. this.transformNodes.forEach(function (o) {
  28047. _this.scene.removeTransformNode(o);
  28048. });
  28049. this.lensFlareSystems.forEach(function (o) {
  28050. _this.scene.removeLensFlareSystem(o);
  28051. });
  28052. this.actionManagers.forEach(function (o) {
  28053. _this.scene.removeActionManager(o);
  28054. });
  28055. this.sounds.forEach(function (o) {
  28056. o.stop();
  28057. o.autoplay = false;
  28058. _this.scene.mainSoundTrack.RemoveSound(o);
  28059. });
  28060. this.textures.forEach(function (o) {
  28061. _this.scene.removeTexture(o);
  28062. });
  28063. };
  28064. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28065. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28066. var asset = sourceAssets_1[_i];
  28067. var move = true;
  28068. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28069. var keepAsset = keepAssets_1[_a];
  28070. if (asset === keepAsset) {
  28071. move = false;
  28072. break;
  28073. }
  28074. }
  28075. if (move) {
  28076. targetAssets.push(asset);
  28077. }
  28078. }
  28079. };
  28080. /**
  28081. * Removes all the assets contained in the scene and adds them to the container.
  28082. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28083. */
  28084. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28085. if (keepAssets === undefined) {
  28086. keepAssets = new KeepAssets();
  28087. }
  28088. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28089. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28090. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28091. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28092. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28093. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28094. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28095. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28096. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28097. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28098. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28099. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28100. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28101. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28102. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28103. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28104. this.removeAllFromScene();
  28105. };
  28106. return AssetContainer;
  28107. }());
  28108. BABYLON.AssetContainer = AssetContainer;
  28109. })(BABYLON || (BABYLON = {}));
  28110. //# sourceMappingURL=babylon.assetContainer.js.map
  28111. "use strict";
  28112. var BABYLON;
  28113. (function (BABYLON) {
  28114. var Buffer = /** @class */ (function () {
  28115. /**
  28116. * Constructor
  28117. * @param engine the engine
  28118. * @param data the data to use for this buffer
  28119. * @param updatable whether the data is updatable
  28120. * @param stride the stride (optional)
  28121. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28122. * @param instanced whether the buffer is instanced (optional)
  28123. * @param useBytes set to true if the stride in in bytes (optional)
  28124. */
  28125. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28126. if (stride === void 0) { stride = 0; }
  28127. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28128. if (instanced === void 0) { instanced = false; }
  28129. if (useBytes === void 0) { useBytes = false; }
  28130. if (engine instanceof BABYLON.Mesh) {
  28131. this._engine = engine.getScene().getEngine();
  28132. }
  28133. else {
  28134. this._engine = engine;
  28135. }
  28136. this._updatable = updatable;
  28137. this._instanced = instanced;
  28138. this._data = data;
  28139. this.byteStride = useBytes ? stride : stride * 4;
  28140. if (!postponeInternalCreation) {
  28141. this.create();
  28142. }
  28143. }
  28144. /**
  28145. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28146. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28147. * @param offset defines offset in the buffer (0 by default)
  28148. * @param size defines the size in floats of attributes (position is 3 for instance)
  28149. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28150. * @param instanced defines if the vertex buffer contains indexed data
  28151. * @param useBytes defines if the offset and stride are in bytes
  28152. * @returns the new vertex buffer
  28153. */
  28154. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28155. if (useBytes === void 0) { useBytes = false; }
  28156. var byteOffset = useBytes ? offset : offset * 4;
  28157. var byteStride = stride ? (useBytes ? stride : stride * 4) : this.byteStride;
  28158. // a lot of these parameters are ignored as they are overriden by the buffer
  28159. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28160. };
  28161. // Properties
  28162. Buffer.prototype.isUpdatable = function () {
  28163. return this._updatable;
  28164. };
  28165. Buffer.prototype.getData = function () {
  28166. return this._data;
  28167. };
  28168. Buffer.prototype.getBuffer = function () {
  28169. return this._buffer;
  28170. };
  28171. /**
  28172. * Gets the stride in float32 units (i.e. byte stride / 4).
  28173. * May not be an integer if the byte stride is not divisible by 4.
  28174. * DEPRECATED. Use byteStride instead.
  28175. * @returns the stride in float32 units
  28176. */
  28177. Buffer.prototype.getStrideSize = function () {
  28178. return this.byteStride / 4;
  28179. };
  28180. // Methods
  28181. Buffer.prototype.create = function (data) {
  28182. if (data === void 0) { data = null; }
  28183. if (!data && this._buffer) {
  28184. return; // nothing to do
  28185. }
  28186. data = data || this._data;
  28187. if (!data) {
  28188. return;
  28189. }
  28190. if (!this._buffer) {
  28191. if (this._updatable) {
  28192. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28193. this._data = data;
  28194. }
  28195. else {
  28196. this._buffer = this._engine.createVertexBuffer(data);
  28197. }
  28198. }
  28199. else if (this._updatable) {
  28200. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28201. this._data = data;
  28202. }
  28203. };
  28204. Buffer.prototype._rebuild = function () {
  28205. this._buffer = null;
  28206. this.create(this._data);
  28207. };
  28208. Buffer.prototype.update = function (data) {
  28209. this.create(data);
  28210. };
  28211. /**
  28212. * Updates the data directly.
  28213. * @param data the new data
  28214. * @param offset the new offset
  28215. * @param vertexCount the vertex count (optional)
  28216. * @param useBytes set to true if the offset is in bytes
  28217. */
  28218. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28219. if (useBytes === void 0) { useBytes = false; }
  28220. if (!this._buffer) {
  28221. return;
  28222. }
  28223. if (this._updatable) {
  28224. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * 4, (vertexCount ? vertexCount * this.byteStride : undefined));
  28225. this._data = null;
  28226. }
  28227. };
  28228. Buffer.prototype.dispose = function () {
  28229. if (!this._buffer) {
  28230. return;
  28231. }
  28232. if (this._engine._releaseBuffer(this._buffer)) {
  28233. this._buffer = null;
  28234. }
  28235. };
  28236. return Buffer;
  28237. }());
  28238. BABYLON.Buffer = Buffer;
  28239. })(BABYLON || (BABYLON = {}));
  28240. //# sourceMappingURL=babylon.buffer.js.map
  28241. "use strict";
  28242. var BABYLON;
  28243. (function (BABYLON) {
  28244. var VertexBuffer = /** @class */ (function () {
  28245. /**
  28246. * Constructor
  28247. * @param engine the engine
  28248. * @param data the data to use for this vertex buffer
  28249. * @param kind the vertex buffer kind
  28250. * @param updatable whether the data is updatable
  28251. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28252. * @param stride the stride (optional)
  28253. * @param instanced whether the buffer is instanced (optional)
  28254. * @param offset the offset of the data (optional)
  28255. * @param size the number of components (optional)
  28256. * @param type the type of the component (optional)
  28257. * @param normalized whether the data contains normalized data (optional)
  28258. * @param useBytes set to true if stride and offset are in bytes (optional)
  28259. */
  28260. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28261. if (normalized === void 0) { normalized = false; }
  28262. if (useBytes === void 0) { useBytes = false; }
  28263. if (data instanceof BABYLON.Buffer) {
  28264. this._buffer = data;
  28265. this._ownsBuffer = false;
  28266. }
  28267. else {
  28268. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28269. this._ownsBuffer = true;
  28270. }
  28271. this._kind = kind;
  28272. if (type == undefined) {
  28273. var data_1 = this.getData();
  28274. this.type = VertexBuffer.FLOAT;
  28275. if (data_1 instanceof Int8Array)
  28276. this.type = VertexBuffer.BYTE;
  28277. else if (data_1 instanceof Uint8Array)
  28278. this.type = VertexBuffer.UNSIGNED_BYTE;
  28279. else if (data_1 instanceof Int16Array)
  28280. this.type = VertexBuffer.SHORT;
  28281. else if (data_1 instanceof Uint16Array)
  28282. this.type = VertexBuffer.UNSIGNED_SHORT;
  28283. else if (data_1 instanceof Int32Array)
  28284. this.type = VertexBuffer.INT;
  28285. else if (data_1 instanceof Uint32Array)
  28286. this.type = VertexBuffer.UNSIGNED_INT;
  28287. }
  28288. else {
  28289. this.type = type;
  28290. }
  28291. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28292. if (useBytes) {
  28293. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28294. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28295. this.byteOffset = offset || 0;
  28296. }
  28297. else {
  28298. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28299. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28300. this.byteOffset = (offset || 0) * typeByteLength;
  28301. }
  28302. this.normalized = normalized;
  28303. this._instanced = instanced !== undefined ? instanced : false;
  28304. this._instanceDivisor = instanced ? 1 : 0;
  28305. }
  28306. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28307. /**
  28308. * Gets or sets the instance divisor when in instanced mode
  28309. */
  28310. get: function () {
  28311. return this._instanceDivisor;
  28312. },
  28313. set: function (value) {
  28314. this._instanceDivisor = value;
  28315. if (value == 0) {
  28316. this._instanced = false;
  28317. }
  28318. else {
  28319. this._instanced = true;
  28320. }
  28321. },
  28322. enumerable: true,
  28323. configurable: true
  28324. });
  28325. VertexBuffer.prototype._rebuild = function () {
  28326. if (!this._buffer) {
  28327. return;
  28328. }
  28329. this._buffer._rebuild();
  28330. };
  28331. /**
  28332. * Returns the kind of the VertexBuffer (string).
  28333. */
  28334. VertexBuffer.prototype.getKind = function () {
  28335. return this._kind;
  28336. };
  28337. // Properties
  28338. /**
  28339. * Boolean : is the VertexBuffer updatable ?
  28340. */
  28341. VertexBuffer.prototype.isUpdatable = function () {
  28342. return this._buffer.isUpdatable();
  28343. };
  28344. /**
  28345. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28346. */
  28347. VertexBuffer.prototype.getData = function () {
  28348. return this._buffer.getData();
  28349. };
  28350. /**
  28351. * Returns the WebGLBuffer associated to the VertexBuffer.
  28352. */
  28353. VertexBuffer.prototype.getBuffer = function () {
  28354. return this._buffer.getBuffer();
  28355. };
  28356. /**
  28357. * Returns the stride as a multiple of the type byte length.
  28358. * DEPRECATED. Use byteStride instead.
  28359. */
  28360. VertexBuffer.prototype.getStrideSize = function () {
  28361. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28362. };
  28363. /**
  28364. * Returns the offset as a multiple of the type byte length.
  28365. * DEPRECATED. Use byteOffset instead.
  28366. */
  28367. VertexBuffer.prototype.getOffset = function () {
  28368. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28369. };
  28370. /**
  28371. * Returns the number of components per vertex attribute (integer).
  28372. */
  28373. VertexBuffer.prototype.getSize = function () {
  28374. return this._size;
  28375. };
  28376. /**
  28377. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28378. */
  28379. VertexBuffer.prototype.getIsInstanced = function () {
  28380. return this._instanced;
  28381. };
  28382. /**
  28383. * Returns the instancing divisor, zero for non-instanced (integer).
  28384. */
  28385. VertexBuffer.prototype.getInstanceDivisor = function () {
  28386. return this._instanceDivisor;
  28387. };
  28388. // Methods
  28389. /**
  28390. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28391. * Returns the created WebGLBuffer.
  28392. */
  28393. VertexBuffer.prototype.create = function (data) {
  28394. return this._buffer.create(data);
  28395. };
  28396. /**
  28397. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28398. * This function will create a new buffer if the current one is not updatable
  28399. * Returns the updated WebGLBuffer.
  28400. */
  28401. VertexBuffer.prototype.update = function (data) {
  28402. return this._buffer.update(data);
  28403. };
  28404. /**
  28405. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28406. * Returns the directly updated WebGLBuffer.
  28407. */
  28408. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  28409. return this._buffer.updateDirectly(data, offset);
  28410. };
  28411. /**
  28412. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28413. */
  28414. VertexBuffer.prototype.dispose = function () {
  28415. if (this._ownsBuffer) {
  28416. this._buffer.dispose();
  28417. }
  28418. };
  28419. /**
  28420. * Enumerates each value of this vertex buffer as numbers.
  28421. * @param count the number of values to enumerate
  28422. * @param callback the callback function called for each value
  28423. */
  28424. VertexBuffer.prototype.forEach = function (count, callback) {
  28425. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28426. };
  28427. Object.defineProperty(VertexBuffer, "PositionKind", {
  28428. get: function () {
  28429. return VertexBuffer._PositionKind;
  28430. },
  28431. enumerable: true,
  28432. configurable: true
  28433. });
  28434. Object.defineProperty(VertexBuffer, "NormalKind", {
  28435. get: function () {
  28436. return VertexBuffer._NormalKind;
  28437. },
  28438. enumerable: true,
  28439. configurable: true
  28440. });
  28441. Object.defineProperty(VertexBuffer, "TangentKind", {
  28442. get: function () {
  28443. return VertexBuffer._TangentKind;
  28444. },
  28445. enumerable: true,
  28446. configurable: true
  28447. });
  28448. Object.defineProperty(VertexBuffer, "UVKind", {
  28449. get: function () {
  28450. return VertexBuffer._UVKind;
  28451. },
  28452. enumerable: true,
  28453. configurable: true
  28454. });
  28455. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28456. get: function () {
  28457. return VertexBuffer._UV2Kind;
  28458. },
  28459. enumerable: true,
  28460. configurable: true
  28461. });
  28462. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28463. get: function () {
  28464. return VertexBuffer._UV3Kind;
  28465. },
  28466. enumerable: true,
  28467. configurable: true
  28468. });
  28469. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28470. get: function () {
  28471. return VertexBuffer._UV4Kind;
  28472. },
  28473. enumerable: true,
  28474. configurable: true
  28475. });
  28476. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28477. get: function () {
  28478. return VertexBuffer._UV5Kind;
  28479. },
  28480. enumerable: true,
  28481. configurable: true
  28482. });
  28483. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28484. get: function () {
  28485. return VertexBuffer._UV6Kind;
  28486. },
  28487. enumerable: true,
  28488. configurable: true
  28489. });
  28490. Object.defineProperty(VertexBuffer, "ColorKind", {
  28491. get: function () {
  28492. return VertexBuffer._ColorKind;
  28493. },
  28494. enumerable: true,
  28495. configurable: true
  28496. });
  28497. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28498. get: function () {
  28499. return VertexBuffer._MatricesIndicesKind;
  28500. },
  28501. enumerable: true,
  28502. configurable: true
  28503. });
  28504. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28505. get: function () {
  28506. return VertexBuffer._MatricesWeightsKind;
  28507. },
  28508. enumerable: true,
  28509. configurable: true
  28510. });
  28511. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28512. get: function () {
  28513. return VertexBuffer._MatricesIndicesExtraKind;
  28514. },
  28515. enumerable: true,
  28516. configurable: true
  28517. });
  28518. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28519. get: function () {
  28520. return VertexBuffer._MatricesWeightsExtraKind;
  28521. },
  28522. enumerable: true,
  28523. configurable: true
  28524. });
  28525. /**
  28526. * Deduces the stride given a kind.
  28527. * @param kind The kind string to deduce
  28528. * @returns The deduced stride
  28529. */
  28530. VertexBuffer.DeduceStride = function (kind) {
  28531. switch (kind) {
  28532. case VertexBuffer.UVKind:
  28533. case VertexBuffer.UV2Kind:
  28534. case VertexBuffer.UV3Kind:
  28535. case VertexBuffer.UV4Kind:
  28536. case VertexBuffer.UV5Kind:
  28537. case VertexBuffer.UV6Kind:
  28538. return 2;
  28539. case VertexBuffer.NormalKind:
  28540. case VertexBuffer.PositionKind:
  28541. return 3;
  28542. case VertexBuffer.ColorKind:
  28543. case VertexBuffer.MatricesIndicesKind:
  28544. case VertexBuffer.MatricesIndicesExtraKind:
  28545. case VertexBuffer.MatricesWeightsKind:
  28546. case VertexBuffer.MatricesWeightsExtraKind:
  28547. case VertexBuffer.TangentKind:
  28548. return 4;
  28549. default:
  28550. throw new Error("Invalid kind '" + kind + "'");
  28551. }
  28552. };
  28553. /**
  28554. * Gets the byte length of the given type.
  28555. * @param type the type
  28556. * @returns the number of bytes
  28557. */
  28558. VertexBuffer.GetTypeByteLength = function (type) {
  28559. switch (type) {
  28560. case VertexBuffer.BYTE:
  28561. case VertexBuffer.UNSIGNED_BYTE:
  28562. return 1;
  28563. case VertexBuffer.SHORT:
  28564. case VertexBuffer.UNSIGNED_SHORT:
  28565. return 2;
  28566. case VertexBuffer.INT:
  28567. case VertexBuffer.FLOAT:
  28568. return 4;
  28569. default:
  28570. throw new Error("Invalid type '" + type + "'");
  28571. }
  28572. };
  28573. /**
  28574. * Enumerates each value of the given parameters as numbers.
  28575. * @param data the data to enumerate
  28576. * @param byteOffset the byte offset of the data
  28577. * @param byteStride the byte stride of the data
  28578. * @param componentCount the number of components per element
  28579. * @param componentType the type of the component
  28580. * @param count the total number of components
  28581. * @param normalized whether the data is normalized
  28582. * @param callback the callback function called for each value
  28583. */
  28584. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  28585. if (data instanceof Array) {
  28586. var offset = byteOffset / 4;
  28587. var stride = byteStride / 4;
  28588. for (var index = 0; index < count; index += componentCount) {
  28589. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28590. callback(data[offset + componentIndex], index + componentIndex);
  28591. }
  28592. offset += stride;
  28593. }
  28594. }
  28595. else {
  28596. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  28597. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  28598. for (var index = 0; index < count; index += componentCount) {
  28599. var componentByteOffset = byteOffset;
  28600. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28601. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  28602. callback(value, index + componentIndex);
  28603. componentByteOffset += componentByteLength;
  28604. }
  28605. byteOffset += byteStride;
  28606. }
  28607. }
  28608. };
  28609. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  28610. switch (type) {
  28611. case VertexBuffer.BYTE: {
  28612. var value = dataView.getInt8(byteOffset);
  28613. if (normalized) {
  28614. value = (value + 0.5) / 127.5;
  28615. }
  28616. return value;
  28617. }
  28618. case VertexBuffer.UNSIGNED_BYTE: {
  28619. var value = dataView.getUint8(byteOffset);
  28620. if (normalized) {
  28621. value = value / 255;
  28622. }
  28623. return value;
  28624. }
  28625. case VertexBuffer.SHORT: {
  28626. var value = dataView.getInt16(byteOffset, true);
  28627. if (normalized) {
  28628. value = (value + 0.5) / 16383.5;
  28629. }
  28630. return value;
  28631. }
  28632. case VertexBuffer.UNSIGNED_SHORT: {
  28633. var value = dataView.getUint16(byteOffset, true);
  28634. if (normalized) {
  28635. value = value / 65535;
  28636. }
  28637. return value;
  28638. }
  28639. case VertexBuffer.FLOAT: {
  28640. return dataView.getFloat32(byteOffset, true);
  28641. }
  28642. default: {
  28643. throw new Error("Invalid component type " + type);
  28644. }
  28645. }
  28646. };
  28647. /**
  28648. * The byte type.
  28649. */
  28650. VertexBuffer.BYTE = 5120;
  28651. /**
  28652. * The unsigned byte type.
  28653. */
  28654. VertexBuffer.UNSIGNED_BYTE = 5121;
  28655. /**
  28656. * The short type.
  28657. */
  28658. VertexBuffer.SHORT = 5122;
  28659. /**
  28660. * The unsigned short type.
  28661. */
  28662. VertexBuffer.UNSIGNED_SHORT = 5123;
  28663. /**
  28664. * The integer type.
  28665. */
  28666. VertexBuffer.INT = 5124;
  28667. /**
  28668. * The unsigned integer type.
  28669. */
  28670. VertexBuffer.UNSIGNED_INT = 5125;
  28671. /**
  28672. * The float type.
  28673. */
  28674. VertexBuffer.FLOAT = 5126;
  28675. // Enums
  28676. VertexBuffer._PositionKind = "position";
  28677. VertexBuffer._NormalKind = "normal";
  28678. VertexBuffer._TangentKind = "tangent";
  28679. VertexBuffer._UVKind = "uv";
  28680. VertexBuffer._UV2Kind = "uv2";
  28681. VertexBuffer._UV3Kind = "uv3";
  28682. VertexBuffer._UV4Kind = "uv4";
  28683. VertexBuffer._UV5Kind = "uv5";
  28684. VertexBuffer._UV6Kind = "uv6";
  28685. VertexBuffer._ColorKind = "color";
  28686. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  28687. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  28688. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  28689. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  28690. return VertexBuffer;
  28691. }());
  28692. BABYLON.VertexBuffer = VertexBuffer;
  28693. })(BABYLON || (BABYLON = {}));
  28694. //# sourceMappingURL=babylon.vertexBuffer.js.map
  28695. "use strict";
  28696. var BABYLON;
  28697. (function (BABYLON) {
  28698. /**
  28699. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  28700. */
  28701. var DummyInternalTextureTracker = /** @class */ (function () {
  28702. function DummyInternalTextureTracker() {
  28703. /**
  28704. * Gets or set the previous tracker in the list
  28705. */
  28706. this.previous = null;
  28707. /**
  28708. * Gets or set the next tracker in the list
  28709. */
  28710. this.next = null;
  28711. }
  28712. return DummyInternalTextureTracker;
  28713. }());
  28714. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  28715. })(BABYLON || (BABYLON = {}));
  28716. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  28717. "use strict";
  28718. var BABYLON;
  28719. (function (BABYLON) {
  28720. /**
  28721. * Class used to store data associated with WebGL texture data for the engine
  28722. * This class should not be used directly
  28723. */
  28724. var InternalTexture = /** @class */ (function () {
  28725. /**
  28726. * Creates a new InternalTexture
  28727. * @param engine defines the engine to use
  28728. * @param dataSource defines the type of data that will be used
  28729. */
  28730. function InternalTexture(engine, dataSource) {
  28731. /**
  28732. * Observable called when the texture is loaded
  28733. */
  28734. this.onLoadedObservable = new BABYLON.Observable();
  28735. /**
  28736. * Gets or set the previous tracker in the list
  28737. */
  28738. this.previous = null;
  28739. /**
  28740. * Gets or set the next tracker in the list
  28741. */
  28742. this.next = null;
  28743. // Private
  28744. /** @ignore */
  28745. this._initialSlot = -1;
  28746. /** @ignore */
  28747. this._designatedSlot = -1;
  28748. /** @ignore */
  28749. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  28750. /** @ignore */
  28751. this._comparisonFunction = 0;
  28752. /** @ignore */
  28753. this._references = 1;
  28754. this._engine = engine;
  28755. this._dataSource = dataSource;
  28756. this._webGLTexture = engine._createTexture();
  28757. }
  28758. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  28759. /**
  28760. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  28761. */
  28762. get: function () {
  28763. return this._dataSource;
  28764. },
  28765. enumerable: true,
  28766. configurable: true
  28767. });
  28768. /**
  28769. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  28770. */
  28771. InternalTexture.prototype.incrementReferences = function () {
  28772. this._references++;
  28773. };
  28774. /**
  28775. * Change the size of the texture (not the size of the content)
  28776. * @param width defines the new width
  28777. * @param height defines the new height
  28778. * @param depth defines the new depth (1 by default)
  28779. */
  28780. InternalTexture.prototype.updateSize = function (width, height, depth) {
  28781. if (depth === void 0) { depth = 1; }
  28782. this.width = width;
  28783. this.height = height;
  28784. this.depth = depth;
  28785. this.baseWidth = width;
  28786. this.baseHeight = height;
  28787. this.baseDepth = depth;
  28788. this._size = width * height * depth;
  28789. };
  28790. /** @ignore */
  28791. InternalTexture.prototype._rebuild = function () {
  28792. var _this = this;
  28793. var proxy;
  28794. this.isReady = false;
  28795. this._cachedCoordinatesMode = null;
  28796. this._cachedWrapU = null;
  28797. this._cachedWrapV = null;
  28798. this._cachedAnisotropicFilteringLevel = null;
  28799. switch (this._dataSource) {
  28800. case InternalTexture.DATASOURCE_TEMP:
  28801. return;
  28802. case InternalTexture.DATASOURCE_URL:
  28803. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  28804. _this.isReady = true;
  28805. }, null, this._buffer, undefined, this.format);
  28806. proxy._swapAndDie(this);
  28807. return;
  28808. case InternalTexture.DATASOURCE_RAW:
  28809. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28810. proxy._swapAndDie(this);
  28811. this.isReady = true;
  28812. return;
  28813. case InternalTexture.DATASOURCE_RAW3D:
  28814. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28815. proxy._swapAndDie(this);
  28816. this.isReady = true;
  28817. return;
  28818. case InternalTexture.DATASOURCE_DYNAMIC:
  28819. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  28820. proxy._swapAndDie(this);
  28821. // The engine will make sure to update content so no need to flag it as isReady = true
  28822. return;
  28823. case InternalTexture.DATASOURCE_RENDERTARGET:
  28824. var options = new BABYLON.RenderTargetCreationOptions();
  28825. options.generateDepthBuffer = this._generateDepthBuffer;
  28826. options.generateMipMaps = this.generateMipMaps;
  28827. options.generateStencilBuffer = this._generateStencilBuffer;
  28828. options.samplingMode = this.samplingMode;
  28829. options.type = this.type;
  28830. if (this.isCube) {
  28831. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  28832. }
  28833. else {
  28834. var size = {
  28835. width: this.width,
  28836. height: this.height
  28837. };
  28838. proxy = this._engine.createRenderTargetTexture(size, options);
  28839. }
  28840. proxy._swapAndDie(this);
  28841. this.isReady = true;
  28842. return;
  28843. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  28844. var depthTextureOptions = {
  28845. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  28846. comparisonFunction: this._comparisonFunction,
  28847. generateStencil: this._generateStencilBuffer,
  28848. isCube: this.isCube
  28849. };
  28850. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  28851. proxy._swapAndDie(this);
  28852. this.isReady = true;
  28853. return;
  28854. case InternalTexture.DATASOURCE_CUBE:
  28855. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  28856. _this.isReady = true;
  28857. }, null, this.format, this._extension);
  28858. proxy._swapAndDie(this);
  28859. return;
  28860. case InternalTexture.DATASOURCE_CUBERAW:
  28861. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  28862. proxy._swapAndDie(this);
  28863. this.isReady = true;
  28864. return;
  28865. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  28866. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  28867. if (proxy) {
  28868. proxy._swapAndDie(_this);
  28869. }
  28870. _this.isReady = true;
  28871. }, null, this.format, this._extension);
  28872. return;
  28873. }
  28874. };
  28875. InternalTexture.prototype._swapAndDie = function (target) {
  28876. target._webGLTexture = this._webGLTexture;
  28877. if (this._framebuffer) {
  28878. target._framebuffer = this._framebuffer;
  28879. }
  28880. if (this._depthStencilBuffer) {
  28881. target._depthStencilBuffer = this._depthStencilBuffer;
  28882. }
  28883. if (this._lodTextureHigh) {
  28884. if (target._lodTextureHigh) {
  28885. target._lodTextureHigh.dispose();
  28886. }
  28887. target._lodTextureHigh = this._lodTextureHigh;
  28888. }
  28889. if (this._lodTextureMid) {
  28890. if (target._lodTextureMid) {
  28891. target._lodTextureMid.dispose();
  28892. }
  28893. target._lodTextureMid = this._lodTextureMid;
  28894. }
  28895. if (this._lodTextureLow) {
  28896. if (target._lodTextureLow) {
  28897. target._lodTextureLow.dispose();
  28898. }
  28899. target._lodTextureLow = this._lodTextureLow;
  28900. }
  28901. var cache = this._engine.getLoadedTexturesCache();
  28902. var index = cache.indexOf(this);
  28903. if (index !== -1) {
  28904. cache.splice(index, 1);
  28905. }
  28906. };
  28907. /**
  28908. * Dispose the current allocated resources
  28909. */
  28910. InternalTexture.prototype.dispose = function () {
  28911. if (!this._webGLTexture) {
  28912. return;
  28913. }
  28914. this._references--;
  28915. if (this._references === 0) {
  28916. this._engine._releaseTexture(this);
  28917. this._webGLTexture = null;
  28918. this.previous = null;
  28919. this.next = null;
  28920. }
  28921. };
  28922. /**
  28923. * The source of the texture data is unknown
  28924. */
  28925. InternalTexture.DATASOURCE_UNKNOWN = 0;
  28926. /**
  28927. * Texture data comes from an URL
  28928. */
  28929. InternalTexture.DATASOURCE_URL = 1;
  28930. /**
  28931. * Texture data is only used for temporary storage
  28932. */
  28933. InternalTexture.DATASOURCE_TEMP = 2;
  28934. /**
  28935. * Texture data comes from raw data (ArrayBuffer)
  28936. */
  28937. InternalTexture.DATASOURCE_RAW = 3;
  28938. /**
  28939. * Texture content is dynamic (video or dynamic texture)
  28940. */
  28941. InternalTexture.DATASOURCE_DYNAMIC = 4;
  28942. /**
  28943. * Texture content is generated by rendering to it
  28944. */
  28945. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  28946. /**
  28947. * Texture content is part of a multi render target process
  28948. */
  28949. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  28950. /**
  28951. * Texture data comes from a cube data file
  28952. */
  28953. InternalTexture.DATASOURCE_CUBE = 7;
  28954. /**
  28955. * Texture data comes from a raw cube data
  28956. */
  28957. InternalTexture.DATASOURCE_CUBERAW = 8;
  28958. /**
  28959. * Texture data come from a prefiltered cube data file
  28960. */
  28961. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  28962. /**
  28963. * Texture content is raw 3D data
  28964. */
  28965. InternalTexture.DATASOURCE_RAW3D = 10;
  28966. /**
  28967. * Texture content is a depth texture
  28968. */
  28969. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  28970. return InternalTexture;
  28971. }());
  28972. BABYLON.InternalTexture = InternalTexture;
  28973. })(BABYLON || (BABYLON = {}));
  28974. //# sourceMappingURL=babylon.internalTexture.js.map
  28975. "use strict";
  28976. var BABYLON;
  28977. (function (BABYLON) {
  28978. var BaseTexture = /** @class */ (function () {
  28979. function BaseTexture(scene) {
  28980. this._hasAlpha = false;
  28981. this.getAlphaFromRGB = false;
  28982. this.level = 1;
  28983. this.coordinatesIndex = 0;
  28984. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  28985. /**
  28986. * | Value | Type | Description |
  28987. * | ----- | ------------------ | ----------- |
  28988. * | 0 | CLAMP_ADDRESSMODE | |
  28989. * | 1 | WRAP_ADDRESSMODE | |
  28990. * | 2 | MIRROR_ADDRESSMODE | |
  28991. */
  28992. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28993. /**
  28994. * | Value | Type | Description |
  28995. * | ----- | ------------------ | ----------- |
  28996. * | 0 | CLAMP_ADDRESSMODE | |
  28997. * | 1 | WRAP_ADDRESSMODE | |
  28998. * | 2 | MIRROR_ADDRESSMODE | |
  28999. */
  29000. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29001. /**
  29002. * | Value | Type | Description |
  29003. * | ----- | ------------------ | ----------- |
  29004. * | 0 | CLAMP_ADDRESSMODE | |
  29005. * | 1 | WRAP_ADDRESSMODE | |
  29006. * | 2 | MIRROR_ADDRESSMODE | |
  29007. */
  29008. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29009. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29010. this.isCube = false;
  29011. this.is3D = false;
  29012. this.gammaSpace = true;
  29013. this.invertZ = false;
  29014. this.lodLevelInAlpha = false;
  29015. this.lodGenerationOffset = 0.0;
  29016. this.lodGenerationScale = 0.8;
  29017. this.isRenderTarget = false;
  29018. this.animations = new Array();
  29019. /**
  29020. * An event triggered when the texture is disposed.
  29021. */
  29022. this.onDisposeObservable = new BABYLON.Observable();
  29023. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29024. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29025. if (this._scene) {
  29026. this._scene.textures.push(this);
  29027. }
  29028. this._uid = null;
  29029. }
  29030. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29031. get: function () {
  29032. return this._hasAlpha;
  29033. },
  29034. set: function (value) {
  29035. if (this._hasAlpha === value) {
  29036. return;
  29037. }
  29038. this._hasAlpha = value;
  29039. if (this._scene) {
  29040. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29041. }
  29042. },
  29043. enumerable: true,
  29044. configurable: true
  29045. });
  29046. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29047. get: function () {
  29048. return this._coordinatesMode;
  29049. },
  29050. /**
  29051. * How a texture is mapped.
  29052. *
  29053. * | Value | Type | Description |
  29054. * | ----- | ----------------------------------- | ----------- |
  29055. * | 0 | EXPLICIT_MODE | |
  29056. * | 1 | SPHERICAL_MODE | |
  29057. * | 2 | PLANAR_MODE | |
  29058. * | 3 | CUBIC_MODE | |
  29059. * | 4 | PROJECTION_MODE | |
  29060. * | 5 | SKYBOX_MODE | |
  29061. * | 6 | INVCUBIC_MODE | |
  29062. * | 7 | EQUIRECTANGULAR_MODE | |
  29063. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29064. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29065. */
  29066. set: function (value) {
  29067. if (this._coordinatesMode === value) {
  29068. return;
  29069. }
  29070. this._coordinatesMode = value;
  29071. if (this._scene) {
  29072. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29073. }
  29074. },
  29075. enumerable: true,
  29076. configurable: true
  29077. });
  29078. Object.defineProperty(BaseTexture.prototype, "uid", {
  29079. get: function () {
  29080. if (!this._uid) {
  29081. this._uid = BABYLON.Tools.RandomId();
  29082. }
  29083. return this._uid;
  29084. },
  29085. enumerable: true,
  29086. configurable: true
  29087. });
  29088. BaseTexture.prototype.toString = function () {
  29089. return this.name;
  29090. };
  29091. BaseTexture.prototype.getClassName = function () {
  29092. return "BaseTexture";
  29093. };
  29094. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29095. set: function (callback) {
  29096. if (this._onDisposeObserver) {
  29097. this.onDisposeObservable.remove(this._onDisposeObserver);
  29098. }
  29099. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29100. },
  29101. enumerable: true,
  29102. configurable: true
  29103. });
  29104. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29105. get: function () {
  29106. return true;
  29107. },
  29108. enumerable: true,
  29109. configurable: true
  29110. });
  29111. BaseTexture.prototype.getScene = function () {
  29112. return this._scene;
  29113. };
  29114. BaseTexture.prototype.getTextureMatrix = function () {
  29115. return BABYLON.Matrix.IdentityReadOnly;
  29116. };
  29117. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29118. return BABYLON.Matrix.IdentityReadOnly;
  29119. };
  29120. BaseTexture.prototype.getInternalTexture = function () {
  29121. return this._texture;
  29122. };
  29123. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29124. return !this.isBlocking || this.isReady();
  29125. };
  29126. BaseTexture.prototype.isReady = function () {
  29127. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29128. this.delayLoad();
  29129. return false;
  29130. }
  29131. if (this._texture) {
  29132. return this._texture.isReady;
  29133. }
  29134. return false;
  29135. };
  29136. BaseTexture.prototype.getSize = function () {
  29137. if (this._texture && this._texture.width) {
  29138. return new BABYLON.Size(this._texture.width, this._texture.height);
  29139. }
  29140. if (this._texture && this._texture._size) {
  29141. return new BABYLON.Size(this._texture._size, this._texture._size);
  29142. }
  29143. return BABYLON.Size.Zero();
  29144. };
  29145. BaseTexture.prototype.getBaseSize = function () {
  29146. if (!this.isReady() || !this._texture)
  29147. return BABYLON.Size.Zero();
  29148. if (this._texture._size) {
  29149. return new BABYLON.Size(this._texture._size, this._texture._size);
  29150. }
  29151. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29152. };
  29153. BaseTexture.prototype.scale = function (ratio) {
  29154. };
  29155. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29156. get: function () {
  29157. return false;
  29158. },
  29159. enumerable: true,
  29160. configurable: true
  29161. });
  29162. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29163. if (!this._scene) {
  29164. return null;
  29165. }
  29166. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29167. for (var index = 0; index < texturesCache.length; index++) {
  29168. var texturesCacheEntry = texturesCache[index];
  29169. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29170. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29171. texturesCacheEntry.incrementReferences();
  29172. return texturesCacheEntry;
  29173. }
  29174. }
  29175. }
  29176. return null;
  29177. };
  29178. BaseTexture.prototype._rebuild = function () {
  29179. };
  29180. BaseTexture.prototype.delayLoad = function () {
  29181. };
  29182. BaseTexture.prototype.clone = function () {
  29183. return null;
  29184. };
  29185. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29186. get: function () {
  29187. if (!this._texture) {
  29188. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29189. }
  29190. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29191. },
  29192. enumerable: true,
  29193. configurable: true
  29194. });
  29195. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29196. get: function () {
  29197. if (!this._texture) {
  29198. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29199. }
  29200. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29201. },
  29202. enumerable: true,
  29203. configurable: true
  29204. });
  29205. BaseTexture.prototype.readPixels = function (faceIndex) {
  29206. if (faceIndex === void 0) { faceIndex = 0; }
  29207. if (!this._texture) {
  29208. return null;
  29209. }
  29210. var size = this.getSize();
  29211. var scene = this.getScene();
  29212. if (!scene) {
  29213. return null;
  29214. }
  29215. var engine = scene.getEngine();
  29216. if (this._texture.isCube) {
  29217. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29218. }
  29219. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29220. };
  29221. BaseTexture.prototype.releaseInternalTexture = function () {
  29222. if (this._texture) {
  29223. this._texture.dispose();
  29224. this._texture = null;
  29225. }
  29226. };
  29227. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29228. get: function () {
  29229. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29230. return null;
  29231. }
  29232. if (!this._texture._sphericalPolynomial) {
  29233. this._texture._sphericalPolynomial =
  29234. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29235. }
  29236. return this._texture._sphericalPolynomial;
  29237. },
  29238. set: function (value) {
  29239. if (this._texture) {
  29240. this._texture._sphericalPolynomial = value;
  29241. }
  29242. },
  29243. enumerable: true,
  29244. configurable: true
  29245. });
  29246. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29247. get: function () {
  29248. if (this._texture) {
  29249. return this._texture._lodTextureHigh;
  29250. }
  29251. return null;
  29252. },
  29253. enumerable: true,
  29254. configurable: true
  29255. });
  29256. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29257. get: function () {
  29258. if (this._texture) {
  29259. return this._texture._lodTextureMid;
  29260. }
  29261. return null;
  29262. },
  29263. enumerable: true,
  29264. configurable: true
  29265. });
  29266. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29267. get: function () {
  29268. if (this._texture) {
  29269. return this._texture._lodTextureLow;
  29270. }
  29271. return null;
  29272. },
  29273. enumerable: true,
  29274. configurable: true
  29275. });
  29276. BaseTexture.prototype.dispose = function () {
  29277. if (!this._scene) {
  29278. return;
  29279. }
  29280. // Animations
  29281. this._scene.stopAnimation(this);
  29282. // Remove from scene
  29283. this._scene._removePendingData(this);
  29284. var index = this._scene.textures.indexOf(this);
  29285. if (index >= 0) {
  29286. this._scene.textures.splice(index, 1);
  29287. }
  29288. if (this._texture === undefined) {
  29289. return;
  29290. }
  29291. // Release
  29292. this.releaseInternalTexture();
  29293. // Callback
  29294. this.onDisposeObservable.notifyObservers(this);
  29295. this.onDisposeObservable.clear();
  29296. };
  29297. BaseTexture.prototype.serialize = function () {
  29298. if (!this.name) {
  29299. return null;
  29300. }
  29301. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29302. // Animations
  29303. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29304. return serializationObject;
  29305. };
  29306. BaseTexture.WhenAllReady = function (textures, callback) {
  29307. var numRemaining = textures.length;
  29308. if (numRemaining === 0) {
  29309. callback();
  29310. return;
  29311. }
  29312. var _loop_1 = function () {
  29313. texture = textures[i];
  29314. if (texture.isReady()) {
  29315. if (--numRemaining === 0) {
  29316. callback();
  29317. }
  29318. }
  29319. else {
  29320. onLoadObservable = texture.onLoadObservable;
  29321. var onLoadCallback_1 = function () {
  29322. onLoadObservable.removeCallback(onLoadCallback_1);
  29323. if (--numRemaining === 0) {
  29324. callback();
  29325. }
  29326. };
  29327. onLoadObservable.add(onLoadCallback_1);
  29328. }
  29329. };
  29330. var texture, onLoadObservable;
  29331. for (var i = 0; i < textures.length; i++) {
  29332. _loop_1();
  29333. }
  29334. };
  29335. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29336. __decorate([
  29337. BABYLON.serialize()
  29338. ], BaseTexture.prototype, "name", void 0);
  29339. __decorate([
  29340. BABYLON.serialize("hasAlpha")
  29341. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29342. __decorate([
  29343. BABYLON.serialize()
  29344. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29345. __decorate([
  29346. BABYLON.serialize()
  29347. ], BaseTexture.prototype, "level", void 0);
  29348. __decorate([
  29349. BABYLON.serialize()
  29350. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29351. __decorate([
  29352. BABYLON.serialize("coordinatesMode")
  29353. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29354. __decorate([
  29355. BABYLON.serialize()
  29356. ], BaseTexture.prototype, "wrapU", void 0);
  29357. __decorate([
  29358. BABYLON.serialize()
  29359. ], BaseTexture.prototype, "wrapV", void 0);
  29360. __decorate([
  29361. BABYLON.serialize()
  29362. ], BaseTexture.prototype, "wrapR", void 0);
  29363. __decorate([
  29364. BABYLON.serialize()
  29365. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29366. __decorate([
  29367. BABYLON.serialize()
  29368. ], BaseTexture.prototype, "isCube", void 0);
  29369. __decorate([
  29370. BABYLON.serialize()
  29371. ], BaseTexture.prototype, "is3D", void 0);
  29372. __decorate([
  29373. BABYLON.serialize()
  29374. ], BaseTexture.prototype, "gammaSpace", void 0);
  29375. __decorate([
  29376. BABYLON.serialize()
  29377. ], BaseTexture.prototype, "invertZ", void 0);
  29378. __decorate([
  29379. BABYLON.serialize()
  29380. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29381. __decorate([
  29382. BABYLON.serialize()
  29383. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29384. __decorate([
  29385. BABYLON.serialize()
  29386. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  29387. __decorate([
  29388. BABYLON.serialize()
  29389. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29390. return BaseTexture;
  29391. }());
  29392. BABYLON.BaseTexture = BaseTexture;
  29393. })(BABYLON || (BABYLON = {}));
  29394. //# sourceMappingURL=babylon.baseTexture.js.map
  29395. "use strict";
  29396. var BABYLON;
  29397. (function (BABYLON) {
  29398. var Texture = /** @class */ (function (_super) {
  29399. __extends(Texture, _super);
  29400. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29401. if (noMipmap === void 0) { noMipmap = false; }
  29402. if (invertY === void 0) { invertY = true; }
  29403. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29404. if (onLoad === void 0) { onLoad = null; }
  29405. if (onError === void 0) { onError = null; }
  29406. if (buffer === void 0) { buffer = null; }
  29407. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29408. var _this = _super.call(this, scene) || this;
  29409. _this.uOffset = 0;
  29410. _this.vOffset = 0;
  29411. _this.uScale = 1.0;
  29412. _this.vScale = 1.0;
  29413. _this.uAng = 0;
  29414. _this.vAng = 0;
  29415. _this.wAng = 0;
  29416. _this._isBlocking = true;
  29417. _this.name = url || "";
  29418. _this.url = url;
  29419. _this._noMipmap = noMipmap;
  29420. _this._invertY = invertY;
  29421. _this._samplingMode = samplingMode;
  29422. _this._buffer = buffer;
  29423. _this._deleteBuffer = deleteBuffer;
  29424. if (format) {
  29425. _this._format = format;
  29426. }
  29427. scene = _this.getScene();
  29428. if (!scene) {
  29429. return _this;
  29430. }
  29431. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29432. var load = function () {
  29433. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29434. _this.onLoadObservable.notifyObservers(_this);
  29435. }
  29436. if (onLoad) {
  29437. onLoad();
  29438. }
  29439. if (!_this.isBlocking && scene) {
  29440. scene.resetCachedMaterial();
  29441. }
  29442. };
  29443. if (!_this.url) {
  29444. _this._delayedOnLoad = load;
  29445. _this._delayedOnError = onError;
  29446. return _this;
  29447. }
  29448. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  29449. if (!_this._texture) {
  29450. if (!scene.useDelayedTextureLoading) {
  29451. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  29452. if (deleteBuffer) {
  29453. delete _this._buffer;
  29454. }
  29455. }
  29456. else {
  29457. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29458. _this._delayedOnLoad = load;
  29459. _this._delayedOnError = onError;
  29460. }
  29461. }
  29462. else {
  29463. if (_this._texture.isReady) {
  29464. BABYLON.Tools.SetImmediate(function () { return load(); });
  29465. }
  29466. else {
  29467. _this._texture.onLoadedObservable.add(load);
  29468. }
  29469. }
  29470. return _this;
  29471. }
  29472. Object.defineProperty(Texture.prototype, "noMipmap", {
  29473. get: function () {
  29474. return this._noMipmap;
  29475. },
  29476. enumerable: true,
  29477. configurable: true
  29478. });
  29479. Object.defineProperty(Texture.prototype, "isBlocking", {
  29480. get: function () {
  29481. return this._isBlocking;
  29482. },
  29483. set: function (value) {
  29484. this._isBlocking = value;
  29485. },
  29486. enumerable: true,
  29487. configurable: true
  29488. });
  29489. Object.defineProperty(Texture.prototype, "samplingMode", {
  29490. get: function () {
  29491. return this._samplingMode;
  29492. },
  29493. enumerable: true,
  29494. configurable: true
  29495. });
  29496. Texture.prototype.updateURL = function (url) {
  29497. this.url = url;
  29498. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29499. this.delayLoad();
  29500. };
  29501. Texture.prototype.delayLoad = function () {
  29502. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29503. return;
  29504. }
  29505. var scene = this.getScene();
  29506. if (!scene) {
  29507. return;
  29508. }
  29509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29510. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  29511. if (!this._texture) {
  29512. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  29513. if (this._deleteBuffer) {
  29514. delete this._buffer;
  29515. }
  29516. }
  29517. else {
  29518. if (this._delayedOnLoad) {
  29519. if (this._texture.isReady) {
  29520. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  29521. }
  29522. else {
  29523. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  29524. }
  29525. }
  29526. }
  29527. this._delayedOnLoad = null;
  29528. this._delayedOnError = null;
  29529. };
  29530. Texture.prototype.updateSamplingMode = function (samplingMode) {
  29531. if (!this._texture) {
  29532. return;
  29533. }
  29534. var scene = this.getScene();
  29535. if (!scene) {
  29536. return;
  29537. }
  29538. this._samplingMode = samplingMode;
  29539. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  29540. };
  29541. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  29542. x *= this.uScale;
  29543. y *= this.vScale;
  29544. x -= 0.5 * this.uScale;
  29545. y -= 0.5 * this.vScale;
  29546. z -= 0.5;
  29547. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  29548. t.x += 0.5 * this.uScale + this.uOffset;
  29549. t.y += 0.5 * this.vScale + this.vOffset;
  29550. t.z += 0.5;
  29551. };
  29552. Texture.prototype.getTextureMatrix = function () {
  29553. var _this = this;
  29554. if (this.uOffset === this._cachedUOffset &&
  29555. this.vOffset === this._cachedVOffset &&
  29556. this.uScale === this._cachedUScale &&
  29557. this.vScale === this._cachedVScale &&
  29558. this.uAng === this._cachedUAng &&
  29559. this.vAng === this._cachedVAng &&
  29560. this.wAng === this._cachedWAng) {
  29561. return this._cachedTextureMatrix;
  29562. }
  29563. this._cachedUOffset = this.uOffset;
  29564. this._cachedVOffset = this.vOffset;
  29565. this._cachedUScale = this.uScale;
  29566. this._cachedVScale = this.vScale;
  29567. this._cachedUAng = this.uAng;
  29568. this._cachedVAng = this.vAng;
  29569. this._cachedWAng = this.wAng;
  29570. if (!this._cachedTextureMatrix) {
  29571. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29572. this._rowGenerationMatrix = new BABYLON.Matrix();
  29573. this._t0 = BABYLON.Vector3.Zero();
  29574. this._t1 = BABYLON.Vector3.Zero();
  29575. this._t2 = BABYLON.Vector3.Zero();
  29576. }
  29577. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  29578. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  29579. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  29580. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  29581. this._t1.subtractInPlace(this._t0);
  29582. this._t2.subtractInPlace(this._t0);
  29583. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29584. this._cachedTextureMatrix.m[0] = this._t1.x;
  29585. this._cachedTextureMatrix.m[1] = this._t1.y;
  29586. this._cachedTextureMatrix.m[2] = this._t1.z;
  29587. this._cachedTextureMatrix.m[4] = this._t2.x;
  29588. this._cachedTextureMatrix.m[5] = this._t2.y;
  29589. this._cachedTextureMatrix.m[6] = this._t2.z;
  29590. this._cachedTextureMatrix.m[8] = this._t0.x;
  29591. this._cachedTextureMatrix.m[9] = this._t0.y;
  29592. this._cachedTextureMatrix.m[10] = this._t0.z;
  29593. var scene = this.getScene();
  29594. if (!scene) {
  29595. return this._cachedTextureMatrix;
  29596. }
  29597. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29598. return mat.hasTexture(_this);
  29599. });
  29600. return this._cachedTextureMatrix;
  29601. };
  29602. Texture.prototype.getReflectionTextureMatrix = function () {
  29603. var _this = this;
  29604. var scene = this.getScene();
  29605. if (!scene) {
  29606. return this._cachedTextureMatrix;
  29607. }
  29608. if (this.uOffset === this._cachedUOffset &&
  29609. this.vOffset === this._cachedVOffset &&
  29610. this.uScale === this._cachedUScale &&
  29611. this.vScale === this._cachedVScale &&
  29612. this.coordinatesMode === this._cachedCoordinatesMode) {
  29613. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  29614. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  29615. return this._cachedTextureMatrix;
  29616. }
  29617. }
  29618. else {
  29619. return this._cachedTextureMatrix;
  29620. }
  29621. }
  29622. if (!this._cachedTextureMatrix) {
  29623. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29624. }
  29625. if (!this._projectionModeMatrix) {
  29626. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  29627. }
  29628. this._cachedUOffset = this.uOffset;
  29629. this._cachedVOffset = this.vOffset;
  29630. this._cachedUScale = this.uScale;
  29631. this._cachedVScale = this.vScale;
  29632. this._cachedCoordinatesMode = this.coordinatesMode;
  29633. switch (this.coordinatesMode) {
  29634. case Texture.PLANAR_MODE:
  29635. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29636. this._cachedTextureMatrix[0] = this.uScale;
  29637. this._cachedTextureMatrix[5] = this.vScale;
  29638. this._cachedTextureMatrix[12] = this.uOffset;
  29639. this._cachedTextureMatrix[13] = this.vOffset;
  29640. break;
  29641. case Texture.PROJECTION_MODE:
  29642. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  29643. this._projectionModeMatrix.m[0] = 0.5;
  29644. this._projectionModeMatrix.m[5] = -0.5;
  29645. this._projectionModeMatrix.m[10] = 0.0;
  29646. this._projectionModeMatrix.m[12] = 0.5;
  29647. this._projectionModeMatrix.m[13] = 0.5;
  29648. this._projectionModeMatrix.m[14] = 1.0;
  29649. this._projectionModeMatrix.m[15] = 1.0;
  29650. var projectionMatrix = scene.getProjectionMatrix();
  29651. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  29652. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  29653. break;
  29654. default:
  29655. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29656. break;
  29657. }
  29658. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29659. return (mat.getActiveTextures().indexOf(_this) !== -1);
  29660. });
  29661. return this._cachedTextureMatrix;
  29662. };
  29663. Texture.prototype.clone = function () {
  29664. var _this = this;
  29665. return BABYLON.SerializationHelper.Clone(function () {
  29666. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  29667. }, this);
  29668. };
  29669. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  29670. get: function () {
  29671. if (!this._onLoadObservable) {
  29672. this._onLoadObservable = new BABYLON.Observable();
  29673. }
  29674. return this._onLoadObservable;
  29675. },
  29676. enumerable: true,
  29677. configurable: true
  29678. });
  29679. Texture.prototype.serialize = function () {
  29680. var serializationObject = _super.prototype.serialize.call(this);
  29681. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  29682. serializationObject.base64String = this._buffer;
  29683. serializationObject.name = serializationObject.name.replace("data:", "");
  29684. }
  29685. return serializationObject;
  29686. };
  29687. Texture.prototype.getClassName = function () {
  29688. return "Texture";
  29689. };
  29690. Texture.prototype.dispose = function () {
  29691. _super.prototype.dispose.call(this);
  29692. if (this.onLoadObservable) {
  29693. this.onLoadObservable.clear();
  29694. this._onLoadObservable = null;
  29695. }
  29696. this._delayedOnLoad = null;
  29697. this._delayedOnError = null;
  29698. };
  29699. // Statics
  29700. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  29701. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29702. if (onLoad === void 0) { onLoad = null; }
  29703. if (onError === void 0) { onError = null; }
  29704. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  29705. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  29706. };
  29707. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  29708. if (parsedTexture.customType) {
  29709. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  29710. // Update Sampling Mode
  29711. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  29712. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  29713. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  29714. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  29715. }
  29716. }
  29717. return parsedCustomTexture;
  29718. }
  29719. if (parsedTexture.isCube) {
  29720. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  29721. }
  29722. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  29723. return null;
  29724. }
  29725. var texture = BABYLON.SerializationHelper.Parse(function () {
  29726. var generateMipMaps = true;
  29727. if (parsedTexture.noMipmap) {
  29728. generateMipMaps = false;
  29729. }
  29730. if (parsedTexture.mirrorPlane) {
  29731. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  29732. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  29733. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  29734. return mirrorTexture;
  29735. }
  29736. else if (parsedTexture.isRenderTarget) {
  29737. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  29738. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  29739. return renderTargetTexture;
  29740. }
  29741. else {
  29742. var texture;
  29743. if (parsedTexture.base64String) {
  29744. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  29745. }
  29746. else {
  29747. var url = rootUrl + parsedTexture.name;
  29748. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  29749. url = parsedTexture.url;
  29750. }
  29751. texture = new Texture(url, scene, !generateMipMaps);
  29752. }
  29753. return texture;
  29754. }
  29755. }, parsedTexture, scene);
  29756. // Update Sampling Mode
  29757. if (parsedTexture.samplingMode) {
  29758. var sampling = parsedTexture.samplingMode;
  29759. if (texture._samplingMode !== sampling) {
  29760. texture.updateSamplingMode(sampling);
  29761. }
  29762. }
  29763. // Animations
  29764. if (parsedTexture.animations) {
  29765. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  29766. var parsedAnimation = parsedTexture.animations[animationIndex];
  29767. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29768. }
  29769. }
  29770. return texture;
  29771. };
  29772. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  29773. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29774. if (noMipmap === void 0) { noMipmap = false; }
  29775. if (invertY === void 0) { invertY = true; }
  29776. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29777. if (onLoad === void 0) { onLoad = null; }
  29778. if (onError === void 0) { onError = null; }
  29779. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  29780. if (name.substr(0, 5) !== "data:") {
  29781. name = "data:" + name;
  29782. }
  29783. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  29784. };
  29785. // Constants
  29786. Texture.NEAREST_SAMPLINGMODE = 1;
  29787. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  29788. Texture.BILINEAR_SAMPLINGMODE = 2;
  29789. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  29790. Texture.TRILINEAR_SAMPLINGMODE = 3;
  29791. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  29792. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  29793. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  29794. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  29795. Texture.NEAREST_LINEAR = 7;
  29796. Texture.NEAREST_NEAREST = 8;
  29797. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  29798. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  29799. Texture.LINEAR_LINEAR = 11;
  29800. Texture.LINEAR_NEAREST = 12;
  29801. Texture.EXPLICIT_MODE = 0;
  29802. Texture.SPHERICAL_MODE = 1;
  29803. Texture.PLANAR_MODE = 2;
  29804. Texture.CUBIC_MODE = 3;
  29805. Texture.PROJECTION_MODE = 4;
  29806. Texture.SKYBOX_MODE = 5;
  29807. Texture.INVCUBIC_MODE = 6;
  29808. Texture.EQUIRECTANGULAR_MODE = 7;
  29809. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  29810. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  29811. Texture.CLAMP_ADDRESSMODE = 0;
  29812. Texture.WRAP_ADDRESSMODE = 1;
  29813. Texture.MIRROR_ADDRESSMODE = 2;
  29814. /**
  29815. * 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
  29816. */
  29817. Texture.UseSerializedUrlIfAny = false;
  29818. __decorate([
  29819. BABYLON.serialize()
  29820. ], Texture.prototype, "url", void 0);
  29821. __decorate([
  29822. BABYLON.serialize()
  29823. ], Texture.prototype, "uOffset", void 0);
  29824. __decorate([
  29825. BABYLON.serialize()
  29826. ], Texture.prototype, "vOffset", void 0);
  29827. __decorate([
  29828. BABYLON.serialize()
  29829. ], Texture.prototype, "uScale", void 0);
  29830. __decorate([
  29831. BABYLON.serialize()
  29832. ], Texture.prototype, "vScale", void 0);
  29833. __decorate([
  29834. BABYLON.serialize()
  29835. ], Texture.prototype, "uAng", void 0);
  29836. __decorate([
  29837. BABYLON.serialize()
  29838. ], Texture.prototype, "vAng", void 0);
  29839. __decorate([
  29840. BABYLON.serialize()
  29841. ], Texture.prototype, "wAng", void 0);
  29842. __decorate([
  29843. BABYLON.serialize()
  29844. ], Texture.prototype, "isBlocking", null);
  29845. return Texture;
  29846. }(BABYLON.BaseTexture));
  29847. BABYLON.Texture = Texture;
  29848. })(BABYLON || (BABYLON = {}));
  29849. //# sourceMappingURL=babylon.texture.js.map
  29850. "use strict";
  29851. var BABYLON;
  29852. (function (BABYLON) {
  29853. var _InstancesBatch = /** @class */ (function () {
  29854. function _InstancesBatch() {
  29855. this.mustReturn = false;
  29856. this.visibleInstances = new Array();
  29857. this.renderSelf = new Array();
  29858. }
  29859. return _InstancesBatch;
  29860. }());
  29861. BABYLON._InstancesBatch = _InstancesBatch;
  29862. var Mesh = /** @class */ (function (_super) {
  29863. __extends(Mesh, _super);
  29864. /**
  29865. * @constructor
  29866. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  29867. * @param {Scene} scene The scene to add this mesh to.
  29868. * @param {Node} parent The parent of this mesh, if it has one
  29869. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  29870. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  29871. * When false, achieved by calling a clone(), also passing False.
  29872. * This will make creation of children, recursive.
  29873. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  29874. */
  29875. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  29876. if (scene === void 0) { scene = null; }
  29877. if (parent === void 0) { parent = null; }
  29878. if (source === void 0) { source = null; }
  29879. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29880. var _this = _super.call(this, name, scene) || this;
  29881. // Events
  29882. /**
  29883. * An event triggered before rendering the mesh
  29884. */
  29885. _this.onBeforeRenderObservable = new BABYLON.Observable();
  29886. /**
  29887. * An event triggered after rendering the mesh
  29888. */
  29889. _this.onAfterRenderObservable = new BABYLON.Observable();
  29890. /**
  29891. * An event triggered before drawing the mesh
  29892. */
  29893. _this.onBeforeDrawObservable = new BABYLON.Observable();
  29894. // Members
  29895. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29896. _this.instances = new Array();
  29897. _this._LODLevels = new Array();
  29898. _this._visibleInstances = {};
  29899. _this._renderIdForInstances = new Array();
  29900. _this._batchCache = new _InstancesBatch();
  29901. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  29902. // Use by builder only to know what orientation were the mesh build in.
  29903. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  29904. _this.overrideMaterialSideOrientation = null;
  29905. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  29906. // Will be used to save a source mesh reference, If any
  29907. _this._source = null;
  29908. scene = _this.getScene();
  29909. if (source) {
  29910. // Source mesh
  29911. _this._source = source;
  29912. // Geometry
  29913. if (source._geometry) {
  29914. source._geometry.applyToMesh(_this);
  29915. }
  29916. // Deep copy
  29917. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  29918. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  29919. // Metadata
  29920. if (source.metadata && source.metadata.clone) {
  29921. _this.metadata = source.metadata.clone();
  29922. }
  29923. else {
  29924. _this.metadata = source.metadata;
  29925. }
  29926. // Tags
  29927. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  29928. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  29929. }
  29930. // Parent
  29931. _this.parent = source.parent;
  29932. // Pivot
  29933. _this.setPivotMatrix(source.getPivotMatrix());
  29934. _this.id = name + "." + source.id;
  29935. // Material
  29936. _this.material = source.material;
  29937. var index;
  29938. if (!doNotCloneChildren) {
  29939. // Children
  29940. var directDescendants = source.getDescendants(true);
  29941. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  29942. var child = directDescendants[index_1];
  29943. if (child.clone) {
  29944. child.clone(name + "." + child.name, _this);
  29945. }
  29946. }
  29947. }
  29948. // Physics clone
  29949. var physicsEngine = _this.getScene().getPhysicsEngine();
  29950. if (clonePhysicsImpostor && physicsEngine) {
  29951. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  29952. if (impostor) {
  29953. _this.physicsImpostor = impostor.clone(_this);
  29954. }
  29955. }
  29956. // Particles
  29957. for (index = 0; index < scene.particleSystems.length; index++) {
  29958. var system = scene.particleSystems[index];
  29959. if (system.emitter === source) {
  29960. system.clone(system.name, _this);
  29961. }
  29962. }
  29963. _this.computeWorldMatrix(true);
  29964. }
  29965. // Parent
  29966. if (parent !== null) {
  29967. _this.parent = parent;
  29968. }
  29969. return _this;
  29970. }
  29971. Object.defineProperty(Mesh, "FRONTSIDE", {
  29972. /**
  29973. * Mesh side orientation : usually the external or front surface
  29974. */
  29975. get: function () {
  29976. return Mesh._FRONTSIDE;
  29977. },
  29978. enumerable: true,
  29979. configurable: true
  29980. });
  29981. Object.defineProperty(Mesh, "BACKSIDE", {
  29982. /**
  29983. * Mesh side orientation : usually the internal or back surface
  29984. */
  29985. get: function () {
  29986. return Mesh._BACKSIDE;
  29987. },
  29988. enumerable: true,
  29989. configurable: true
  29990. });
  29991. Object.defineProperty(Mesh, "DOUBLESIDE", {
  29992. /**
  29993. * Mesh side orientation : both internal and external or front and back surfaces
  29994. */
  29995. get: function () {
  29996. return Mesh._DOUBLESIDE;
  29997. },
  29998. enumerable: true,
  29999. configurable: true
  30000. });
  30001. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30002. /**
  30003. * Mesh side orientation : by default, `FRONTSIDE`
  30004. */
  30005. get: function () {
  30006. return Mesh._DEFAULTSIDE;
  30007. },
  30008. enumerable: true,
  30009. configurable: true
  30010. });
  30011. Object.defineProperty(Mesh, "NO_CAP", {
  30012. /**
  30013. * Mesh cap setting : no cap
  30014. */
  30015. get: function () {
  30016. return Mesh._NO_CAP;
  30017. },
  30018. enumerable: true,
  30019. configurable: true
  30020. });
  30021. Object.defineProperty(Mesh, "CAP_START", {
  30022. /**
  30023. * Mesh cap setting : one cap at the beginning of the mesh
  30024. */
  30025. get: function () {
  30026. return Mesh._CAP_START;
  30027. },
  30028. enumerable: true,
  30029. configurable: true
  30030. });
  30031. Object.defineProperty(Mesh, "CAP_END", {
  30032. /**
  30033. * Mesh cap setting : one cap at the end of the mesh
  30034. */
  30035. get: function () {
  30036. return Mesh._CAP_END;
  30037. },
  30038. enumerable: true,
  30039. configurable: true
  30040. });
  30041. Object.defineProperty(Mesh, "CAP_ALL", {
  30042. /**
  30043. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30044. */
  30045. get: function () {
  30046. return Mesh._CAP_ALL;
  30047. },
  30048. enumerable: true,
  30049. configurable: true
  30050. });
  30051. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30052. set: function (callback) {
  30053. if (this._onBeforeDrawObserver) {
  30054. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30055. }
  30056. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30057. },
  30058. enumerable: true,
  30059. configurable: true
  30060. });
  30061. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30062. get: function () {
  30063. return this._morphTargetManager;
  30064. },
  30065. set: function (value) {
  30066. if (this._morphTargetManager === value) {
  30067. return;
  30068. }
  30069. this._morphTargetManager = value;
  30070. this._syncGeometryWithMorphTargetManager();
  30071. },
  30072. enumerable: true,
  30073. configurable: true
  30074. });
  30075. Object.defineProperty(Mesh.prototype, "source", {
  30076. get: function () {
  30077. return this._source;
  30078. },
  30079. enumerable: true,
  30080. configurable: true
  30081. });
  30082. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30083. get: function () {
  30084. return this._unIndexed;
  30085. },
  30086. set: function (value) {
  30087. if (this._unIndexed !== value) {
  30088. this._unIndexed = value;
  30089. this._markSubMeshesAsAttributesDirty();
  30090. }
  30091. },
  30092. enumerable: true,
  30093. configurable: true
  30094. });
  30095. // Methods
  30096. /**
  30097. * Returns the string "Mesh".
  30098. */
  30099. Mesh.prototype.getClassName = function () {
  30100. return "Mesh";
  30101. };
  30102. /**
  30103. * Returns a string.
  30104. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30105. */
  30106. Mesh.prototype.toString = function (fullDetails) {
  30107. var ret = _super.prototype.toString.call(this, fullDetails);
  30108. ret += ", n vertices: " + this.getTotalVertices();
  30109. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30110. if (this.animations) {
  30111. for (var i = 0; i < this.animations.length; i++) {
  30112. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30113. }
  30114. }
  30115. if (fullDetails) {
  30116. if (this._geometry) {
  30117. var ib = this.getIndices();
  30118. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30119. if (vb && ib) {
  30120. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30121. }
  30122. }
  30123. else {
  30124. ret += ", flat shading: UNKNOWN";
  30125. }
  30126. }
  30127. return ret;
  30128. };
  30129. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30130. /**
  30131. * True if the mesh has some Levels Of Details (LOD).
  30132. * Returns a boolean.
  30133. */
  30134. get: function () {
  30135. return this._LODLevels.length > 0;
  30136. },
  30137. enumerable: true,
  30138. configurable: true
  30139. });
  30140. /**
  30141. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30142. * @returns an array of {BABYLON.MeshLODLevel}
  30143. */
  30144. Mesh.prototype.getLODLevels = function () {
  30145. return this._LODLevels;
  30146. };
  30147. Mesh.prototype._sortLODLevels = function () {
  30148. this._LODLevels.sort(function (a, b) {
  30149. if (a.distance < b.distance) {
  30150. return 1;
  30151. }
  30152. if (a.distance > b.distance) {
  30153. return -1;
  30154. }
  30155. return 0;
  30156. });
  30157. };
  30158. /**
  30159. * Add a mesh as LOD level triggered at the given distance.
  30160. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30161. * @param {number} distance The distance from the center of the object to show this level
  30162. * @param {Mesh} mesh The mesh to be added as LOD level
  30163. * @return {Mesh} This mesh (for chaining)
  30164. */
  30165. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30166. if (mesh && mesh._masterMesh) {
  30167. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30168. return this;
  30169. }
  30170. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30171. this._LODLevels.push(level);
  30172. if (mesh) {
  30173. mesh._masterMesh = this;
  30174. }
  30175. this._sortLODLevels();
  30176. return this;
  30177. };
  30178. /**
  30179. * Returns the LOD level mesh at the passed distance or null if not found.
  30180. * It is related to the method `addLODLevel(distance, mesh)`.
  30181. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30182. * Returns an object Mesh or `null`.
  30183. */
  30184. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30185. for (var index = 0; index < this._LODLevels.length; index++) {
  30186. var level = this._LODLevels[index];
  30187. if (level.distance === distance) {
  30188. return level.mesh;
  30189. }
  30190. }
  30191. return null;
  30192. };
  30193. /**
  30194. * Remove a mesh from the LOD array
  30195. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30196. * @param {Mesh} mesh The mesh to be removed.
  30197. * @return {Mesh} This mesh (for chaining)
  30198. */
  30199. Mesh.prototype.removeLODLevel = function (mesh) {
  30200. for (var index = 0; index < this._LODLevels.length; index++) {
  30201. if (this._LODLevels[index].mesh === mesh) {
  30202. this._LODLevels.splice(index, 1);
  30203. if (mesh) {
  30204. mesh._masterMesh = null;
  30205. }
  30206. }
  30207. }
  30208. this._sortLODLevels();
  30209. return this;
  30210. };
  30211. /**
  30212. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30213. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30214. */
  30215. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30216. if (!this._LODLevels || this._LODLevels.length === 0) {
  30217. return this;
  30218. }
  30219. var bSphere;
  30220. if (boundingSphere) {
  30221. bSphere = boundingSphere;
  30222. }
  30223. else {
  30224. var boundingInfo = this.getBoundingInfo();
  30225. bSphere = boundingInfo.boundingSphere;
  30226. }
  30227. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30228. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30229. if (this.onLODLevelSelection) {
  30230. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30231. }
  30232. return this;
  30233. }
  30234. for (var index = 0; index < this._LODLevels.length; index++) {
  30235. var level = this._LODLevels[index];
  30236. if (level.distance < distanceToCamera) {
  30237. if (level.mesh) {
  30238. level.mesh._preActivate();
  30239. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30240. }
  30241. if (this.onLODLevelSelection) {
  30242. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30243. }
  30244. return level.mesh;
  30245. }
  30246. }
  30247. if (this.onLODLevelSelection) {
  30248. this.onLODLevelSelection(distanceToCamera, this, this);
  30249. }
  30250. return this;
  30251. };
  30252. Object.defineProperty(Mesh.prototype, "geometry", {
  30253. /**
  30254. * Returns the mesh internal Geometry object.
  30255. */
  30256. get: function () {
  30257. return this._geometry;
  30258. },
  30259. enumerable: true,
  30260. configurable: true
  30261. });
  30262. /**
  30263. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30264. */
  30265. Mesh.prototype.getTotalVertices = function () {
  30266. if (this._geometry === null || this._geometry === undefined) {
  30267. return 0;
  30268. }
  30269. return this._geometry.getTotalVertices();
  30270. };
  30271. /**
  30272. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30273. * 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.
  30274. * You can force the copy with forceCopy === true
  30275. * Returns null if the mesh has no geometry or no vertex buffer.
  30276. * Possible `kind` values :
  30277. * - BABYLON.VertexBuffer.PositionKind
  30278. * - BABYLON.VertexBuffer.UVKind
  30279. * - BABYLON.VertexBuffer.UV2Kind
  30280. * - BABYLON.VertexBuffer.UV3Kind
  30281. * - BABYLON.VertexBuffer.UV4Kind
  30282. * - BABYLON.VertexBuffer.UV5Kind
  30283. * - BABYLON.VertexBuffer.UV6Kind
  30284. * - BABYLON.VertexBuffer.ColorKind
  30285. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30286. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30287. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30288. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30289. */
  30290. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30291. if (!this._geometry) {
  30292. return null;
  30293. }
  30294. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30295. };
  30296. /**
  30297. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30298. * Returns `null` if the mesh has no geometry.
  30299. * Possible `kind` values :
  30300. * - BABYLON.VertexBuffer.PositionKind
  30301. * - BABYLON.VertexBuffer.UVKind
  30302. * - BABYLON.VertexBuffer.UV2Kind
  30303. * - BABYLON.VertexBuffer.UV3Kind
  30304. * - BABYLON.VertexBuffer.UV4Kind
  30305. * - BABYLON.VertexBuffer.UV5Kind
  30306. * - BABYLON.VertexBuffer.UV6Kind
  30307. * - BABYLON.VertexBuffer.ColorKind
  30308. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30309. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30310. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30311. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30312. */
  30313. Mesh.prototype.getVertexBuffer = function (kind) {
  30314. if (!this._geometry) {
  30315. return null;
  30316. }
  30317. return this._geometry.getVertexBuffer(kind);
  30318. };
  30319. /**
  30320. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30321. * Possible `kind` values :
  30322. * - BABYLON.VertexBuffer.PositionKind
  30323. * - BABYLON.VertexBuffer.UVKind
  30324. * - BABYLON.VertexBuffer.UV2Kind
  30325. * - BABYLON.VertexBuffer.UV3Kind
  30326. * - BABYLON.VertexBuffer.UV4Kind
  30327. * - BABYLON.VertexBuffer.UV5Kind
  30328. * - BABYLON.VertexBuffer.UV6Kind
  30329. * - BABYLON.VertexBuffer.ColorKind
  30330. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30331. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30332. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30333. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30334. */
  30335. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30336. if (!this._geometry) {
  30337. if (this._delayInfo) {
  30338. return this._delayInfo.indexOf(kind) !== -1;
  30339. }
  30340. return false;
  30341. }
  30342. return this._geometry.isVerticesDataPresent(kind);
  30343. };
  30344. /**
  30345. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30346. * Possible `kind` values :
  30347. * - BABYLON.VertexBuffer.PositionKind
  30348. * - BABYLON.VertexBuffer.UVKind
  30349. * - BABYLON.VertexBuffer.UV2Kind
  30350. * - BABYLON.VertexBuffer.UV3Kind
  30351. * - BABYLON.VertexBuffer.UV4Kind
  30352. * - BABYLON.VertexBuffer.UV5Kind
  30353. * - BABYLON.VertexBuffer.UV6Kind
  30354. * - BABYLON.VertexBuffer.ColorKind
  30355. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30356. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30357. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30358. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30359. */
  30360. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30361. if (!this._geometry) {
  30362. if (this._delayInfo) {
  30363. return this._delayInfo.indexOf(kind) !== -1;
  30364. }
  30365. return false;
  30366. }
  30367. return this._geometry.isVertexBufferUpdatable(kind);
  30368. };
  30369. /**
  30370. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30371. * Possible `kind` values :
  30372. * - BABYLON.VertexBuffer.PositionKind
  30373. * - BABYLON.VertexBuffer.UVKind
  30374. * - BABYLON.VertexBuffer.UV2Kind
  30375. * - BABYLON.VertexBuffer.UV3Kind
  30376. * - BABYLON.VertexBuffer.UV4Kind
  30377. * - BABYLON.VertexBuffer.UV5Kind
  30378. * - BABYLON.VertexBuffer.UV6Kind
  30379. * - BABYLON.VertexBuffer.ColorKind
  30380. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30381. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30382. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30383. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30384. */
  30385. Mesh.prototype.getVerticesDataKinds = function () {
  30386. if (!this._geometry) {
  30387. var result = new Array();
  30388. if (this._delayInfo) {
  30389. this._delayInfo.forEach(function (kind, index, array) {
  30390. result.push(kind);
  30391. });
  30392. }
  30393. return result;
  30394. }
  30395. return this._geometry.getVerticesDataKinds();
  30396. };
  30397. /**
  30398. * Returns a positive integer : the total number of indices in this mesh geometry.
  30399. * Returns zero if the mesh has no geometry.
  30400. */
  30401. Mesh.prototype.getTotalIndices = function () {
  30402. if (!this._geometry) {
  30403. return 0;
  30404. }
  30405. return this._geometry.getTotalIndices();
  30406. };
  30407. /**
  30408. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  30409. * 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.
  30410. * Returns an empty array if the mesh has no geometry.
  30411. */
  30412. Mesh.prototype.getIndices = function (copyWhenShared) {
  30413. if (!this._geometry) {
  30414. return [];
  30415. }
  30416. return this._geometry.getIndices(copyWhenShared);
  30417. };
  30418. Object.defineProperty(Mesh.prototype, "isBlocked", {
  30419. get: function () {
  30420. return this._masterMesh !== null && this._masterMesh !== undefined;
  30421. },
  30422. enumerable: true,
  30423. configurable: true
  30424. });
  30425. /**
  30426. * Determine if the current mesh is ready to be rendered
  30427. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  30428. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  30429. * @returns true if all associated assets are ready (material, textures, shaders)
  30430. */
  30431. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  30432. if (completeCheck === void 0) { completeCheck = false; }
  30433. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  30434. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30435. return false;
  30436. }
  30437. if (!_super.prototype.isReady.call(this, completeCheck)) {
  30438. return false;
  30439. }
  30440. if (!this.subMeshes || this.subMeshes.length === 0) {
  30441. return true;
  30442. }
  30443. if (!completeCheck) {
  30444. return true;
  30445. }
  30446. var engine = this.getEngine();
  30447. var scene = this.getScene();
  30448. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  30449. this.computeWorldMatrix();
  30450. var mat = this.material || scene.defaultMaterial;
  30451. if (mat) {
  30452. if (mat.storeEffectOnSubMeshes) {
  30453. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30454. var subMesh = _a[_i];
  30455. var effectiveMaterial = subMesh.getMaterial();
  30456. if (effectiveMaterial) {
  30457. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  30458. return false;
  30459. }
  30460. }
  30461. }
  30462. }
  30463. else {
  30464. if (!mat.isReady(this, hardwareInstancedRendering)) {
  30465. return false;
  30466. }
  30467. }
  30468. }
  30469. // Shadows
  30470. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  30471. var light = _c[_b];
  30472. var generator = light.getShadowGenerator();
  30473. if (generator) {
  30474. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  30475. var subMesh = _e[_d];
  30476. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  30477. return false;
  30478. }
  30479. }
  30480. }
  30481. }
  30482. // LOD
  30483. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  30484. var lod = _g[_f];
  30485. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  30486. return false;
  30487. }
  30488. }
  30489. return true;
  30490. };
  30491. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  30492. /**
  30493. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  30494. * This property is pertinent only for updatable parametric shapes.
  30495. */
  30496. get: function () {
  30497. return this._areNormalsFrozen;
  30498. },
  30499. enumerable: true,
  30500. configurable: true
  30501. });
  30502. /**
  30503. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30504. * It has no effect at all on other shapes.
  30505. * It prevents the mesh normals from being recomputed on next `positions` array update.
  30506. * Returns the Mesh.
  30507. */
  30508. Mesh.prototype.freezeNormals = function () {
  30509. this._areNormalsFrozen = true;
  30510. return this;
  30511. };
  30512. /**
  30513. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30514. * It has no effect at all on other shapes.
  30515. * It reactivates the mesh normals computation if it was previously frozen.
  30516. * Returns the Mesh.
  30517. */
  30518. Mesh.prototype.unfreezeNormals = function () {
  30519. this._areNormalsFrozen = false;
  30520. return this;
  30521. };
  30522. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  30523. /**
  30524. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  30525. */
  30526. set: function (count) {
  30527. this._overridenInstanceCount = count;
  30528. },
  30529. enumerable: true,
  30530. configurable: true
  30531. });
  30532. // Methods
  30533. Mesh.prototype._preActivate = function () {
  30534. var sceneRenderId = this.getScene().getRenderId();
  30535. if (this._preActivateId === sceneRenderId) {
  30536. return this;
  30537. }
  30538. this._preActivateId = sceneRenderId;
  30539. this._visibleInstances = null;
  30540. return this;
  30541. };
  30542. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  30543. if (this._visibleInstances) {
  30544. this._visibleInstances.intermediateDefaultRenderId = renderId;
  30545. }
  30546. return this;
  30547. };
  30548. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  30549. if (!this._visibleInstances) {
  30550. this._visibleInstances = {};
  30551. this._visibleInstances.defaultRenderId = renderId;
  30552. this._visibleInstances.selfDefaultRenderId = this._renderId;
  30553. }
  30554. if (!this._visibleInstances[renderId]) {
  30555. this._visibleInstances[renderId] = new Array();
  30556. }
  30557. this._visibleInstances[renderId].push(instance);
  30558. return this;
  30559. };
  30560. /**
  30561. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  30562. * This means the mesh underlying bounding box and sphere are recomputed.
  30563. * Returns the Mesh.
  30564. */
  30565. Mesh.prototype.refreshBoundingInfo = function () {
  30566. return this._refreshBoundingInfo(false);
  30567. };
  30568. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  30569. if (this._boundingInfo && this._boundingInfo.isLocked) {
  30570. return this;
  30571. }
  30572. var data = this._getPositionData(applySkeleton);
  30573. if (data) {
  30574. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  30575. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30576. }
  30577. if (this.subMeshes) {
  30578. for (var index = 0; index < this.subMeshes.length; index++) {
  30579. this.subMeshes[index].refreshBoundingInfo();
  30580. }
  30581. }
  30582. this._updateBoundingInfo();
  30583. return this;
  30584. };
  30585. Mesh.prototype._getPositionData = function (applySkeleton) {
  30586. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30587. if (data && applySkeleton && this.skeleton) {
  30588. data = BABYLON.Tools.Slice(data);
  30589. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30590. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30591. if (matricesWeightsData && matricesIndicesData) {
  30592. var needExtras = this.numBoneInfluencers > 4;
  30593. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30594. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30595. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  30596. var tempVector = BABYLON.Tmp.Vector3[0];
  30597. var finalMatrix = BABYLON.Tmp.Matrix[0];
  30598. var tempMatrix = BABYLON.Tmp.Matrix[1];
  30599. var matWeightIdx = 0;
  30600. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  30601. finalMatrix.reset();
  30602. var inf;
  30603. var weight;
  30604. for (inf = 0; inf < 4; inf++) {
  30605. weight = matricesWeightsData[matWeightIdx + inf];
  30606. if (weight <= 0)
  30607. break;
  30608. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30609. finalMatrix.addToSelf(tempMatrix);
  30610. }
  30611. if (needExtras) {
  30612. for (inf = 0; inf < 4; inf++) {
  30613. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30614. if (weight <= 0)
  30615. break;
  30616. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30617. finalMatrix.addToSelf(tempMatrix);
  30618. }
  30619. }
  30620. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  30621. tempVector.toArray(data, index);
  30622. }
  30623. }
  30624. }
  30625. return data;
  30626. };
  30627. Mesh.prototype._createGlobalSubMesh = function (force) {
  30628. var totalVertices = this.getTotalVertices();
  30629. if (!totalVertices || !this.getIndices()) {
  30630. return null;
  30631. }
  30632. // Check if we need to recreate the submeshes
  30633. if (this.subMeshes && this.subMeshes.length > 0) {
  30634. var ib = this.getIndices();
  30635. if (!ib) {
  30636. return null;
  30637. }
  30638. var totalIndices = ib.length;
  30639. var needToRecreate = false;
  30640. if (force) {
  30641. needToRecreate = true;
  30642. }
  30643. else {
  30644. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30645. var submesh = _a[_i];
  30646. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  30647. needToRecreate = true;
  30648. break;
  30649. }
  30650. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  30651. needToRecreate = true;
  30652. break;
  30653. }
  30654. }
  30655. }
  30656. if (!needToRecreate) {
  30657. return this.subMeshes[0];
  30658. }
  30659. }
  30660. this.releaseSubMeshes();
  30661. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  30662. };
  30663. Mesh.prototype.subdivide = function (count) {
  30664. if (count < 1) {
  30665. return;
  30666. }
  30667. var totalIndices = this.getTotalIndices();
  30668. var subdivisionSize = (totalIndices / count) | 0;
  30669. var offset = 0;
  30670. // Ensure that subdivisionSize is a multiple of 3
  30671. while (subdivisionSize % 3 !== 0) {
  30672. subdivisionSize++;
  30673. }
  30674. this.releaseSubMeshes();
  30675. for (var index = 0; index < count; index++) {
  30676. if (offset >= totalIndices) {
  30677. break;
  30678. }
  30679. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  30680. offset += subdivisionSize;
  30681. }
  30682. this.synchronizeInstances();
  30683. };
  30684. /**
  30685. * Sets the vertex data of the mesh geometry for the requested `kind`.
  30686. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  30687. * The `data` are either a numeric array either a Float32Array.
  30688. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  30689. * 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).
  30690. * Note that a new underlying VertexBuffer object is created each call.
  30691. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  30692. *
  30693. * Possible `kind` values :
  30694. * - BABYLON.VertexBuffer.PositionKind
  30695. * - BABYLON.VertexBuffer.UVKind
  30696. * - BABYLON.VertexBuffer.UV2Kind
  30697. * - BABYLON.VertexBuffer.UV3Kind
  30698. * - BABYLON.VertexBuffer.UV4Kind
  30699. * - BABYLON.VertexBuffer.UV5Kind
  30700. * - BABYLON.VertexBuffer.UV6Kind
  30701. * - BABYLON.VertexBuffer.ColorKind
  30702. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30703. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30704. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30705. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30706. *
  30707. * Returns the Mesh.
  30708. */
  30709. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30710. if (updatable === void 0) { updatable = false; }
  30711. if (!this._geometry) {
  30712. var vertexData = new BABYLON.VertexData();
  30713. vertexData.set(data, kind);
  30714. var scene = this.getScene();
  30715. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  30716. }
  30717. else {
  30718. this._geometry.setVerticesData(kind, data, updatable, stride);
  30719. }
  30720. return this;
  30721. };
  30722. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  30723. if (updatable === void 0) { updatable = true; }
  30724. var vb = this.getVertexBuffer(kind);
  30725. if (!vb || vb.isUpdatable() === updatable) {
  30726. return;
  30727. }
  30728. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  30729. };
  30730. /**
  30731. * Sets the mesh VertexBuffer.
  30732. * Returns the Mesh.
  30733. */
  30734. Mesh.prototype.setVerticesBuffer = function (buffer) {
  30735. if (!this._geometry) {
  30736. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  30737. }
  30738. this._geometry.setVerticesBuffer(buffer);
  30739. return this;
  30740. };
  30741. /**
  30742. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  30743. * If the mesh has no geometry, it is simply returned as it is.
  30744. * The `data` are either a numeric array either a Float32Array.
  30745. * No new underlying VertexBuffer object is created.
  30746. * 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.
  30747. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  30748. *
  30749. * Possible `kind` values :
  30750. * - BABYLON.VertexBuffer.PositionKind
  30751. * - BABYLON.VertexBuffer.UVKind
  30752. * - BABYLON.VertexBuffer.UV2Kind
  30753. * - BABYLON.VertexBuffer.UV3Kind
  30754. * - BABYLON.VertexBuffer.UV4Kind
  30755. * - BABYLON.VertexBuffer.UV5Kind
  30756. * - BABYLON.VertexBuffer.UV6Kind
  30757. * - BABYLON.VertexBuffer.ColorKind
  30758. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30759. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30760. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30761. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30762. *
  30763. * Returns the Mesh.
  30764. */
  30765. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  30766. if (!this._geometry) {
  30767. return this;
  30768. }
  30769. if (!makeItUnique) {
  30770. this._geometry.updateVerticesData(kind, data, updateExtends);
  30771. }
  30772. else {
  30773. this.makeGeometryUnique();
  30774. this.updateVerticesData(kind, data, updateExtends, false);
  30775. }
  30776. return this;
  30777. };
  30778. /**
  30779. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  30780. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  30781. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  30782. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  30783. * Returns the Mesh.
  30784. */
  30785. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  30786. if (computeNormals === void 0) { computeNormals = true; }
  30787. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30788. if (!positions) {
  30789. return this;
  30790. }
  30791. positionFunction(positions);
  30792. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  30793. if (computeNormals) {
  30794. var indices = this.getIndices();
  30795. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30796. if (!normals) {
  30797. return this;
  30798. }
  30799. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  30800. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  30801. }
  30802. return this;
  30803. };
  30804. /**
  30805. * Creates a un-shared specific occurence of the geometry for the mesh.
  30806. * Returns the Mesh.
  30807. */
  30808. Mesh.prototype.makeGeometryUnique = function () {
  30809. if (!this._geometry) {
  30810. return this;
  30811. }
  30812. var oldGeometry = this._geometry;
  30813. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  30814. oldGeometry.releaseForMesh(this, true);
  30815. geometry.applyToMesh(this);
  30816. return this;
  30817. };
  30818. /**
  30819. * Sets the mesh indices.
  30820. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  30821. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  30822. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  30823. * This method creates a new index buffer each call.
  30824. * Returns the Mesh.
  30825. */
  30826. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  30827. if (totalVertices === void 0) { totalVertices = null; }
  30828. if (updatable === void 0) { updatable = false; }
  30829. if (!this._geometry) {
  30830. var vertexData = new BABYLON.VertexData();
  30831. vertexData.indices = indices;
  30832. var scene = this.getScene();
  30833. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  30834. }
  30835. else {
  30836. this._geometry.setIndices(indices, totalVertices, updatable);
  30837. }
  30838. return this;
  30839. };
  30840. /**
  30841. * Update the current index buffer
  30842. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  30843. * Returns the Mesh.
  30844. */
  30845. Mesh.prototype.updateIndices = function (indices, offset) {
  30846. if (!this._geometry) {
  30847. return this;
  30848. }
  30849. this._geometry.updateIndices(indices, offset);
  30850. return this;
  30851. };
  30852. /**
  30853. * Invert the geometry to move from a right handed system to a left handed one.
  30854. * Returns the Mesh.
  30855. */
  30856. Mesh.prototype.toLeftHanded = function () {
  30857. if (!this._geometry) {
  30858. return this;
  30859. }
  30860. this._geometry.toLeftHanded();
  30861. return this;
  30862. };
  30863. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  30864. if (!this._geometry) {
  30865. return this;
  30866. }
  30867. var engine = this.getScene().getEngine();
  30868. // Wireframe
  30869. var indexToBind;
  30870. if (this._unIndexed) {
  30871. indexToBind = null;
  30872. }
  30873. else {
  30874. switch (fillMode) {
  30875. case BABYLON.Material.PointFillMode:
  30876. indexToBind = null;
  30877. break;
  30878. case BABYLON.Material.WireFrameFillMode:
  30879. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  30880. break;
  30881. default:
  30882. case BABYLON.Material.TriangleFillMode:
  30883. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  30884. break;
  30885. }
  30886. }
  30887. // VBOs
  30888. this._geometry._bind(effect, indexToBind);
  30889. return this;
  30890. };
  30891. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  30892. if (alternate === void 0) { alternate = false; }
  30893. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  30894. return this;
  30895. }
  30896. this.onBeforeDrawObservable.notifyObservers(this);
  30897. var scene = this.getScene();
  30898. var engine = scene.getEngine();
  30899. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  30900. // or triangles as points
  30901. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  30902. }
  30903. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  30904. // Triangles as wireframe
  30905. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  30906. }
  30907. else {
  30908. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  30909. }
  30910. if (scene._isAlternateRenderingEnabled && !alternate) {
  30911. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  30912. if (!effect || !scene.activeCamera) {
  30913. return this;
  30914. }
  30915. scene._switchToAlternateCameraConfiguration(true);
  30916. this._effectiveMaterial.bindView(effect);
  30917. this._effectiveMaterial.bindViewProjection(effect);
  30918. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  30919. this._draw(subMesh, fillMode, instancesCount, true);
  30920. engine.setViewport(scene.activeCamera.viewport);
  30921. scene._switchToAlternateCameraConfiguration(false);
  30922. this._effectiveMaterial.bindView(effect);
  30923. this._effectiveMaterial.bindViewProjection(effect);
  30924. }
  30925. return this;
  30926. };
  30927. /**
  30928. * Registers for this mesh a javascript function called just before the rendering process.
  30929. * This function is passed the current mesh.
  30930. * Return the Mesh.
  30931. */
  30932. Mesh.prototype.registerBeforeRender = function (func) {
  30933. this.onBeforeRenderObservable.add(func);
  30934. return this;
  30935. };
  30936. /**
  30937. * Disposes a previously registered javascript function called before the rendering.
  30938. * This function is passed the current mesh.
  30939. * Returns the Mesh.
  30940. */
  30941. Mesh.prototype.unregisterBeforeRender = function (func) {
  30942. this.onBeforeRenderObservable.removeCallback(func);
  30943. return this;
  30944. };
  30945. /**
  30946. * Registers for this mesh a javascript function called just after the rendering is complete.
  30947. * This function is passed the current mesh.
  30948. * Returns the Mesh.
  30949. */
  30950. Mesh.prototype.registerAfterRender = function (func) {
  30951. this.onAfterRenderObservable.add(func);
  30952. return this;
  30953. };
  30954. /**
  30955. * Disposes a previously registered javascript function called after the rendering.
  30956. * This function is passed the current mesh.
  30957. * Return the Mesh.
  30958. */
  30959. Mesh.prototype.unregisterAfterRender = function (func) {
  30960. this.onAfterRenderObservable.removeCallback(func);
  30961. return this;
  30962. };
  30963. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  30964. var scene = this.getScene();
  30965. this._batchCache.mustReturn = false;
  30966. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  30967. this._batchCache.visibleInstances[subMeshId] = null;
  30968. if (this._visibleInstances) {
  30969. var currentRenderId = scene.getRenderId();
  30970. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  30971. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  30972. var selfRenderId = this._renderId;
  30973. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  30974. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  30975. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  30976. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  30977. }
  30978. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  30979. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  30980. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  30981. this._batchCache.mustReturn = true;
  30982. return this._batchCache;
  30983. }
  30984. if (currentRenderId !== selfRenderId) {
  30985. this._batchCache.renderSelf[subMeshId] = false;
  30986. }
  30987. }
  30988. this._renderIdForInstances[subMeshId] = currentRenderId;
  30989. }
  30990. return this._batchCache;
  30991. };
  30992. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  30993. var visibleInstances = batch.visibleInstances[subMesh._id];
  30994. if (!visibleInstances) {
  30995. return this;
  30996. }
  30997. var matricesCount = visibleInstances.length + 1;
  30998. var bufferSize = matricesCount * 16 * 4;
  30999. var currentInstancesBufferSize = this._instancesBufferSize;
  31000. var instancesBuffer = this._instancesBuffer;
  31001. while (this._instancesBufferSize < bufferSize) {
  31002. this._instancesBufferSize *= 2;
  31003. }
  31004. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31005. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31006. }
  31007. var offset = 0;
  31008. var instancesCount = 0;
  31009. var world = this.getWorldMatrix();
  31010. if (batch.renderSelf[subMesh._id]) {
  31011. world.copyToArray(this._instancesData, offset);
  31012. offset += 16;
  31013. instancesCount++;
  31014. }
  31015. if (visibleInstances) {
  31016. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31017. var instance = visibleInstances[instanceIndex];
  31018. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31019. offset += 16;
  31020. instancesCount++;
  31021. }
  31022. }
  31023. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31024. if (instancesBuffer) {
  31025. instancesBuffer.dispose();
  31026. }
  31027. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31028. this._instancesBuffer = instancesBuffer;
  31029. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31030. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31031. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31032. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31033. }
  31034. else {
  31035. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31036. }
  31037. this._bind(subMesh, effect, fillMode);
  31038. this._draw(subMesh, fillMode, instancesCount);
  31039. engine.unbindInstanceAttributes();
  31040. return this;
  31041. };
  31042. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31043. var scene = this.getScene();
  31044. var engine = scene.getEngine();
  31045. if (hardwareInstancedRendering) {
  31046. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31047. }
  31048. else {
  31049. if (batch.renderSelf[subMesh._id]) {
  31050. // Draw
  31051. if (onBeforeDraw) {
  31052. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31053. }
  31054. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31055. }
  31056. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31057. if (visibleInstancesForSubMesh) {
  31058. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31059. var instance = visibleInstancesForSubMesh[instanceIndex];
  31060. // World
  31061. var world = instance.getWorldMatrix();
  31062. if (onBeforeDraw) {
  31063. onBeforeDraw(true, world, effectiveMaterial);
  31064. }
  31065. // Draw
  31066. this._draw(subMesh, fillMode);
  31067. }
  31068. }
  31069. }
  31070. return this;
  31071. };
  31072. /**
  31073. * Triggers the draw call for the mesh.
  31074. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31075. * Returns the Mesh.
  31076. */
  31077. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31078. this.checkOcclusionQuery();
  31079. if (this._isOccluded) {
  31080. return this;
  31081. }
  31082. var scene = this.getScene();
  31083. // Managing instances
  31084. var batch = this._getInstancesRenderList(subMesh._id);
  31085. if (batch.mustReturn) {
  31086. return this;
  31087. }
  31088. // Checking geometry state
  31089. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31090. return this;
  31091. }
  31092. this.onBeforeRenderObservable.notifyObservers(this);
  31093. var engine = scene.getEngine();
  31094. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31095. // Material
  31096. var material = subMesh.getMaterial();
  31097. if (!material) {
  31098. return this;
  31099. }
  31100. this._effectiveMaterial = material;
  31101. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31102. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31103. return this;
  31104. }
  31105. }
  31106. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31107. return this;
  31108. }
  31109. // Alpha mode
  31110. if (enableAlphaMode) {
  31111. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31112. }
  31113. // Outline - step 1
  31114. var savedDepthWrite = engine.getDepthWrite();
  31115. if (this.renderOutline) {
  31116. engine.setDepthWrite(false);
  31117. scene.getOutlineRenderer().render(subMesh, batch);
  31118. engine.setDepthWrite(savedDepthWrite);
  31119. }
  31120. var effect;
  31121. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31122. effect = subMesh.effect;
  31123. }
  31124. else {
  31125. effect = this._effectiveMaterial.getEffect();
  31126. }
  31127. if (!effect) {
  31128. return this;
  31129. }
  31130. var sideOrientation = this.overrideMaterialSideOrientation;
  31131. if (sideOrientation == null) {
  31132. sideOrientation = this._effectiveMaterial.sideOrientation;
  31133. if (this._getWorldMatrixDeterminant() < 0) {
  31134. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31135. }
  31136. }
  31137. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31138. if (this._effectiveMaterial.forceDepthWrite) {
  31139. engine.setDepthWrite(true);
  31140. }
  31141. // Bind
  31142. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31143. if (!hardwareInstancedRendering) {
  31144. this._bind(subMesh, effect, fillMode);
  31145. }
  31146. var world = this.getWorldMatrix();
  31147. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31148. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31149. }
  31150. else {
  31151. this._effectiveMaterial.bind(world, this);
  31152. }
  31153. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31154. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31155. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31156. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31157. }
  31158. // Draw
  31159. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31160. // Unbind
  31161. this._effectiveMaterial.unbind();
  31162. // Outline - step 2
  31163. if (this.renderOutline && savedDepthWrite) {
  31164. engine.setDepthWrite(true);
  31165. engine.setColorWrite(false);
  31166. scene.getOutlineRenderer().render(subMesh, batch);
  31167. engine.setColorWrite(true);
  31168. }
  31169. // Overlay
  31170. if (this.renderOverlay) {
  31171. var currentMode = engine.getAlphaMode();
  31172. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31173. scene.getOutlineRenderer().render(subMesh, batch, true);
  31174. engine.setAlphaMode(currentMode);
  31175. }
  31176. this.onAfterRenderObservable.notifyObservers(this);
  31177. return this;
  31178. };
  31179. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31180. if (isInstance && effectiveMaterial) {
  31181. effectiveMaterial.bindOnlyWorldMatrix(world);
  31182. }
  31183. };
  31184. /**
  31185. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31186. */
  31187. Mesh.prototype.getEmittedParticleSystems = function () {
  31188. var results = new Array();
  31189. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31190. var particleSystem = this.getScene().particleSystems[index];
  31191. if (particleSystem.emitter === this) {
  31192. results.push(particleSystem);
  31193. }
  31194. }
  31195. return results;
  31196. };
  31197. /**
  31198. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31199. */
  31200. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31201. var results = new Array();
  31202. var descendants = this.getDescendants();
  31203. descendants.push(this);
  31204. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31205. var particleSystem = this.getScene().particleSystems[index];
  31206. var emitter = particleSystem.emitter;
  31207. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31208. results.push(particleSystem);
  31209. }
  31210. }
  31211. return results;
  31212. };
  31213. Mesh.prototype._checkDelayState = function () {
  31214. var scene = this.getScene();
  31215. if (this._geometry) {
  31216. this._geometry.load(scene);
  31217. }
  31218. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31219. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31220. this._queueLoad(scene);
  31221. }
  31222. return this;
  31223. };
  31224. Mesh.prototype._queueLoad = function (scene) {
  31225. var _this = this;
  31226. scene._addPendingData(this);
  31227. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31228. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31229. if (data instanceof ArrayBuffer) {
  31230. _this._delayLoadingFunction(data, _this);
  31231. }
  31232. else {
  31233. _this._delayLoadingFunction(JSON.parse(data), _this);
  31234. }
  31235. _this.instances.forEach(function (instance) {
  31236. instance._syncSubMeshes();
  31237. });
  31238. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31239. scene._removePendingData(_this);
  31240. }, function () { }, scene.database, getBinaryData);
  31241. return this;
  31242. };
  31243. /**
  31244. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31245. */
  31246. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31247. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31248. return false;
  31249. }
  31250. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31251. return false;
  31252. }
  31253. this._checkDelayState();
  31254. return true;
  31255. };
  31256. /**
  31257. * Sets the mesh material by the material or multiMaterial `id` property.
  31258. * The material `id` is a string identifying the material or the multiMaterial.
  31259. * This method returns the Mesh.
  31260. */
  31261. Mesh.prototype.setMaterialByID = function (id) {
  31262. var materials = this.getScene().materials;
  31263. var index;
  31264. for (index = materials.length - 1; index > -1; index--) {
  31265. if (materials[index].id === id) {
  31266. this.material = materials[index];
  31267. return this;
  31268. }
  31269. }
  31270. // Multi
  31271. var multiMaterials = this.getScene().multiMaterials;
  31272. for (index = multiMaterials.length - 1; index > -1; index--) {
  31273. if (multiMaterials[index].id === id) {
  31274. this.material = multiMaterials[index];
  31275. return this;
  31276. }
  31277. }
  31278. return this;
  31279. };
  31280. /**
  31281. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31282. */
  31283. Mesh.prototype.getAnimatables = function () {
  31284. var results = new Array();
  31285. if (this.material) {
  31286. results.push(this.material);
  31287. }
  31288. if (this.skeleton) {
  31289. results.push(this.skeleton);
  31290. }
  31291. return results;
  31292. };
  31293. /**
  31294. * Modifies the mesh geometry according to the passed transformation matrix.
  31295. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31296. * The mesh normals are modified accordingly the same transformation.
  31297. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31298. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31299. * Returns the Mesh.
  31300. */
  31301. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31302. // Position
  31303. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31304. return this;
  31305. }
  31306. var submeshes = this.subMeshes.splice(0);
  31307. this._resetPointsArrayCache();
  31308. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31309. var temp = new Array();
  31310. var index;
  31311. for (index = 0; index < data.length; index += 3) {
  31312. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31313. }
  31314. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31315. // Normals
  31316. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31317. return this;
  31318. }
  31319. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31320. temp = [];
  31321. for (index = 0; index < data.length; index += 3) {
  31322. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31323. }
  31324. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31325. // flip faces?
  31326. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31327. this.flipFaces();
  31328. }
  31329. // Restore submeshes
  31330. this.releaseSubMeshes();
  31331. this.subMeshes = submeshes;
  31332. return this;
  31333. };
  31334. /**
  31335. * Modifies the mesh geometry according to its own current World Matrix.
  31336. * The mesh World Matrix is then reset.
  31337. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31338. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31339. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31340. * Returns the Mesh.
  31341. */
  31342. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31343. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31344. this.scaling.copyFromFloats(1, 1, 1);
  31345. this.position.copyFromFloats(0, 0, 0);
  31346. this.rotation.copyFromFloats(0, 0, 0);
  31347. //only if quaternion is already set
  31348. if (this.rotationQuaternion) {
  31349. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31350. }
  31351. this._worldMatrix = BABYLON.Matrix.Identity();
  31352. return this;
  31353. };
  31354. Object.defineProperty(Mesh.prototype, "_positions", {
  31355. // Cache
  31356. get: function () {
  31357. if (this._geometry) {
  31358. return this._geometry._positions;
  31359. }
  31360. return null;
  31361. },
  31362. enumerable: true,
  31363. configurable: true
  31364. });
  31365. Mesh.prototype._resetPointsArrayCache = function () {
  31366. if (this._geometry) {
  31367. this._geometry._resetPointsArrayCache();
  31368. }
  31369. return this;
  31370. };
  31371. Mesh.prototype._generatePointsArray = function () {
  31372. if (this._geometry) {
  31373. return this._geometry._generatePointsArray();
  31374. }
  31375. return false;
  31376. };
  31377. /**
  31378. * Returns a new Mesh object generated from the current mesh properties.
  31379. * This method must not get confused with createInstance().
  31380. * The parameter `name` is a string, the name given to the new mesh.
  31381. * The optional parameter `newParent` can be any Node object (default `null`).
  31382. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  31383. * 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.
  31384. */
  31385. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  31386. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31387. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  31388. };
  31389. /**
  31390. * Releases resources associated with this mesh.
  31391. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  31392. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  31393. */
  31394. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  31395. var _this = this;
  31396. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  31397. this.morphTargetManager = null;
  31398. if (this._geometry) {
  31399. this._geometry.releaseForMesh(this, true);
  31400. }
  31401. // Sources
  31402. var meshes = this.getScene().meshes;
  31403. meshes.forEach(function (abstractMesh) {
  31404. var mesh = abstractMesh;
  31405. if (mesh._source && mesh._source === _this) {
  31406. mesh._source = null;
  31407. }
  31408. });
  31409. this._source = null;
  31410. // Instances
  31411. if (this._instancesBuffer) {
  31412. this._instancesBuffer.dispose();
  31413. this._instancesBuffer = null;
  31414. }
  31415. while (this.instances.length) {
  31416. this.instances[0].dispose();
  31417. }
  31418. // Effect layers.
  31419. var effectLayers = this.getScene().effectLayers;
  31420. for (var i = 0; i < effectLayers.length; i++) {
  31421. var effectLayer = effectLayers[i];
  31422. if (effectLayer) {
  31423. effectLayer._disposeMesh(this);
  31424. }
  31425. }
  31426. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  31427. };
  31428. /**
  31429. * Modifies the mesh geometry according to a displacement map.
  31430. * 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.
  31431. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31432. * This method returns nothing.
  31433. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  31434. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31435. * 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.
  31436. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31437. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31438. *
  31439. * Returns the Mesh.
  31440. */
  31441. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  31442. var _this = this;
  31443. var scene = this.getScene();
  31444. var onload = function (img) {
  31445. // Getting height map data
  31446. var canvas = document.createElement("canvas");
  31447. var context = canvas.getContext("2d");
  31448. var heightMapWidth = img.width;
  31449. var heightMapHeight = img.height;
  31450. canvas.width = heightMapWidth;
  31451. canvas.height = heightMapHeight;
  31452. context.drawImage(img, 0, 0);
  31453. // Create VertexData from map data
  31454. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  31455. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  31456. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  31457. //execute success callback, if set
  31458. if (onSuccess) {
  31459. onSuccess(_this);
  31460. }
  31461. };
  31462. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  31463. return this;
  31464. };
  31465. /**
  31466. * Modifies the mesh geometry according to a displacementMap buffer.
  31467. * 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.
  31468. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31469. * This method returns nothing.
  31470. * 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.
  31471. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  31472. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31473. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31474. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31475. *
  31476. * Returns the Mesh.
  31477. */
  31478. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  31479. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  31480. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  31481. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31482. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  31483. return this;
  31484. }
  31485. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31486. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31487. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31488. var position = BABYLON.Vector3.Zero();
  31489. var normal = BABYLON.Vector3.Zero();
  31490. var uv = BABYLON.Vector2.Zero();
  31491. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  31492. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  31493. for (var index = 0; index < positions.length; index += 3) {
  31494. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  31495. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  31496. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  31497. // Compute height
  31498. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  31499. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  31500. var pos = (u + v * heightMapWidth) * 4;
  31501. var r = buffer[pos] / 255.0;
  31502. var g = buffer[pos + 1] / 255.0;
  31503. var b = buffer[pos + 2] / 255.0;
  31504. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31505. normal.normalize();
  31506. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  31507. position = position.add(normal);
  31508. position.toArray(positions, index);
  31509. }
  31510. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  31511. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  31512. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31513. return this;
  31514. };
  31515. /**
  31516. * Modify the mesh to get a flat shading rendering.
  31517. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  31518. * This method returns the Mesh.
  31519. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  31520. */
  31521. Mesh.prototype.convertToFlatShadedMesh = function () {
  31522. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  31523. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31524. var kinds = this.getVerticesDataKinds();
  31525. var vbs = {};
  31526. var data = {};
  31527. var newdata = {};
  31528. var updatableNormals = false;
  31529. var kindIndex;
  31530. var kind;
  31531. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31532. kind = kinds[kindIndex];
  31533. var vertexBuffer = this.getVertexBuffer(kind);
  31534. if (kind === BABYLON.VertexBuffer.NormalKind) {
  31535. updatableNormals = vertexBuffer.isUpdatable();
  31536. kinds.splice(kindIndex, 1);
  31537. kindIndex--;
  31538. continue;
  31539. }
  31540. vbs[kind] = vertexBuffer;
  31541. data[kind] = vbs[kind].getData();
  31542. newdata[kind] = [];
  31543. }
  31544. // Save previous submeshes
  31545. var previousSubmeshes = this.subMeshes.slice(0);
  31546. var indices = this.getIndices();
  31547. var totalIndices = this.getTotalIndices();
  31548. // Generating unique vertices per face
  31549. var index;
  31550. for (index = 0; index < totalIndices; index++) {
  31551. var vertexIndex = indices[index];
  31552. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31553. kind = kinds[kindIndex];
  31554. var stride = vbs[kind].getStrideSize();
  31555. for (var offset = 0; offset < stride; offset++) {
  31556. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31557. }
  31558. }
  31559. }
  31560. // Updating faces & normal
  31561. var normals = [];
  31562. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  31563. for (index = 0; index < totalIndices; index += 3) {
  31564. indices[index] = index;
  31565. indices[index + 1] = index + 1;
  31566. indices[index + 2] = index + 2;
  31567. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  31568. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  31569. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  31570. var p1p2 = p1.subtract(p2);
  31571. var p3p2 = p3.subtract(p2);
  31572. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  31573. // Store same normals for every vertex
  31574. for (var localIndex = 0; localIndex < 3; localIndex++) {
  31575. normals.push(normal.x);
  31576. normals.push(normal.y);
  31577. normals.push(normal.z);
  31578. }
  31579. }
  31580. this.setIndices(indices);
  31581. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  31582. // Updating vertex buffers
  31583. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31584. kind = kinds[kindIndex];
  31585. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31586. }
  31587. // Updating submeshes
  31588. this.releaseSubMeshes();
  31589. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31590. var previousOne = previousSubmeshes[submeshIndex];
  31591. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31592. }
  31593. this.synchronizeInstances();
  31594. return this;
  31595. };
  31596. /**
  31597. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  31598. * In other words, more vertices, no more indices and a single bigger VBO.
  31599. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  31600. * Returns the Mesh.
  31601. */
  31602. Mesh.prototype.convertToUnIndexedMesh = function () {
  31603. /// <summary>Remove indices by unfolding faces into buffers</summary>
  31604. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31605. var kinds = this.getVerticesDataKinds();
  31606. var vbs = {};
  31607. var data = {};
  31608. var newdata = {};
  31609. var kindIndex;
  31610. var kind;
  31611. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31612. kind = kinds[kindIndex];
  31613. var vertexBuffer = this.getVertexBuffer(kind);
  31614. vbs[kind] = vertexBuffer;
  31615. data[kind] = vbs[kind].getData();
  31616. newdata[kind] = [];
  31617. }
  31618. // Save previous submeshes
  31619. var previousSubmeshes = this.subMeshes.slice(0);
  31620. var indices = this.getIndices();
  31621. var totalIndices = this.getTotalIndices();
  31622. // Generating unique vertices per face
  31623. var index;
  31624. for (index = 0; index < totalIndices; index++) {
  31625. var vertexIndex = indices[index];
  31626. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31627. kind = kinds[kindIndex];
  31628. var stride = vbs[kind].getStrideSize();
  31629. for (var offset = 0; offset < stride; offset++) {
  31630. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31631. }
  31632. }
  31633. }
  31634. // Updating indices
  31635. for (index = 0; index < totalIndices; index += 3) {
  31636. indices[index] = index;
  31637. indices[index + 1] = index + 1;
  31638. indices[index + 2] = index + 2;
  31639. }
  31640. this.setIndices(indices);
  31641. // Updating vertex buffers
  31642. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31643. kind = kinds[kindIndex];
  31644. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31645. }
  31646. // Updating submeshes
  31647. this.releaseSubMeshes();
  31648. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31649. var previousOne = previousSubmeshes[submeshIndex];
  31650. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31651. }
  31652. this._unIndexed = true;
  31653. this.synchronizeInstances();
  31654. return this;
  31655. };
  31656. /**
  31657. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  31658. * This method returns the Mesh.
  31659. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  31660. */
  31661. Mesh.prototype.flipFaces = function (flipNormals) {
  31662. if (flipNormals === void 0) { flipNormals = false; }
  31663. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  31664. var i;
  31665. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  31666. for (i = 0; i < vertex_data.normals.length; i++) {
  31667. vertex_data.normals[i] *= -1;
  31668. }
  31669. }
  31670. if (vertex_data.indices) {
  31671. var temp;
  31672. for (i = 0; i < vertex_data.indices.length; i += 3) {
  31673. // reassign indices
  31674. temp = vertex_data.indices[i + 1];
  31675. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  31676. vertex_data.indices[i + 2] = temp;
  31677. }
  31678. }
  31679. vertex_data.applyToMesh(this);
  31680. return this;
  31681. };
  31682. // Instances
  31683. /**
  31684. * Creates a new InstancedMesh object from the mesh model.
  31685. * An instance shares the same properties and the same material than its model.
  31686. * Only these properties of each instance can then be set individually :
  31687. * - position
  31688. * - rotation
  31689. * - rotationQuaternion
  31690. * - setPivotMatrix
  31691. * - scaling
  31692. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  31693. * Warning : this method is not supported for Line mesh and LineSystem
  31694. */
  31695. Mesh.prototype.createInstance = function (name) {
  31696. return new BABYLON.InstancedMesh(name, this);
  31697. };
  31698. /**
  31699. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  31700. * After this call, all the mesh instances have the same submeshes than the current mesh.
  31701. * This method returns the Mesh.
  31702. */
  31703. Mesh.prototype.synchronizeInstances = function () {
  31704. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  31705. var instance = this.instances[instanceIndex];
  31706. instance._syncSubMeshes();
  31707. }
  31708. return this;
  31709. };
  31710. /**
  31711. * Simplify the mesh according to the given array of settings.
  31712. * Function will return immediately and will simplify async. It returns the Mesh.
  31713. * @param settings a collection of simplification settings.
  31714. * @param parallelProcessing should all levels calculate parallel or one after the other.
  31715. * @param type the type of simplification to run.
  31716. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  31717. */
  31718. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  31719. if (parallelProcessing === void 0) { parallelProcessing = true; }
  31720. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  31721. this.getScene().simplificationQueue.addTask({
  31722. settings: settings,
  31723. parallelProcessing: parallelProcessing,
  31724. mesh: this,
  31725. simplificationType: simplificationType,
  31726. successCallback: successCallback
  31727. });
  31728. return this;
  31729. };
  31730. /**
  31731. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  31732. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  31733. * This should be used together with the simplification to avoid disappearing triangles.
  31734. * Returns the Mesh.
  31735. * @param successCallback an optional success callback to be called after the optimization finished.
  31736. */
  31737. Mesh.prototype.optimizeIndices = function (successCallback) {
  31738. var _this = this;
  31739. var indices = this.getIndices();
  31740. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31741. if (!positions || !indices) {
  31742. return this;
  31743. }
  31744. var vectorPositions = new Array();
  31745. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  31746. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  31747. }
  31748. var dupes = new Array();
  31749. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  31750. var realPos = vectorPositions.length - 1 - iteration;
  31751. var testedPosition = vectorPositions[realPos];
  31752. for (var j = 0; j < realPos; ++j) {
  31753. var againstPosition = vectorPositions[j];
  31754. if (testedPosition.equals(againstPosition)) {
  31755. dupes[realPos] = j;
  31756. break;
  31757. }
  31758. }
  31759. }, function () {
  31760. for (var i = 0; i < indices.length; ++i) {
  31761. indices[i] = dupes[indices[i]] || indices[i];
  31762. }
  31763. //indices are now reordered
  31764. var originalSubMeshes = _this.subMeshes.slice(0);
  31765. _this.setIndices(indices);
  31766. _this.subMeshes = originalSubMeshes;
  31767. if (successCallback) {
  31768. successCallback(_this);
  31769. }
  31770. });
  31771. return this;
  31772. };
  31773. Mesh.prototype.serialize = function (serializationObject) {
  31774. serializationObject.name = this.name;
  31775. serializationObject.id = this.id;
  31776. serializationObject.type = this.getClassName();
  31777. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31778. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31779. }
  31780. serializationObject.position = this.position.asArray();
  31781. if (this.rotationQuaternion) {
  31782. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  31783. }
  31784. else if (this.rotation) {
  31785. serializationObject.rotation = this.rotation.asArray();
  31786. }
  31787. serializationObject.scaling = this.scaling.asArray();
  31788. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  31789. serializationObject.isEnabled = this.isEnabled(false);
  31790. serializationObject.isVisible = this.isVisible;
  31791. serializationObject.infiniteDistance = this.infiniteDistance;
  31792. serializationObject.pickable = this.isPickable;
  31793. serializationObject.receiveShadows = this.receiveShadows;
  31794. serializationObject.billboardMode = this.billboardMode;
  31795. serializationObject.visibility = this.visibility;
  31796. serializationObject.checkCollisions = this.checkCollisions;
  31797. serializationObject.isBlocker = this.isBlocker;
  31798. // Parent
  31799. if (this.parent) {
  31800. serializationObject.parentId = this.parent.id;
  31801. }
  31802. // Geometry
  31803. serializationObject.isUnIndexed = this.isUnIndexed;
  31804. var geometry = this._geometry;
  31805. if (geometry) {
  31806. var geometryId = geometry.id;
  31807. serializationObject.geometryId = geometryId;
  31808. // SubMeshes
  31809. serializationObject.subMeshes = [];
  31810. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  31811. var subMesh = this.subMeshes[subIndex];
  31812. serializationObject.subMeshes.push({
  31813. materialIndex: subMesh.materialIndex,
  31814. verticesStart: subMesh.verticesStart,
  31815. verticesCount: subMesh.verticesCount,
  31816. indexStart: subMesh.indexStart,
  31817. indexCount: subMesh.indexCount
  31818. });
  31819. }
  31820. }
  31821. // Material
  31822. if (this.material) {
  31823. serializationObject.materialId = this.material.id;
  31824. }
  31825. else {
  31826. this.material = null;
  31827. }
  31828. // Morph targets
  31829. if (this.morphTargetManager) {
  31830. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  31831. }
  31832. // Skeleton
  31833. if (this.skeleton) {
  31834. serializationObject.skeletonId = this.skeleton.id;
  31835. }
  31836. // Physics
  31837. //TODO implement correct serialization for physics impostors.
  31838. var impostor = this.getPhysicsImpostor();
  31839. if (impostor) {
  31840. serializationObject.physicsMass = impostor.getParam("mass");
  31841. serializationObject.physicsFriction = impostor.getParam("friction");
  31842. serializationObject.physicsRestitution = impostor.getParam("mass");
  31843. serializationObject.physicsImpostor = impostor.type;
  31844. }
  31845. // Metadata
  31846. if (this.metadata) {
  31847. serializationObject.metadata = this.metadata;
  31848. }
  31849. // Instances
  31850. serializationObject.instances = [];
  31851. for (var index = 0; index < this.instances.length; index++) {
  31852. var instance = this.instances[index];
  31853. var serializationInstance = {
  31854. name: instance.name,
  31855. id: instance.id,
  31856. position: instance.position.asArray(),
  31857. scaling: instance.scaling.asArray()
  31858. };
  31859. if (instance.rotationQuaternion) {
  31860. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31861. }
  31862. else if (instance.rotation) {
  31863. serializationInstance.rotation = instance.rotation.asArray();
  31864. }
  31865. serializationObject.instances.push(serializationInstance);
  31866. // Animations
  31867. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31868. serializationInstance.ranges = instance.serializeAnimationRanges();
  31869. }
  31870. //
  31871. // Animations
  31872. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31873. serializationObject.ranges = this.serializeAnimationRanges();
  31874. // Layer mask
  31875. serializationObject.layerMask = this.layerMask;
  31876. // Alpha
  31877. serializationObject.alphaIndex = this.alphaIndex;
  31878. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  31879. // Overlay
  31880. serializationObject.overlayAlpha = this.overlayAlpha;
  31881. serializationObject.overlayColor = this.overlayColor.asArray();
  31882. serializationObject.renderOverlay = this.renderOverlay;
  31883. // Fog
  31884. serializationObject.applyFog = this.applyFog;
  31885. // Action Manager
  31886. if (this.actionManager) {
  31887. serializationObject.actions = this.actionManager.serialize(this.name);
  31888. }
  31889. };
  31890. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  31891. if (!this.geometry) {
  31892. return;
  31893. }
  31894. this._markSubMeshesAsAttributesDirty();
  31895. var morphTargetManager = this._morphTargetManager;
  31896. if (morphTargetManager && morphTargetManager.vertexCount) {
  31897. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  31898. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  31899. this.morphTargetManager = null;
  31900. return;
  31901. }
  31902. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  31903. var morphTarget = morphTargetManager.getActiveTarget(index);
  31904. var positions = morphTarget.getPositions();
  31905. if (!positions) {
  31906. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  31907. return;
  31908. }
  31909. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  31910. var normals = morphTarget.getNormals();
  31911. if (normals) {
  31912. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  31913. }
  31914. var tangents = morphTarget.getTangents();
  31915. if (tangents) {
  31916. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  31917. }
  31918. }
  31919. }
  31920. else {
  31921. var index = 0;
  31922. // Positions
  31923. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  31924. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  31925. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  31926. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  31927. }
  31928. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  31929. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  31930. }
  31931. index++;
  31932. }
  31933. }
  31934. };
  31935. // Statics
  31936. /**
  31937. * Returns a new Mesh object parsed from the source provided.
  31938. * The parameter `parsedMesh` is the source.
  31939. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  31940. */
  31941. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  31942. var mesh;
  31943. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  31944. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  31945. }
  31946. else {
  31947. mesh = new Mesh(parsedMesh.name, scene);
  31948. }
  31949. mesh.id = parsedMesh.id;
  31950. if (BABYLON.Tags) {
  31951. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  31952. }
  31953. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  31954. if (parsedMesh.metadata !== undefined) {
  31955. mesh.metadata = parsedMesh.metadata;
  31956. }
  31957. if (parsedMesh.rotationQuaternion) {
  31958. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  31959. }
  31960. else if (parsedMesh.rotation) {
  31961. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  31962. }
  31963. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  31964. if (parsedMesh.localMatrix) {
  31965. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  31966. }
  31967. else if (parsedMesh.pivotMatrix) {
  31968. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  31969. }
  31970. mesh.setEnabled(parsedMesh.isEnabled);
  31971. mesh.isVisible = parsedMesh.isVisible;
  31972. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  31973. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  31974. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  31975. if (parsedMesh.applyFog !== undefined) {
  31976. mesh.applyFog = parsedMesh.applyFog;
  31977. }
  31978. if (parsedMesh.pickable !== undefined) {
  31979. mesh.isPickable = parsedMesh.pickable;
  31980. }
  31981. if (parsedMesh.alphaIndex !== undefined) {
  31982. mesh.alphaIndex = parsedMesh.alphaIndex;
  31983. }
  31984. mesh.receiveShadows = parsedMesh.receiveShadows;
  31985. mesh.billboardMode = parsedMesh.billboardMode;
  31986. if (parsedMesh.visibility !== undefined) {
  31987. mesh.visibility = parsedMesh.visibility;
  31988. }
  31989. mesh.checkCollisions = parsedMesh.checkCollisions;
  31990. if (parsedMesh.isBlocker !== undefined) {
  31991. mesh.isBlocker = parsedMesh.isBlocker;
  31992. }
  31993. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  31994. // freezeWorldMatrix
  31995. if (parsedMesh.freezeWorldMatrix) {
  31996. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  31997. }
  31998. // Parent
  31999. if (parsedMesh.parentId) {
  32000. mesh._waitingParentId = parsedMesh.parentId;
  32001. }
  32002. // Actions
  32003. if (parsedMesh.actions !== undefined) {
  32004. mesh._waitingActions = parsedMesh.actions;
  32005. }
  32006. // Overlay
  32007. if (parsedMesh.overlayAlpha !== undefined) {
  32008. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32009. }
  32010. if (parsedMesh.overlayColor !== undefined) {
  32011. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32012. }
  32013. if (parsedMesh.renderOverlay !== undefined) {
  32014. mesh.renderOverlay = parsedMesh.renderOverlay;
  32015. }
  32016. // Geometry
  32017. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32018. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32019. if (parsedMesh.delayLoadingFile) {
  32020. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32021. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32022. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32023. if (parsedMesh._binaryInfo) {
  32024. mesh._binaryInfo = parsedMesh._binaryInfo;
  32025. }
  32026. mesh._delayInfo = [];
  32027. if (parsedMesh.hasUVs) {
  32028. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32029. }
  32030. if (parsedMesh.hasUVs2) {
  32031. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32032. }
  32033. if (parsedMesh.hasUVs3) {
  32034. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32035. }
  32036. if (parsedMesh.hasUVs4) {
  32037. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32038. }
  32039. if (parsedMesh.hasUVs5) {
  32040. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32041. }
  32042. if (parsedMesh.hasUVs6) {
  32043. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32044. }
  32045. if (parsedMesh.hasColors) {
  32046. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32047. }
  32048. if (parsedMesh.hasMatricesIndices) {
  32049. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32050. }
  32051. if (parsedMesh.hasMatricesWeights) {
  32052. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32053. }
  32054. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32055. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32056. mesh._checkDelayState();
  32057. }
  32058. }
  32059. else {
  32060. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32061. }
  32062. // Material
  32063. if (parsedMesh.materialId) {
  32064. mesh.setMaterialByID(parsedMesh.materialId);
  32065. }
  32066. else {
  32067. mesh.material = null;
  32068. }
  32069. // Morph targets
  32070. if (parsedMesh.morphTargetManagerId > -1) {
  32071. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32072. }
  32073. // Skeleton
  32074. if (parsedMesh.skeletonId > -1) {
  32075. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32076. if (parsedMesh.numBoneInfluencers) {
  32077. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32078. }
  32079. }
  32080. // Animations
  32081. if (parsedMesh.animations) {
  32082. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32083. var parsedAnimation = parsedMesh.animations[animationIndex];
  32084. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32085. }
  32086. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32087. }
  32088. if (parsedMesh.autoAnimate) {
  32089. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32090. }
  32091. // Layer Mask
  32092. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32093. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32094. }
  32095. else {
  32096. mesh.layerMask = 0x0FFFFFFF;
  32097. }
  32098. // Physics
  32099. if (parsedMesh.physicsImpostor) {
  32100. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32101. mass: parsedMesh.physicsMass,
  32102. friction: parsedMesh.physicsFriction,
  32103. restitution: parsedMesh.physicsRestitution
  32104. }, scene);
  32105. }
  32106. // Instances
  32107. if (parsedMesh.instances) {
  32108. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32109. var parsedInstance = parsedMesh.instances[index];
  32110. var instance = mesh.createInstance(parsedInstance.name);
  32111. if (parsedInstance.id) {
  32112. instance.id = parsedInstance.id;
  32113. }
  32114. if (BABYLON.Tags) {
  32115. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32116. }
  32117. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32118. if (parsedInstance.parentId) {
  32119. instance._waitingParentId = parsedInstance.parentId;
  32120. }
  32121. if (parsedInstance.rotationQuaternion) {
  32122. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32123. }
  32124. else if (parsedInstance.rotation) {
  32125. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32126. }
  32127. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32128. instance.checkCollisions = mesh.checkCollisions;
  32129. if (parsedMesh.animations) {
  32130. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32131. parsedAnimation = parsedMesh.animations[animationIndex];
  32132. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32133. }
  32134. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32135. }
  32136. }
  32137. }
  32138. return mesh;
  32139. };
  32140. /**
  32141. * Creates a ribbon mesh.
  32142. * Please consider using the same method from the MeshBuilder class instead.
  32143. * 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.
  32144. *
  32145. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32146. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32147. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32148. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32149. * 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.
  32150. * 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.
  32151. * 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
  32152. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32153. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32155. */
  32156. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32157. if (closeArray === void 0) { closeArray = false; }
  32158. if (updatable === void 0) { updatable = false; }
  32159. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32160. pathArray: pathArray,
  32161. closeArray: closeArray,
  32162. closePath: closePath,
  32163. offset: offset,
  32164. updatable: updatable,
  32165. sideOrientation: sideOrientation,
  32166. instance: instance
  32167. }, scene);
  32168. };
  32169. /**
  32170. * Creates a plane polygonal mesh. By default, this is a disc.
  32171. * Please consider using the same method from the MeshBuilder class instead.
  32172. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32173. * 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.
  32174. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32175. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32177. */
  32178. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32179. if (scene === void 0) { scene = null; }
  32180. var options = {
  32181. radius: radius,
  32182. tessellation: tessellation,
  32183. sideOrientation: sideOrientation,
  32184. updatable: updatable
  32185. };
  32186. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32187. };
  32188. /**
  32189. * Creates a box mesh.
  32190. * Please consider using the same method from the MeshBuilder class instead.
  32191. * The parameter `size` sets the size (float) of each box side (default 1).
  32192. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32193. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32194. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32195. */
  32196. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32197. if (scene === void 0) { scene = null; }
  32198. var options = {
  32199. size: size,
  32200. sideOrientation: sideOrientation,
  32201. updatable: updatable
  32202. };
  32203. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32204. };
  32205. /**
  32206. * Creates a sphere mesh.
  32207. * Please consider using the same method from the MeshBuilder class instead.
  32208. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32209. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32211. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32213. */
  32214. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32215. var options = {
  32216. segments: segments,
  32217. diameterX: diameter,
  32218. diameterY: diameter,
  32219. diameterZ: diameter,
  32220. sideOrientation: sideOrientation,
  32221. updatable: updatable
  32222. };
  32223. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32224. };
  32225. /**
  32226. * Creates a cylinder or a cone mesh.
  32227. * Please consider using the same method from the MeshBuilder class instead.
  32228. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32229. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32230. * 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.
  32231. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32232. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32236. */
  32237. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32238. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32239. if (scene !== undefined) {
  32240. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32241. updatable = scene;
  32242. }
  32243. scene = subdivisions;
  32244. subdivisions = 1;
  32245. }
  32246. var options = {
  32247. height: height,
  32248. diameterTop: diameterTop,
  32249. diameterBottom: diameterBottom,
  32250. tessellation: tessellation,
  32251. subdivisions: subdivisions,
  32252. sideOrientation: sideOrientation,
  32253. updatable: updatable
  32254. };
  32255. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32256. };
  32257. // Torus (Code from SharpDX.org)
  32258. /**
  32259. * Creates a torus mesh.
  32260. * Please consider using the same method from the MeshBuilder class instead.
  32261. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32262. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32263. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32267. */
  32268. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32269. var options = {
  32270. diameter: diameter,
  32271. thickness: thickness,
  32272. tessellation: tessellation,
  32273. sideOrientation: sideOrientation,
  32274. updatable: updatable
  32275. };
  32276. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32277. };
  32278. /**
  32279. * Creates a torus knot mesh.
  32280. * Please consider using the same method from the MeshBuilder class instead.
  32281. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32282. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32283. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32284. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32285. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32288. */
  32289. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32290. var options = {
  32291. radius: radius,
  32292. tube: tube,
  32293. radialSegments: radialSegments,
  32294. tubularSegments: tubularSegments,
  32295. p: p,
  32296. q: q,
  32297. sideOrientation: sideOrientation,
  32298. updatable: updatable
  32299. };
  32300. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32301. };
  32302. /**
  32303. * Creates a line mesh.
  32304. * Please consider using the same method from the MeshBuilder class instead.
  32305. * 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.
  32306. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32307. * The parameter `points` is an array successive Vector3.
  32308. * 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
  32309. * When updating an instance, remember that only point positions can change, not the number of points.
  32310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32311. */
  32312. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32313. if (scene === void 0) { scene = null; }
  32314. if (updatable === void 0) { updatable = false; }
  32315. if (instance === void 0) { instance = null; }
  32316. var options = {
  32317. points: points,
  32318. updatable: updatable,
  32319. instance: instance
  32320. };
  32321. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32322. };
  32323. /**
  32324. * Creates a dashed line mesh.
  32325. * Please consider using the same method from the MeshBuilder class instead.
  32326. * 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.
  32327. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32328. * The parameter `points` is an array successive Vector3.
  32329. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32330. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32331. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32332. * 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
  32333. * When updating an instance, remember that only point positions can change, not the number of points.
  32334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32335. */
  32336. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32337. if (scene === void 0) { scene = null; }
  32338. var options = {
  32339. points: points,
  32340. dashSize: dashSize,
  32341. gapSize: gapSize,
  32342. dashNb: dashNb,
  32343. updatable: updatable,
  32344. instance: instance
  32345. };
  32346. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32347. };
  32348. /**
  32349. * Creates a polygon mesh.
  32350. * Please consider using the same method from the MeshBuilder class instead.
  32351. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32352. * 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.
  32353. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32354. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32355. * Remember you can only change the shape positions, not their number when updating a polygon.
  32356. */
  32357. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32358. var options = {
  32359. shape: shape,
  32360. holes: holes,
  32361. updatable: updatable,
  32362. sideOrientation: sideOrientation
  32363. };
  32364. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32365. };
  32366. /**
  32367. * Creates an extruded polygon mesh, with depth in the Y direction.
  32368. * Please consider using the same method from the MeshBuilder class instead.
  32369. */
  32370. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32371. var options = {
  32372. shape: shape,
  32373. holes: holes,
  32374. depth: depth,
  32375. updatable: updatable,
  32376. sideOrientation: sideOrientation
  32377. };
  32378. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  32379. };
  32380. /**
  32381. * Creates an extruded shape mesh.
  32382. * 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.
  32383. * Please consider using the same method from the MeshBuilder class instead.
  32384. *
  32385. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32386. * 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
  32387. * extruded along the Z axis.
  32388. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32389. * 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.
  32390. * The parameter `scale` (float, default 1) is the value to scale the shape.
  32391. * 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
  32392. * 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
  32393. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32397. */
  32398. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  32399. if (scene === void 0) { scene = null; }
  32400. var options = {
  32401. shape: shape,
  32402. path: path,
  32403. scale: scale,
  32404. rotation: rotation,
  32405. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32406. sideOrientation: sideOrientation,
  32407. instance: instance,
  32408. updatable: updatable
  32409. };
  32410. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  32411. };
  32412. /**
  32413. * Creates an custom extruded shape mesh.
  32414. * 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.
  32415. * Please consider using the same method from the MeshBuilder class instead.
  32416. *
  32417. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32418. * 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
  32419. * extruded along the Z axis.
  32420. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32421. * 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
  32422. * and the distance of this point from the begining of the path :
  32423. * ```javascript
  32424. * var rotationFunction = function(i, distance) {
  32425. * // do things
  32426. * return rotationValue; }
  32427. * ```
  32428. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  32429. * 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
  32430. * and the distance of this point from the begining of the path :
  32431. * ```javascript
  32432. * var scaleFunction = function(i, distance) {
  32433. * // do things
  32434. * return scaleValue;}
  32435. * ```
  32436. * It must returns a float value that will be the scale value applied to the shape on each path point.
  32437. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  32438. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  32439. * 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
  32440. * 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
  32441. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32443. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32445. */
  32446. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  32447. var options = {
  32448. shape: shape,
  32449. path: path,
  32450. scaleFunction: scaleFunction,
  32451. rotationFunction: rotationFunction,
  32452. ribbonCloseArray: ribbonCloseArray,
  32453. ribbonClosePath: ribbonClosePath,
  32454. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32455. sideOrientation: sideOrientation,
  32456. instance: instance,
  32457. updatable: updatable
  32458. };
  32459. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  32460. };
  32461. /**
  32462. * Creates lathe mesh.
  32463. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  32464. * Please consider using the same method from the MeshBuilder class instead.
  32465. * 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
  32466. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  32467. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  32468. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  32469. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32470. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32471. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32472. */
  32473. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  32474. var options = {
  32475. shape: shape,
  32476. radius: radius,
  32477. tessellation: tessellation,
  32478. sideOrientation: sideOrientation,
  32479. updatable: updatable
  32480. };
  32481. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  32482. };
  32483. /**
  32484. * Creates a plane mesh.
  32485. * Please consider using the same method from the MeshBuilder class instead.
  32486. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  32487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32490. */
  32491. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  32492. var options = {
  32493. size: size,
  32494. width: size,
  32495. height: size,
  32496. sideOrientation: sideOrientation,
  32497. updatable: updatable
  32498. };
  32499. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  32500. };
  32501. /**
  32502. * Creates a ground mesh.
  32503. * Please consider using the same method from the MeshBuilder class instead.
  32504. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  32505. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  32506. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32507. */
  32508. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  32509. var options = {
  32510. width: width,
  32511. height: height,
  32512. subdivisions: subdivisions,
  32513. updatable: updatable
  32514. };
  32515. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  32516. };
  32517. /**
  32518. * Creates a tiled ground mesh.
  32519. * Please consider using the same method from the MeshBuilder class instead.
  32520. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  32521. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  32522. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  32523. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  32524. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  32525. * numbers of subdivisions on the ground width and height of each tile.
  32526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32527. */
  32528. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  32529. var options = {
  32530. xmin: xmin,
  32531. zmin: zmin,
  32532. xmax: xmax,
  32533. zmax: zmax,
  32534. subdivisions: subdivisions,
  32535. precision: precision,
  32536. updatable: updatable
  32537. };
  32538. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  32539. };
  32540. /**
  32541. * Creates a ground mesh from a height map.
  32542. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  32543. * Please consider using the same method from the MeshBuilder class instead.
  32544. * The parameter `url` sets the URL of the height map image resource.
  32545. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  32546. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  32547. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  32548. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  32549. * 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).
  32550. * This function is passed the newly built mesh :
  32551. * ```javascript
  32552. * function(mesh) { // do things
  32553. * return; }
  32554. * ```
  32555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32556. */
  32557. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  32558. var options = {
  32559. width: width,
  32560. height: height,
  32561. subdivisions: subdivisions,
  32562. minHeight: minHeight,
  32563. maxHeight: maxHeight,
  32564. updatable: updatable,
  32565. onReady: onReady
  32566. };
  32567. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  32568. };
  32569. /**
  32570. * Creates a tube mesh.
  32571. * 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.
  32572. * Please consider using the same method from the MeshBuilder class instead.
  32573. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  32574. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  32575. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  32576. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  32577. * 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.
  32578. * It must return a radius value (positive float) :
  32579. * ```javascript
  32580. * var radiusFunction = function(i, distance) {
  32581. * // do things
  32582. * return radius; }
  32583. * ```
  32584. * 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
  32585. * 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
  32586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32587. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32589. */
  32590. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  32591. var options = {
  32592. path: path,
  32593. radius: radius,
  32594. tessellation: tessellation,
  32595. radiusFunction: radiusFunction,
  32596. arc: 1,
  32597. cap: cap,
  32598. updatable: updatable,
  32599. sideOrientation: sideOrientation,
  32600. instance: instance
  32601. };
  32602. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  32603. };
  32604. /**
  32605. * Creates a polyhedron mesh.
  32606. * Please consider using the same method from the MeshBuilder class instead.
  32607. * 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
  32608. * to choose the wanted type.
  32609. * The parameter `size` (positive float, default 1) sets the polygon size.
  32610. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  32611. * 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`.
  32612. * 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
  32613. * 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)`).
  32614. * 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
  32615. * 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.
  32616. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32617. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32619. */
  32620. Mesh.CreatePolyhedron = function (name, options, scene) {
  32621. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  32622. };
  32623. /**
  32624. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  32625. * Please consider using the same method from the MeshBuilder class instead.
  32626. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  32627. * 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`).
  32628. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  32629. * 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.
  32630. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32631. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32633. */
  32634. Mesh.CreateIcoSphere = function (name, options, scene) {
  32635. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  32636. };
  32637. /**
  32638. * Creates a decal mesh.
  32639. * Please consider using the same method from the MeshBuilder class instead.
  32640. * 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.
  32641. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  32642. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  32643. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  32644. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  32645. */
  32646. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  32647. var options = {
  32648. position: position,
  32649. normal: normal,
  32650. size: size,
  32651. angle: angle
  32652. };
  32653. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  32654. };
  32655. // Skeletons
  32656. /**
  32657. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  32658. */
  32659. Mesh.prototype.setPositionsForCPUSkinning = function () {
  32660. if (!this._sourcePositions) {
  32661. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32662. if (!source) {
  32663. return this._sourcePositions;
  32664. }
  32665. this._sourcePositions = new Float32Array(source);
  32666. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32667. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  32668. }
  32669. }
  32670. return this._sourcePositions;
  32671. };
  32672. /**
  32673. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  32674. */
  32675. Mesh.prototype.setNormalsForCPUSkinning = function () {
  32676. if (!this._sourceNormals) {
  32677. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32678. if (!source) {
  32679. return this._sourceNormals;
  32680. }
  32681. this._sourceNormals = new Float32Array(source);
  32682. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32683. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  32684. }
  32685. }
  32686. return this._sourceNormals;
  32687. };
  32688. /**
  32689. * Updates the vertex buffer by applying transformation from the bones.
  32690. * Returns the Mesh.
  32691. *
  32692. * @param {skeleton} skeleton to apply
  32693. */
  32694. Mesh.prototype.applySkeleton = function (skeleton) {
  32695. if (!this.geometry) {
  32696. return this;
  32697. }
  32698. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  32699. return this;
  32700. }
  32701. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  32702. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32703. return this;
  32704. }
  32705. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32706. return this;
  32707. }
  32708. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32709. return this;
  32710. }
  32711. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32712. return this;
  32713. }
  32714. if (!this._sourcePositions) {
  32715. var submeshes = this.subMeshes.slice();
  32716. this.setPositionsForCPUSkinning();
  32717. this.subMeshes = submeshes;
  32718. }
  32719. if (!this._sourceNormals) {
  32720. this.setNormalsForCPUSkinning();
  32721. }
  32722. // positionsData checks for not being Float32Array will only pass at most once
  32723. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32724. if (!positionsData) {
  32725. return this;
  32726. }
  32727. if (!(positionsData instanceof Float32Array)) {
  32728. positionsData = new Float32Array(positionsData);
  32729. }
  32730. // normalsData checks for not being Float32Array will only pass at most once
  32731. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32732. if (!normalsData) {
  32733. return this;
  32734. }
  32735. if (!(normalsData instanceof Float32Array)) {
  32736. normalsData = new Float32Array(normalsData);
  32737. }
  32738. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32739. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32740. if (!matricesWeightsData || !matricesIndicesData) {
  32741. return this;
  32742. }
  32743. var needExtras = this.numBoneInfluencers > 4;
  32744. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32745. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32746. var skeletonMatrices = skeleton.getTransformMatrices(this);
  32747. var tempVector3 = BABYLON.Vector3.Zero();
  32748. var finalMatrix = new BABYLON.Matrix();
  32749. var tempMatrix = new BABYLON.Matrix();
  32750. var matWeightIdx = 0;
  32751. var inf;
  32752. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  32753. var weight;
  32754. for (inf = 0; inf < 4; inf++) {
  32755. weight = matricesWeightsData[matWeightIdx + inf];
  32756. if (weight > 0) {
  32757. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32758. finalMatrix.addToSelf(tempMatrix);
  32759. }
  32760. else
  32761. break;
  32762. }
  32763. if (needExtras) {
  32764. for (inf = 0; inf < 4; inf++) {
  32765. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32766. if (weight > 0) {
  32767. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32768. finalMatrix.addToSelf(tempMatrix);
  32769. }
  32770. else
  32771. break;
  32772. }
  32773. }
  32774. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  32775. tempVector3.toArray(positionsData, index);
  32776. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  32777. tempVector3.toArray(normalsData, index);
  32778. finalMatrix.reset();
  32779. }
  32780. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  32781. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  32782. return this;
  32783. };
  32784. // Tools
  32785. /**
  32786. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  32787. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  32788. */
  32789. Mesh.MinMax = function (meshes) {
  32790. var minVector = null;
  32791. var maxVector = null;
  32792. meshes.forEach(function (mesh, index, array) {
  32793. var boundingInfo = mesh.getBoundingInfo();
  32794. var boundingBox = boundingInfo.boundingBox;
  32795. if (!minVector || !maxVector) {
  32796. minVector = boundingBox.minimumWorld;
  32797. maxVector = boundingBox.maximumWorld;
  32798. }
  32799. else {
  32800. minVector.minimizeInPlace(boundingBox.minimumWorld);
  32801. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  32802. }
  32803. });
  32804. if (!minVector || !maxVector) {
  32805. return {
  32806. min: BABYLON.Vector3.Zero(),
  32807. max: BABYLON.Vector3.Zero()
  32808. };
  32809. }
  32810. return {
  32811. min: minVector,
  32812. max: maxVector
  32813. };
  32814. };
  32815. /**
  32816. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  32817. */
  32818. Mesh.Center = function (meshesOrMinMaxVector) {
  32819. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  32820. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  32821. };
  32822. /**
  32823. * Merge the array of meshes into a single mesh for performance reasons.
  32824. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  32825. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  32826. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  32827. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  32828. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  32829. */
  32830. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  32831. if (disposeSource === void 0) { disposeSource = true; }
  32832. var index;
  32833. if (!allow32BitsIndices) {
  32834. var totalVertices = 0;
  32835. // Counting vertices
  32836. for (index = 0; index < meshes.length; index++) {
  32837. if (meshes[index]) {
  32838. totalVertices += meshes[index].getTotalVertices();
  32839. if (totalVertices > 65536) {
  32840. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  32841. return null;
  32842. }
  32843. }
  32844. }
  32845. }
  32846. // Merge
  32847. var vertexData = null;
  32848. var otherVertexData;
  32849. var indiceArray = new Array();
  32850. var source = null;
  32851. for (index = 0; index < meshes.length; index++) {
  32852. if (meshes[index]) {
  32853. meshes[index].computeWorldMatrix(true);
  32854. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  32855. otherVertexData.transform(meshes[index].getWorldMatrix());
  32856. if (vertexData) {
  32857. vertexData.merge(otherVertexData);
  32858. }
  32859. else {
  32860. vertexData = otherVertexData;
  32861. source = meshes[index];
  32862. }
  32863. if (subdivideWithSubMeshes) {
  32864. indiceArray.push(meshes[index].getTotalIndices());
  32865. }
  32866. }
  32867. }
  32868. source = source;
  32869. if (!meshSubclass) {
  32870. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  32871. }
  32872. vertexData.applyToMesh(meshSubclass);
  32873. // Setting properties
  32874. meshSubclass.material = source.material;
  32875. meshSubclass.checkCollisions = source.checkCollisions;
  32876. // Cleaning
  32877. if (disposeSource) {
  32878. for (index = 0; index < meshes.length; index++) {
  32879. if (meshes[index]) {
  32880. meshes[index].dispose();
  32881. }
  32882. }
  32883. }
  32884. // Subdivide
  32885. if (subdivideWithSubMeshes) {
  32886. //-- Suppresions du submesh global
  32887. meshSubclass.releaseSubMeshes();
  32888. index = 0;
  32889. var offset = 0;
  32890. //-- aplique la subdivision en fonction du tableau d'indices
  32891. while (index < indiceArray.length) {
  32892. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  32893. offset += indiceArray[index];
  32894. index++;
  32895. }
  32896. }
  32897. return meshSubclass;
  32898. };
  32899. // Consts
  32900. Mesh._FRONTSIDE = 0;
  32901. Mesh._BACKSIDE = 1;
  32902. Mesh._DOUBLESIDE = 2;
  32903. Mesh._DEFAULTSIDE = 0;
  32904. Mesh._NO_CAP = 0;
  32905. Mesh._CAP_START = 1;
  32906. Mesh._CAP_END = 2;
  32907. Mesh._CAP_ALL = 3;
  32908. return Mesh;
  32909. }(BABYLON.AbstractMesh));
  32910. BABYLON.Mesh = Mesh;
  32911. })(BABYLON || (BABYLON = {}));
  32912. //# sourceMappingURL=babylon.mesh.js.map
  32913. "use strict";
  32914. var BABYLON;
  32915. (function (BABYLON) {
  32916. var BaseSubMesh = /** @class */ (function () {
  32917. function BaseSubMesh() {
  32918. }
  32919. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  32920. get: function () {
  32921. return this._materialEffect;
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  32927. if (defines === void 0) { defines = null; }
  32928. if (this._materialEffect === effect) {
  32929. if (!effect) {
  32930. this._materialDefines = null;
  32931. }
  32932. return;
  32933. }
  32934. this._materialDefines = defines;
  32935. this._materialEffect = effect;
  32936. };
  32937. return BaseSubMesh;
  32938. }());
  32939. BABYLON.BaseSubMesh = BaseSubMesh;
  32940. var SubMesh = /** @class */ (function (_super) {
  32941. __extends(SubMesh, _super);
  32942. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  32943. if (createBoundingBox === void 0) { createBoundingBox = true; }
  32944. var _this = _super.call(this) || this;
  32945. _this.materialIndex = materialIndex;
  32946. _this.verticesStart = verticesStart;
  32947. _this.verticesCount = verticesCount;
  32948. _this.indexStart = indexStart;
  32949. _this.indexCount = indexCount;
  32950. _this._renderId = 0;
  32951. _this._mesh = mesh;
  32952. _this._renderingMesh = renderingMesh || mesh;
  32953. mesh.subMeshes.push(_this);
  32954. _this._trianglePlanes = [];
  32955. _this._id = mesh.subMeshes.length - 1;
  32956. if (createBoundingBox) {
  32957. _this.refreshBoundingInfo();
  32958. mesh.computeWorldMatrix(true);
  32959. }
  32960. return _this;
  32961. }
  32962. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  32963. if (createBoundingBox === void 0) { createBoundingBox = true; }
  32964. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  32965. };
  32966. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  32967. get: function () {
  32968. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  32969. },
  32970. enumerable: true,
  32971. configurable: true
  32972. });
  32973. /**
  32974. * Returns the submesh BoudingInfo object.
  32975. */
  32976. SubMesh.prototype.getBoundingInfo = function () {
  32977. if (this.IsGlobal) {
  32978. return this._mesh.getBoundingInfo();
  32979. }
  32980. return this._boundingInfo;
  32981. };
  32982. /**
  32983. * Sets the submesh BoundingInfo.
  32984. * Return the SubMesh.
  32985. */
  32986. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  32987. this._boundingInfo = boundingInfo;
  32988. return this;
  32989. };
  32990. /**
  32991. * Returns the mesh of the current submesh.
  32992. */
  32993. SubMesh.prototype.getMesh = function () {
  32994. return this._mesh;
  32995. };
  32996. /**
  32997. * Returns the rendering mesh of the submesh.
  32998. */
  32999. SubMesh.prototype.getRenderingMesh = function () {
  33000. return this._renderingMesh;
  33001. };
  33002. /**
  33003. * Returns the submesh material.
  33004. */
  33005. SubMesh.prototype.getMaterial = function () {
  33006. var rootMaterial = this._renderingMesh.material;
  33007. if (rootMaterial === null || rootMaterial === undefined) {
  33008. return this._mesh.getScene().defaultMaterial;
  33009. }
  33010. else if (rootMaterial.getSubMaterial) {
  33011. var multiMaterial = rootMaterial;
  33012. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33013. if (this._currentMaterial !== effectiveMaterial) {
  33014. this._currentMaterial = effectiveMaterial;
  33015. this._materialDefines = null;
  33016. }
  33017. return effectiveMaterial;
  33018. }
  33019. return rootMaterial;
  33020. };
  33021. // Methods
  33022. /**
  33023. * Sets a new updated BoundingInfo object to the submesh.
  33024. * Returns the SubMesh.
  33025. */
  33026. SubMesh.prototype.refreshBoundingInfo = function () {
  33027. this._lastColliderWorldVertices = null;
  33028. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33029. return this;
  33030. }
  33031. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33032. if (!data) {
  33033. this._boundingInfo = this._mesh.getBoundingInfo();
  33034. return this;
  33035. }
  33036. var indices = this._renderingMesh.getIndices();
  33037. var extend;
  33038. //is this the only submesh?
  33039. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33040. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33041. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33042. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33043. }
  33044. else {
  33045. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33046. }
  33047. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33048. return this;
  33049. };
  33050. SubMesh.prototype._checkCollision = function (collider) {
  33051. var boundingInfo = this.getBoundingInfo();
  33052. return boundingInfo._checkCollision(collider);
  33053. };
  33054. /**
  33055. * Updates the submesh BoundingInfo.
  33056. * Returns the Submesh.
  33057. */
  33058. SubMesh.prototype.updateBoundingInfo = function (world) {
  33059. var boundingInfo = this.getBoundingInfo();
  33060. if (!boundingInfo) {
  33061. this.refreshBoundingInfo();
  33062. boundingInfo = this.getBoundingInfo();
  33063. }
  33064. boundingInfo.update(world);
  33065. return this;
  33066. };
  33067. /**
  33068. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33069. * Boolean returned.
  33070. */
  33071. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33072. var boundingInfo = this.getBoundingInfo();
  33073. if (!boundingInfo) {
  33074. return false;
  33075. }
  33076. return boundingInfo.isInFrustum(frustumPlanes);
  33077. };
  33078. /**
  33079. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33080. * Boolean returned.
  33081. */
  33082. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33083. var boundingInfo = this.getBoundingInfo();
  33084. if (!boundingInfo) {
  33085. return false;
  33086. }
  33087. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33088. };
  33089. /**
  33090. * Renders the submesh.
  33091. * Returns it.
  33092. */
  33093. SubMesh.prototype.render = function (enableAlphaMode) {
  33094. this._renderingMesh.render(this, enableAlphaMode);
  33095. return this;
  33096. };
  33097. /**
  33098. * Returns a new Index Buffer.
  33099. * Type returned : WebGLBuffer.
  33100. */
  33101. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33102. if (!this._linesIndexBuffer) {
  33103. var linesIndices = [];
  33104. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33105. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33106. }
  33107. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33108. this.linesIndexCount = linesIndices.length;
  33109. }
  33110. return this._linesIndexBuffer;
  33111. };
  33112. /**
  33113. * True is the passed Ray intersects the submesh bounding box.
  33114. * Boolean returned.
  33115. */
  33116. SubMesh.prototype.canIntersects = function (ray) {
  33117. var boundingInfo = this.getBoundingInfo();
  33118. if (!boundingInfo) {
  33119. return false;
  33120. }
  33121. return ray.intersectsBox(boundingInfo.boundingBox);
  33122. };
  33123. /**
  33124. * Returns an object IntersectionInfo.
  33125. */
  33126. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33127. var intersectInfo = null;
  33128. var material = this.getMaterial();
  33129. if (!material) {
  33130. return null;
  33131. }
  33132. switch (material.fillMode) {
  33133. case BABYLON.Material.PointListDrawMode:
  33134. case BABYLON.Material.LineListDrawMode:
  33135. case BABYLON.Material.LineLoopDrawMode:
  33136. case BABYLON.Material.LineStripDrawMode:
  33137. case BABYLON.Material.TriangleFanDrawMode:
  33138. case BABYLON.Material.TriangleStripDrawMode:
  33139. return null;
  33140. }
  33141. // LineMesh first as it's also a Mesh...
  33142. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33143. var lineMesh = this._mesh;
  33144. // Line test
  33145. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33146. var p0 = positions[indices[index]];
  33147. var p1 = positions[indices[index + 1]];
  33148. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33149. if (length < 0) {
  33150. continue;
  33151. }
  33152. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33153. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33154. if (fastCheck) {
  33155. break;
  33156. }
  33157. }
  33158. }
  33159. }
  33160. else {
  33161. // Triangles test
  33162. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33163. var p0 = positions[indices[index]];
  33164. var p1 = positions[indices[index + 1]];
  33165. var p2 = positions[indices[index + 2]];
  33166. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33167. if (currentIntersectInfo) {
  33168. if (currentIntersectInfo.distance < 0) {
  33169. continue;
  33170. }
  33171. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33172. intersectInfo = currentIntersectInfo;
  33173. intersectInfo.faceId = index / 3;
  33174. if (fastCheck) {
  33175. break;
  33176. }
  33177. }
  33178. }
  33179. }
  33180. }
  33181. return intersectInfo;
  33182. };
  33183. SubMesh.prototype._rebuild = function () {
  33184. if (this._linesIndexBuffer) {
  33185. this._linesIndexBuffer = null;
  33186. }
  33187. };
  33188. // Clone
  33189. /**
  33190. * Creates a new Submesh from the passed Mesh.
  33191. */
  33192. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33193. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33194. if (!this.IsGlobal) {
  33195. var boundingInfo = this.getBoundingInfo();
  33196. if (!boundingInfo) {
  33197. return result;
  33198. }
  33199. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33200. }
  33201. return result;
  33202. };
  33203. // Dispose
  33204. /**
  33205. * Disposes the Submesh.
  33206. * Returns nothing.
  33207. */
  33208. SubMesh.prototype.dispose = function () {
  33209. if (this._linesIndexBuffer) {
  33210. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33211. this._linesIndexBuffer = null;
  33212. }
  33213. // Remove from mesh
  33214. var index = this._mesh.subMeshes.indexOf(this);
  33215. this._mesh.subMeshes.splice(index, 1);
  33216. };
  33217. // Statics
  33218. /**
  33219. * Creates a new Submesh from the passed parameters :
  33220. * - materialIndex (integer) : the index of the main mesh material.
  33221. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33222. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33223. * - mesh (Mesh) : the main mesh to create the submesh from.
  33224. * - renderingMesh (optional Mesh) : rendering mesh.
  33225. */
  33226. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33227. var minVertexIndex = Number.MAX_VALUE;
  33228. var maxVertexIndex = -Number.MAX_VALUE;
  33229. renderingMesh = (renderingMesh || mesh);
  33230. var indices = renderingMesh.getIndices();
  33231. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33232. var vertexIndex = indices[index];
  33233. if (vertexIndex < minVertexIndex)
  33234. minVertexIndex = vertexIndex;
  33235. if (vertexIndex > maxVertexIndex)
  33236. maxVertexIndex = vertexIndex;
  33237. }
  33238. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33239. };
  33240. return SubMesh;
  33241. }(BaseSubMesh));
  33242. BABYLON.SubMesh = SubMesh;
  33243. })(BABYLON || (BABYLON = {}));
  33244. //# sourceMappingURL=babylon.subMesh.js.map
  33245. "use strict";
  33246. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33247. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33248. s = arguments[i];
  33249. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33250. t[p] = s[p];
  33251. }
  33252. return t;
  33253. };
  33254. var BABYLON;
  33255. (function (BABYLON) {
  33256. /**
  33257. * Manages the defines for the Material
  33258. */
  33259. var MaterialDefines = /** @class */ (function () {
  33260. function MaterialDefines() {
  33261. this._isDirty = true;
  33262. this._areLightsDirty = true;
  33263. this._areAttributesDirty = true;
  33264. this._areTexturesDirty = true;
  33265. this._areFresnelDirty = true;
  33266. this._areMiscDirty = true;
  33267. this._areImageProcessingDirty = true;
  33268. this._normals = false;
  33269. this._uvs = false;
  33270. this._needNormals = false;
  33271. this._needUVs = false;
  33272. }
  33273. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33274. /**
  33275. * Specifies if the material needs to be re-calculated
  33276. */
  33277. get: function () {
  33278. return this._isDirty;
  33279. },
  33280. enumerable: true,
  33281. configurable: true
  33282. });
  33283. /**
  33284. * Marks the material to indicate that it has been re-calculated
  33285. */
  33286. MaterialDefines.prototype.markAsProcessed = function () {
  33287. this._isDirty = false;
  33288. this._areAttributesDirty = false;
  33289. this._areTexturesDirty = false;
  33290. this._areFresnelDirty = false;
  33291. this._areLightsDirty = false;
  33292. this._areMiscDirty = false;
  33293. this._areImageProcessingDirty = false;
  33294. };
  33295. /**
  33296. * Marks the material to indicate that it needs to be re-calculated
  33297. */
  33298. MaterialDefines.prototype.markAsUnprocessed = function () {
  33299. this._isDirty = true;
  33300. };
  33301. /**
  33302. * Marks the material to indicate all of its defines need to be re-calculated
  33303. */
  33304. MaterialDefines.prototype.markAllAsDirty = function () {
  33305. this._areTexturesDirty = true;
  33306. this._areAttributesDirty = true;
  33307. this._areLightsDirty = true;
  33308. this._areFresnelDirty = true;
  33309. this._areMiscDirty = true;
  33310. this._areImageProcessingDirty = true;
  33311. this._isDirty = true;
  33312. };
  33313. /**
  33314. * Marks the material to indicate that image processing needs to be re-calculated
  33315. */
  33316. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33317. this._areImageProcessingDirty = true;
  33318. this._isDirty = true;
  33319. };
  33320. /**
  33321. * Marks the material to indicate the lights need to be re-calculated
  33322. */
  33323. MaterialDefines.prototype.markAsLightDirty = function () {
  33324. this._areLightsDirty = true;
  33325. this._isDirty = true;
  33326. };
  33327. /**
  33328. * Marks the attribute state as changed
  33329. */
  33330. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33331. this._areAttributesDirty = true;
  33332. this._isDirty = true;
  33333. };
  33334. /**
  33335. * Marks the texture state as changed
  33336. */
  33337. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33338. this._areTexturesDirty = true;
  33339. this._isDirty = true;
  33340. };
  33341. /**
  33342. * Marks the fresnel state as changed
  33343. */
  33344. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33345. this._areFresnelDirty = true;
  33346. this._isDirty = true;
  33347. };
  33348. /**
  33349. * Marks the misc state as changed
  33350. */
  33351. MaterialDefines.prototype.markAsMiscDirty = function () {
  33352. this._areMiscDirty = true;
  33353. this._isDirty = true;
  33354. };
  33355. /**
  33356. * Rebuilds the material defines
  33357. */
  33358. MaterialDefines.prototype.rebuild = function () {
  33359. if (this._keys) {
  33360. delete this._keys;
  33361. }
  33362. this._keys = [];
  33363. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33364. var key = _a[_i];
  33365. if (key[0] === "_") {
  33366. continue;
  33367. }
  33368. this._keys.push(key);
  33369. }
  33370. };
  33371. /**
  33372. * Specifies if two material defines are equal
  33373. * @param other - A material define instance to compare to
  33374. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  33375. */
  33376. MaterialDefines.prototype.isEqual = function (other) {
  33377. if (this._keys.length !== other._keys.length) {
  33378. return false;
  33379. }
  33380. for (var index = 0; index < this._keys.length; index++) {
  33381. var prop = this._keys[index];
  33382. if (this[prop] !== other[prop]) {
  33383. return false;
  33384. }
  33385. }
  33386. return true;
  33387. };
  33388. /**
  33389. * Clones this instance's defines to another instance
  33390. * @param other - material defines to clone values to
  33391. */
  33392. MaterialDefines.prototype.cloneTo = function (other) {
  33393. if (this._keys.length !== other._keys.length) {
  33394. other._keys = this._keys.slice(0);
  33395. }
  33396. for (var index = 0; index < this._keys.length; index++) {
  33397. var prop = this._keys[index];
  33398. other[prop] = this[prop];
  33399. }
  33400. };
  33401. /**
  33402. * Resets the material define values
  33403. */
  33404. MaterialDefines.prototype.reset = function () {
  33405. for (var index = 0; index < this._keys.length; index++) {
  33406. var prop = this._keys[index];
  33407. var type = typeof this[prop];
  33408. switch (type) {
  33409. case "number":
  33410. this[prop] = 0;
  33411. break;
  33412. case "string":
  33413. this[prop] = "";
  33414. break;
  33415. default:
  33416. this[prop] = false;
  33417. break;
  33418. }
  33419. }
  33420. };
  33421. /**
  33422. * Converts the material define values to a string
  33423. * @returns - String of material define information
  33424. */
  33425. MaterialDefines.prototype.toString = function () {
  33426. var result = "";
  33427. for (var index = 0; index < this._keys.length; index++) {
  33428. var prop = this._keys[index];
  33429. var value = this[prop];
  33430. var type = typeof value;
  33431. switch (type) {
  33432. case "number":
  33433. case "string":
  33434. result += "#define " + prop + " " + value + "\n";
  33435. break;
  33436. default:
  33437. if (value) {
  33438. result += "#define " + prop + "\n";
  33439. }
  33440. break;
  33441. }
  33442. }
  33443. return result;
  33444. };
  33445. return MaterialDefines;
  33446. }());
  33447. BABYLON.MaterialDefines = MaterialDefines;
  33448. /**
  33449. * Base class for the main features of a material in Babylon.js
  33450. */
  33451. var Material = /** @class */ (function () {
  33452. /**
  33453. * Creates a material instance
  33454. * @param name defines the name of the material
  33455. * @param scene defines the scene to reference
  33456. * @param doNotAdd specifies if the material should be added to the scene
  33457. */
  33458. function Material(name, scene, doNotAdd) {
  33459. /**
  33460. * Specifies if the ready state should be checked on each call
  33461. */
  33462. this.checkReadyOnEveryCall = false;
  33463. /**
  33464. * Specifies if the ready state should be checked once
  33465. */
  33466. this.checkReadyOnlyOnce = false;
  33467. /**
  33468. * The state of the material
  33469. */
  33470. this.state = "";
  33471. /**
  33472. * The alpha value of the material
  33473. */
  33474. this._alpha = 1.0;
  33475. /**
  33476. * Specifies if back face culling is enabled
  33477. */
  33478. this._backFaceCulling = true;
  33479. /**
  33480. * Specifies if the material should be serialized
  33481. */
  33482. this.doNotSerialize = false;
  33483. /**
  33484. * Specifies if the effect should be stored on sub meshes
  33485. */
  33486. this.storeEffectOnSubMeshes = false;
  33487. /**
  33488. * An event triggered when the material is disposed
  33489. */
  33490. this.onDisposeObservable = new BABYLON.Observable();
  33491. /**
  33492. * An event triggered when the material is bound
  33493. */
  33494. this.onBindObservable = new BABYLON.Observable();
  33495. /**
  33496. * An event triggered when the material is unbound
  33497. */
  33498. this.onUnBindObservable = new BABYLON.Observable();
  33499. /**
  33500. * Stores the value of the alpha mode
  33501. */
  33502. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  33503. /**
  33504. * Stores the state of the need depth pre-pass value
  33505. */
  33506. this._needDepthPrePass = false;
  33507. /**
  33508. * Specifies if depth writing should be disabled
  33509. */
  33510. this.disableDepthWrite = false;
  33511. /**
  33512. * Specifies if depth writing should be forced
  33513. */
  33514. this.forceDepthWrite = false;
  33515. /**
  33516. * Specifies if there should be a separate pass for culling
  33517. */
  33518. this.separateCullingPass = false;
  33519. /**
  33520. * Stores the state specifing if fog should be enabled
  33521. */
  33522. this._fogEnabled = true;
  33523. /**
  33524. * Stores the size of points
  33525. */
  33526. this.pointSize = 1.0;
  33527. /**
  33528. * Stores the z offset value
  33529. */
  33530. this.zOffset = 0;
  33531. /**
  33532. * Specifies if the material was previously ready
  33533. */
  33534. this._wasPreviouslyReady = false;
  33535. /**
  33536. * Stores the fill mode state
  33537. */
  33538. this._fillMode = Material.TriangleFillMode;
  33539. this.name = name;
  33540. this.id = name || BABYLON.Tools.RandomId();
  33541. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33542. if (this._scene.useRightHandedSystem) {
  33543. this.sideOrientation = Material.ClockWiseSideOrientation;
  33544. }
  33545. else {
  33546. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  33547. }
  33548. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  33549. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  33550. if (!doNotAdd) {
  33551. this._scene.materials.push(this);
  33552. }
  33553. }
  33554. Object.defineProperty(Material, "TriangleFillMode", {
  33555. /**
  33556. * Returns the triangle fill mode
  33557. */
  33558. get: function () {
  33559. return Material._TriangleFillMode;
  33560. },
  33561. enumerable: true,
  33562. configurable: true
  33563. });
  33564. Object.defineProperty(Material, "WireFrameFillMode", {
  33565. /**
  33566. * Returns the wireframe mode
  33567. */
  33568. get: function () {
  33569. return Material._WireFrameFillMode;
  33570. },
  33571. enumerable: true,
  33572. configurable: true
  33573. });
  33574. Object.defineProperty(Material, "PointFillMode", {
  33575. /**
  33576. * Returns the point fill mode
  33577. */
  33578. get: function () {
  33579. return Material._PointFillMode;
  33580. },
  33581. enumerable: true,
  33582. configurable: true
  33583. });
  33584. Object.defineProperty(Material, "PointListDrawMode", {
  33585. /**
  33586. * Returns the point list draw mode
  33587. */
  33588. get: function () {
  33589. return Material._PointListDrawMode;
  33590. },
  33591. enumerable: true,
  33592. configurable: true
  33593. });
  33594. Object.defineProperty(Material, "LineListDrawMode", {
  33595. /**
  33596. * Returns the line list draw mode
  33597. */
  33598. get: function () {
  33599. return Material._LineListDrawMode;
  33600. },
  33601. enumerable: true,
  33602. configurable: true
  33603. });
  33604. Object.defineProperty(Material, "LineLoopDrawMode", {
  33605. /**
  33606. * Returns the line loop draw mode
  33607. */
  33608. get: function () {
  33609. return Material._LineLoopDrawMode;
  33610. },
  33611. enumerable: true,
  33612. configurable: true
  33613. });
  33614. Object.defineProperty(Material, "LineStripDrawMode", {
  33615. /**
  33616. * Returns the line strip draw mode
  33617. */
  33618. get: function () {
  33619. return Material._LineStripDrawMode;
  33620. },
  33621. enumerable: true,
  33622. configurable: true
  33623. });
  33624. Object.defineProperty(Material, "TriangleStripDrawMode", {
  33625. /**
  33626. * Returns the triangle strip draw mode
  33627. */
  33628. get: function () {
  33629. return Material._TriangleStripDrawMode;
  33630. },
  33631. enumerable: true,
  33632. configurable: true
  33633. });
  33634. Object.defineProperty(Material, "TriangleFanDrawMode", {
  33635. /**
  33636. * Returns the triangle fan draw mode
  33637. */
  33638. get: function () {
  33639. return Material._TriangleFanDrawMode;
  33640. },
  33641. enumerable: true,
  33642. configurable: true
  33643. });
  33644. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  33645. /**
  33646. * Returns the clock-wise side orientation
  33647. */
  33648. get: function () {
  33649. return Material._ClockWiseSideOrientation;
  33650. },
  33651. enumerable: true,
  33652. configurable: true
  33653. });
  33654. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  33655. /**
  33656. * Returns the counter clock-wise side orientation
  33657. */
  33658. get: function () {
  33659. return Material._CounterClockWiseSideOrientation;
  33660. },
  33661. enumerable: true,
  33662. configurable: true
  33663. });
  33664. Object.defineProperty(Material, "TextureDirtyFlag", {
  33665. /**
  33666. * Returns the dirty texture flag value
  33667. */
  33668. get: function () {
  33669. return Material._TextureDirtyFlag;
  33670. },
  33671. enumerable: true,
  33672. configurable: true
  33673. });
  33674. Object.defineProperty(Material, "LightDirtyFlag", {
  33675. /**
  33676. * Returns the dirty light flag value
  33677. */
  33678. get: function () {
  33679. return Material._LightDirtyFlag;
  33680. },
  33681. enumerable: true,
  33682. configurable: true
  33683. });
  33684. Object.defineProperty(Material, "FresnelDirtyFlag", {
  33685. /**
  33686. * Returns the dirty fresnel flag value
  33687. */
  33688. get: function () {
  33689. return Material._FresnelDirtyFlag;
  33690. },
  33691. enumerable: true,
  33692. configurable: true
  33693. });
  33694. Object.defineProperty(Material, "AttributesDirtyFlag", {
  33695. /**
  33696. * Returns the dirty attributes flag value
  33697. */
  33698. get: function () {
  33699. return Material._AttributesDirtyFlag;
  33700. },
  33701. enumerable: true,
  33702. configurable: true
  33703. });
  33704. Object.defineProperty(Material, "MiscDirtyFlag", {
  33705. /**
  33706. * Returns the dirty misc flag value
  33707. */
  33708. get: function () {
  33709. return Material._MiscDirtyFlag;
  33710. },
  33711. enumerable: true,
  33712. configurable: true
  33713. });
  33714. Object.defineProperty(Material.prototype, "alpha", {
  33715. /**
  33716. * Gets the alpha value of the material
  33717. */
  33718. get: function () {
  33719. return this._alpha;
  33720. },
  33721. /**
  33722. * Sets the alpha value of the material
  33723. */
  33724. set: function (value) {
  33725. if (this._alpha === value) {
  33726. return;
  33727. }
  33728. this._alpha = value;
  33729. this.markAsDirty(Material.MiscDirtyFlag);
  33730. },
  33731. enumerable: true,
  33732. configurable: true
  33733. });
  33734. Object.defineProperty(Material.prototype, "backFaceCulling", {
  33735. /**
  33736. * Gets the back-face culling state
  33737. */
  33738. get: function () {
  33739. return this._backFaceCulling;
  33740. },
  33741. /**
  33742. * Sets the back-face culling state
  33743. */
  33744. set: function (value) {
  33745. if (this._backFaceCulling === value) {
  33746. return;
  33747. }
  33748. this._backFaceCulling = value;
  33749. this.markAsDirty(Material.TextureDirtyFlag);
  33750. },
  33751. enumerable: true,
  33752. configurable: true
  33753. });
  33754. Object.defineProperty(Material.prototype, "onDispose", {
  33755. /**
  33756. * Called during a dispose event
  33757. */
  33758. set: function (callback) {
  33759. if (this._onDisposeObserver) {
  33760. this.onDisposeObservable.remove(this._onDisposeObserver);
  33761. }
  33762. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33763. },
  33764. enumerable: true,
  33765. configurable: true
  33766. });
  33767. Object.defineProperty(Material.prototype, "onBind", {
  33768. /**
  33769. * Called during a bind event
  33770. */
  33771. set: function (callback) {
  33772. if (this._onBindObserver) {
  33773. this.onBindObservable.remove(this._onBindObserver);
  33774. }
  33775. this._onBindObserver = this.onBindObservable.add(callback);
  33776. },
  33777. enumerable: true,
  33778. configurable: true
  33779. });
  33780. Object.defineProperty(Material.prototype, "alphaMode", {
  33781. /**
  33782. * Gets the value of the alpha mode
  33783. */
  33784. get: function () {
  33785. return this._alphaMode;
  33786. },
  33787. /**
  33788. * Sets the value of the alpha mode.
  33789. *
  33790. * | Value | Type | Description |
  33791. * | --- | --- | --- |
  33792. * | 0 | ALPHA_DISABLE | |
  33793. * | 1 | ALPHA_ADD | |
  33794. * | 2 | ALPHA_COMBINE | |
  33795. * | 3 | ALPHA_SUBTRACT | |
  33796. * | 4 | ALPHA_MULTIPLY | |
  33797. * | 5 | ALPHA_MAXIMIZED | |
  33798. * | 6 | ALPHA_ONEONE | |
  33799. * | 7 | ALPHA_PREMULTIPLIED | |
  33800. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  33801. * | 9 | ALPHA_INTERPOLATE | |
  33802. * | 10 | ALPHA_SCREENMODE | |
  33803. *
  33804. */
  33805. set: function (value) {
  33806. if (this._alphaMode === value) {
  33807. return;
  33808. }
  33809. this._alphaMode = value;
  33810. this.markAsDirty(Material.TextureDirtyFlag);
  33811. },
  33812. enumerable: true,
  33813. configurable: true
  33814. });
  33815. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  33816. /**
  33817. * Gets the depth pre-pass value
  33818. */
  33819. get: function () {
  33820. return this._needDepthPrePass;
  33821. },
  33822. /**
  33823. * Sets the need depth pre-pass value
  33824. */
  33825. set: function (value) {
  33826. if (this._needDepthPrePass === value) {
  33827. return;
  33828. }
  33829. this._needDepthPrePass = value;
  33830. if (this._needDepthPrePass) {
  33831. this.checkReadyOnEveryCall = true;
  33832. }
  33833. },
  33834. enumerable: true,
  33835. configurable: true
  33836. });
  33837. Object.defineProperty(Material.prototype, "fogEnabled", {
  33838. /**
  33839. * Gets the value of the fog enabled state
  33840. */
  33841. get: function () {
  33842. return this._fogEnabled;
  33843. },
  33844. /**
  33845. * Sets the state for enabling fog
  33846. */
  33847. set: function (value) {
  33848. if (this._fogEnabled === value) {
  33849. return;
  33850. }
  33851. this._fogEnabled = value;
  33852. this.markAsDirty(Material.MiscDirtyFlag);
  33853. },
  33854. enumerable: true,
  33855. configurable: true
  33856. });
  33857. Object.defineProperty(Material.prototype, "wireframe", {
  33858. /**
  33859. * Gets a value specifying if wireframe mode is enabled
  33860. */
  33861. get: function () {
  33862. switch (this._fillMode) {
  33863. case Material.WireFrameFillMode:
  33864. case Material.LineListDrawMode:
  33865. case Material.LineLoopDrawMode:
  33866. case Material.LineStripDrawMode:
  33867. return true;
  33868. }
  33869. return this._scene.forceWireframe;
  33870. },
  33871. /**
  33872. * Sets the state of wireframe mode
  33873. */
  33874. set: function (value) {
  33875. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  33876. },
  33877. enumerable: true,
  33878. configurable: true
  33879. });
  33880. Object.defineProperty(Material.prototype, "pointsCloud", {
  33881. /**
  33882. * Gets the value specifying if point clouds are enabled
  33883. */
  33884. get: function () {
  33885. switch (this._fillMode) {
  33886. case Material.PointFillMode:
  33887. case Material.PointListDrawMode:
  33888. return true;
  33889. }
  33890. return this._scene.forcePointsCloud;
  33891. },
  33892. /**
  33893. * Sets the state of point cloud mode
  33894. */
  33895. set: function (value) {
  33896. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  33897. },
  33898. enumerable: true,
  33899. configurable: true
  33900. });
  33901. Object.defineProperty(Material.prototype, "fillMode", {
  33902. /**
  33903. * Gets the material fill mode
  33904. */
  33905. get: function () {
  33906. return this._fillMode;
  33907. },
  33908. /**
  33909. * Sets the material fill mode
  33910. */
  33911. set: function (value) {
  33912. if (this._fillMode === value) {
  33913. return;
  33914. }
  33915. this._fillMode = value;
  33916. this.markAsDirty(Material.MiscDirtyFlag);
  33917. },
  33918. enumerable: true,
  33919. configurable: true
  33920. });
  33921. /**
  33922. * Returns a string representation of the current material
  33923. * @param fullDetails defines a boolean indicating which levels of logging is desired
  33924. * @returns a string with material information
  33925. */
  33926. Material.prototype.toString = function (fullDetails) {
  33927. var ret = "Name: " + this.name;
  33928. if (fullDetails) {
  33929. }
  33930. return ret;
  33931. };
  33932. /**
  33933. * Gets the class name of the material
  33934. * @returns a string with the class name of the material
  33935. */
  33936. Material.prototype.getClassName = function () {
  33937. return "Material";
  33938. };
  33939. Object.defineProperty(Material.prototype, "isFrozen", {
  33940. /**
  33941. * Specifies if updates for the material been locked
  33942. */
  33943. get: function () {
  33944. return this.checkReadyOnlyOnce;
  33945. },
  33946. enumerable: true,
  33947. configurable: true
  33948. });
  33949. /**
  33950. * Locks updates for the material
  33951. */
  33952. Material.prototype.freeze = function () {
  33953. this.checkReadyOnlyOnce = true;
  33954. };
  33955. /**
  33956. * Unlocks updates for the material
  33957. */
  33958. Material.prototype.unfreeze = function () {
  33959. this.checkReadyOnlyOnce = false;
  33960. };
  33961. /**
  33962. * Specifies if the material is ready to be used
  33963. * @param mesh defines the mesh to check
  33964. * @param useInstances specifies if instances should be used
  33965. * @returns a boolean indicating if the material is ready to be used
  33966. */
  33967. Material.prototype.isReady = function (mesh, useInstances) {
  33968. return true;
  33969. };
  33970. /**
  33971. * Specifies that the submesh is ready to be used
  33972. * @param mesh defines the mesh to check
  33973. * @param subMesh defines which submesh to check
  33974. * @param useInstances specifies that instances should be used
  33975. * @returns a boolean indicating that the submesh is ready or not
  33976. */
  33977. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33978. return false;
  33979. };
  33980. /**
  33981. * Returns the material effect
  33982. * @returns the effect associated with the material
  33983. */
  33984. Material.prototype.getEffect = function () {
  33985. return this._effect;
  33986. };
  33987. /**
  33988. * Returns the current scene
  33989. * @returns a Scene
  33990. */
  33991. Material.prototype.getScene = function () {
  33992. return this._scene;
  33993. };
  33994. /**
  33995. * Specifies if the material will require alpha blending
  33996. * @returns a boolean specifying if alpha blending is needed
  33997. */
  33998. Material.prototype.needAlphaBlending = function () {
  33999. return (this.alpha < 1.0);
  34000. };
  34001. /**
  34002. * Specifies if the mesh will require alpha blending
  34003. * @param mesh defines the mesh to check
  34004. * @returns a boolean specifying if alpha blending is needed for the mesh
  34005. */
  34006. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34007. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34008. };
  34009. /**
  34010. * Specifies if this material should be rendered in alpha test mode
  34011. * @returns a boolean specifying if an alpha test is needed.
  34012. */
  34013. Material.prototype.needAlphaTesting = function () {
  34014. return false;
  34015. };
  34016. /**
  34017. * Gets the texture used for the alpha test
  34018. * @returns the texture to use for alpha testing
  34019. */
  34020. Material.prototype.getAlphaTestTexture = function () {
  34021. return null;
  34022. };
  34023. /**
  34024. * Marks the material to indicate that it needs to be re-calculated
  34025. */
  34026. Material.prototype.markDirty = function () {
  34027. this._wasPreviouslyReady = false;
  34028. };
  34029. /** @ignore */
  34030. Material.prototype._preBind = function (effect, overrideOrientation) {
  34031. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34032. var engine = this._scene.getEngine();
  34033. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34034. var reverse = orientation === Material.ClockWiseSideOrientation;
  34035. engine.enableEffect(effect ? effect : this._effect);
  34036. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34037. return reverse;
  34038. };
  34039. /**
  34040. * Binds the material to the mesh
  34041. * @param world defines the world transformation matrix
  34042. * @param mesh defines the mesh to bind the material to
  34043. */
  34044. Material.prototype.bind = function (world, mesh) {
  34045. };
  34046. /**
  34047. * Binds the submesh to the material
  34048. * @param world defines the world transformation matrix
  34049. * @param mesh defines the mesh containing the submesh
  34050. * @param subMesh defines the submesh to bind the material to
  34051. */
  34052. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34053. };
  34054. /**
  34055. * Binds the world matrix to the material
  34056. * @param world defines the world transformation matrix
  34057. */
  34058. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34059. };
  34060. /**
  34061. * Binds the scene's uniform buffer to the effect.
  34062. * @param effect defines the effect to bind to the scene uniform buffer
  34063. * @param sceneUbo defines the uniform buffer storing scene data
  34064. */
  34065. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34066. sceneUbo.bindToEffect(effect, "Scene");
  34067. };
  34068. /**
  34069. * Binds the view matrix to the effect
  34070. * @param effect defines the effect to bind the view matrix to
  34071. */
  34072. Material.prototype.bindView = function (effect) {
  34073. if (!this._useUBO) {
  34074. effect.setMatrix("view", this.getScene().getViewMatrix());
  34075. }
  34076. else {
  34077. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34078. }
  34079. };
  34080. /**
  34081. * Binds the view projection matrix to the effect
  34082. * @param effect defines the effect to bind the view projection matrix to
  34083. */
  34084. Material.prototype.bindViewProjection = function (effect) {
  34085. if (!this._useUBO) {
  34086. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34087. }
  34088. else {
  34089. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34090. }
  34091. };
  34092. /**
  34093. * Specifies if material alpha testing should be turned on for the mesh
  34094. * @param mesh defines the mesh to check
  34095. */
  34096. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34097. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34098. };
  34099. /**
  34100. * Processes to execute after binding the material to a mesh
  34101. * @param mesh defines the rendered mesh
  34102. */
  34103. Material.prototype._afterBind = function (mesh) {
  34104. this._scene._cachedMaterial = this;
  34105. if (mesh) {
  34106. this._scene._cachedVisibility = mesh.visibility;
  34107. }
  34108. else {
  34109. this._scene._cachedVisibility = 1;
  34110. }
  34111. if (mesh) {
  34112. this.onBindObservable.notifyObservers(mesh);
  34113. }
  34114. if (this.disableDepthWrite) {
  34115. var engine = this._scene.getEngine();
  34116. this._cachedDepthWriteState = engine.getDepthWrite();
  34117. engine.setDepthWrite(false);
  34118. }
  34119. };
  34120. /**
  34121. * Unbinds the material from the mesh
  34122. */
  34123. Material.prototype.unbind = function () {
  34124. this.onUnBindObservable.notifyObservers(this);
  34125. if (this.disableDepthWrite) {
  34126. var engine = this._scene.getEngine();
  34127. engine.setDepthWrite(this._cachedDepthWriteState);
  34128. }
  34129. };
  34130. /**
  34131. * Gets the active textures from the material
  34132. * @returns an array of textures
  34133. */
  34134. Material.prototype.getActiveTextures = function () {
  34135. return [];
  34136. };
  34137. /**
  34138. * Specifies if the material uses a texture
  34139. * @param texture defines the texture to check against the material
  34140. * @returns a boolean specifying if the material uses the texture
  34141. */
  34142. Material.prototype.hasTexture = function (texture) {
  34143. return false;
  34144. };
  34145. /**
  34146. * Makes a duplicate of the material, and gives it a new name
  34147. * @param name defines the new name for the duplicated material
  34148. * @returns the cloned material
  34149. */
  34150. Material.prototype.clone = function (name) {
  34151. return null;
  34152. };
  34153. /**
  34154. * Gets the meshes bound to the material
  34155. * @returns an array of meshes bound to the material
  34156. */
  34157. Material.prototype.getBindedMeshes = function () {
  34158. var result = new Array();
  34159. for (var index = 0; index < this._scene.meshes.length; index++) {
  34160. var mesh = this._scene.meshes[index];
  34161. if (mesh.material === this) {
  34162. result.push(mesh);
  34163. }
  34164. }
  34165. return result;
  34166. };
  34167. /**
  34168. * Force shader compilation
  34169. * @param mesh defines the mesh associated with this material
  34170. * @param onCompiled defines a function to execute once the material is compiled
  34171. * @param options defines the options to configure the compilation
  34172. */
  34173. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34174. var _this = this;
  34175. var localOptions = __assign({ clipPlane: false }, options);
  34176. var subMesh = new BABYLON.BaseSubMesh();
  34177. var scene = this.getScene();
  34178. var checkReady = function () {
  34179. if (!_this._scene || !_this._scene.getEngine()) {
  34180. return;
  34181. }
  34182. if (subMesh._materialDefines) {
  34183. subMesh._materialDefines._renderId = -1;
  34184. }
  34185. var clipPlaneState = scene.clipPlane;
  34186. if (localOptions.clipPlane) {
  34187. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34188. }
  34189. if (_this.storeEffectOnSubMeshes) {
  34190. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34191. if (onCompiled) {
  34192. onCompiled(_this);
  34193. }
  34194. }
  34195. else {
  34196. setTimeout(checkReady, 16);
  34197. }
  34198. }
  34199. else {
  34200. if (_this.isReady(mesh)) {
  34201. if (onCompiled) {
  34202. onCompiled(_this);
  34203. }
  34204. }
  34205. else {
  34206. setTimeout(checkReady, 16);
  34207. }
  34208. }
  34209. if (localOptions.clipPlane) {
  34210. scene.clipPlane = clipPlaneState;
  34211. }
  34212. };
  34213. checkReady();
  34214. };
  34215. /**
  34216. * Force shader compilation
  34217. * @param mesh defines the mesh that will use this material
  34218. * @param options defines additional options for compiling the shaders
  34219. * @returns a promise that resolves when the compilation completes
  34220. */
  34221. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34222. var _this = this;
  34223. return new Promise(function (resolve) {
  34224. _this.forceCompilation(mesh, function () {
  34225. resolve();
  34226. }, options);
  34227. });
  34228. };
  34229. /**
  34230. * Marks a define in the material to indicate that it needs to be re-computed
  34231. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34232. */
  34233. Material.prototype.markAsDirty = function (flag) {
  34234. if (flag & Material.TextureDirtyFlag) {
  34235. this._markAllSubMeshesAsTexturesDirty();
  34236. }
  34237. if (flag & Material.LightDirtyFlag) {
  34238. this._markAllSubMeshesAsLightsDirty();
  34239. }
  34240. if (flag & Material.FresnelDirtyFlag) {
  34241. this._markAllSubMeshesAsFresnelDirty();
  34242. }
  34243. if (flag & Material.AttributesDirtyFlag) {
  34244. this._markAllSubMeshesAsAttributesDirty();
  34245. }
  34246. if (flag & Material.MiscDirtyFlag) {
  34247. this._markAllSubMeshesAsMiscDirty();
  34248. }
  34249. this.getScene().resetCachedMaterial();
  34250. };
  34251. /**
  34252. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34253. * @param func defines a function which checks material defines against the submeshes
  34254. */
  34255. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34256. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34257. var mesh = _a[_i];
  34258. if (!mesh.subMeshes) {
  34259. continue;
  34260. }
  34261. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34262. var subMesh = _c[_b];
  34263. if (subMesh.getMaterial() !== this) {
  34264. continue;
  34265. }
  34266. if (!subMesh._materialDefines) {
  34267. continue;
  34268. }
  34269. func(subMesh._materialDefines);
  34270. }
  34271. }
  34272. };
  34273. /**
  34274. * Indicates that image processing needs to be re-calculated for all submeshes
  34275. */
  34276. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34277. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34278. };
  34279. /**
  34280. * Indicates that textures need to be re-calculated for all submeshes
  34281. */
  34282. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34283. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34284. };
  34285. /**
  34286. * Indicates that fresnel needs to be re-calculated for all submeshes
  34287. */
  34288. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34289. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34290. };
  34291. /**
  34292. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34293. */
  34294. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34295. this._markAllSubMeshesAsDirty(function (defines) {
  34296. defines.markAsFresnelDirty();
  34297. defines.markAsMiscDirty();
  34298. });
  34299. };
  34300. /**
  34301. * Indicates that lights need to be re-calculated for all submeshes
  34302. */
  34303. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34304. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34305. };
  34306. /**
  34307. * Indicates that attributes need to be re-calculated for all submeshes
  34308. */
  34309. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34310. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34311. };
  34312. /**
  34313. * Indicates that misc needs to be re-calculated for all submeshes
  34314. */
  34315. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34316. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34317. };
  34318. /**
  34319. * Indicates that textures and misc need to be re-calculated for all submeshes
  34320. */
  34321. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34322. this._markAllSubMeshesAsDirty(function (defines) {
  34323. defines.markAsTexturesDirty();
  34324. defines.markAsMiscDirty();
  34325. });
  34326. };
  34327. /**
  34328. * Disposes the material
  34329. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34330. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34331. */
  34332. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34333. // Animations
  34334. this.getScene().stopAnimation(this);
  34335. this.getScene().freeProcessedMaterials();
  34336. // Remove from scene
  34337. var index = this._scene.materials.indexOf(this);
  34338. if (index >= 0) {
  34339. this._scene.materials.splice(index, 1);
  34340. }
  34341. // Remove from meshes
  34342. for (index = 0; index < this._scene.meshes.length; index++) {
  34343. var mesh = this._scene.meshes[index];
  34344. if (mesh.material === this) {
  34345. mesh.material = null;
  34346. if (mesh.geometry) {
  34347. var geometry = (mesh.geometry);
  34348. if (this.storeEffectOnSubMeshes) {
  34349. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34350. var subMesh = _a[_i];
  34351. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34352. if (forceDisposeEffect && subMesh._materialEffect) {
  34353. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34354. }
  34355. }
  34356. }
  34357. else {
  34358. geometry._releaseVertexArrayObject(this._effect);
  34359. }
  34360. }
  34361. }
  34362. }
  34363. this._uniformBuffer.dispose();
  34364. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34365. if (forceDisposeEffect && this._effect) {
  34366. if (!this.storeEffectOnSubMeshes) {
  34367. this._scene.getEngine()._releaseEffect(this._effect);
  34368. }
  34369. this._effect = null;
  34370. }
  34371. // Callback
  34372. this.onDisposeObservable.notifyObservers(this);
  34373. this.onDisposeObservable.clear();
  34374. this.onBindObservable.clear();
  34375. this.onUnBindObservable.clear();
  34376. };
  34377. /**
  34378. * Serializes this material
  34379. * @returns the serialized material object
  34380. */
  34381. Material.prototype.serialize = function () {
  34382. return BABYLON.SerializationHelper.Serialize(this);
  34383. };
  34384. /**
  34385. * Creates a MultiMaterial from parsed MultiMaterial data.
  34386. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  34387. * @param scene defines the hosting scene
  34388. * @returns a new MultiMaterial
  34389. */
  34390. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  34391. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  34392. multiMaterial.id = parsedMultiMaterial.id;
  34393. if (BABYLON.Tags) {
  34394. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  34395. }
  34396. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  34397. var subMatId = parsedMultiMaterial.materials[matIndex];
  34398. if (subMatId) {
  34399. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  34400. }
  34401. else {
  34402. multiMaterial.subMaterials.push(null);
  34403. }
  34404. }
  34405. return multiMaterial;
  34406. };
  34407. /**
  34408. * Creates a material from parsed material data
  34409. * @param parsedMaterial defines parsed material data
  34410. * @param scene defines the hosting scene
  34411. * @param rootUrl defines the root URL to use to load textures
  34412. * @returns a new material
  34413. */
  34414. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  34415. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  34416. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  34417. }
  34418. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  34419. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  34420. if (!BABYLON.LegacyPBRMaterial) {
  34421. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  34422. return;
  34423. }
  34424. }
  34425. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  34426. return materialType.Parse(parsedMaterial, scene, rootUrl);
  34427. ;
  34428. };
  34429. // Triangle views
  34430. Material._TriangleFillMode = 0;
  34431. Material._WireFrameFillMode = 1;
  34432. Material._PointFillMode = 2;
  34433. // Draw modes
  34434. Material._PointListDrawMode = 3;
  34435. Material._LineListDrawMode = 4;
  34436. Material._LineLoopDrawMode = 5;
  34437. Material._LineStripDrawMode = 6;
  34438. Material._TriangleStripDrawMode = 7;
  34439. Material._TriangleFanDrawMode = 8;
  34440. /**
  34441. * Stores the clock-wise side orientation
  34442. */
  34443. Material._ClockWiseSideOrientation = 0;
  34444. /**
  34445. * Stores the counter clock-wise side orientation
  34446. */
  34447. Material._CounterClockWiseSideOrientation = 1;
  34448. /**
  34449. * The dirty texture flag value
  34450. */
  34451. Material._TextureDirtyFlag = 1;
  34452. /**
  34453. * The dirty light flag value
  34454. */
  34455. Material._LightDirtyFlag = 2;
  34456. /**
  34457. * The dirty fresnel flag value
  34458. */
  34459. Material._FresnelDirtyFlag = 4;
  34460. /**
  34461. * The dirty attribute flag value
  34462. */
  34463. Material._AttributesDirtyFlag = 8;
  34464. /**
  34465. * The dirty misc flag value
  34466. */
  34467. Material._MiscDirtyFlag = 16;
  34468. __decorate([
  34469. BABYLON.serialize()
  34470. ], Material.prototype, "id", void 0);
  34471. __decorate([
  34472. BABYLON.serialize()
  34473. ], Material.prototype, "name", void 0);
  34474. __decorate([
  34475. BABYLON.serialize()
  34476. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  34477. __decorate([
  34478. BABYLON.serialize()
  34479. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  34480. __decorate([
  34481. BABYLON.serialize()
  34482. ], Material.prototype, "state", void 0);
  34483. __decorate([
  34484. BABYLON.serialize("alpha")
  34485. ], Material.prototype, "_alpha", void 0);
  34486. __decorate([
  34487. BABYLON.serialize("backFaceCulling")
  34488. ], Material.prototype, "_backFaceCulling", void 0);
  34489. __decorate([
  34490. BABYLON.serialize()
  34491. ], Material.prototype, "sideOrientation", void 0);
  34492. __decorate([
  34493. BABYLON.serialize("alphaMode")
  34494. ], Material.prototype, "_alphaMode", void 0);
  34495. __decorate([
  34496. BABYLON.serialize()
  34497. ], Material.prototype, "_needDepthPrePass", void 0);
  34498. __decorate([
  34499. BABYLON.serialize()
  34500. ], Material.prototype, "disableDepthWrite", void 0);
  34501. __decorate([
  34502. BABYLON.serialize()
  34503. ], Material.prototype, "forceDepthWrite", void 0);
  34504. __decorate([
  34505. BABYLON.serialize()
  34506. ], Material.prototype, "separateCullingPass", void 0);
  34507. __decorate([
  34508. BABYLON.serialize("fogEnabled")
  34509. ], Material.prototype, "_fogEnabled", void 0);
  34510. __decorate([
  34511. BABYLON.serialize()
  34512. ], Material.prototype, "pointSize", void 0);
  34513. __decorate([
  34514. BABYLON.serialize()
  34515. ], Material.prototype, "zOffset", void 0);
  34516. __decorate([
  34517. BABYLON.serialize()
  34518. ], Material.prototype, "wireframe", null);
  34519. __decorate([
  34520. BABYLON.serialize()
  34521. ], Material.prototype, "pointsCloud", null);
  34522. __decorate([
  34523. BABYLON.serialize()
  34524. ], Material.prototype, "fillMode", null);
  34525. return Material;
  34526. }());
  34527. BABYLON.Material = Material;
  34528. })(BABYLON || (BABYLON = {}));
  34529. //# sourceMappingURL=babylon.material.js.map
  34530. "use strict";
  34531. var BABYLON;
  34532. (function (BABYLON) {
  34533. var UniformBuffer = /** @class */ (function () {
  34534. /**
  34535. * Uniform buffer objects.
  34536. *
  34537. * Handles blocks of uniform on the GPU.
  34538. *
  34539. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  34540. *
  34541. * For more information, please refer to :
  34542. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  34543. */
  34544. function UniformBuffer(engine, data, dynamic) {
  34545. this._engine = engine;
  34546. this._noUBO = !engine.supportsUniformBuffers;
  34547. this._dynamic = dynamic;
  34548. this._data = data || [];
  34549. this._uniformLocations = {};
  34550. this._uniformSizes = {};
  34551. this._uniformLocationPointer = 0;
  34552. this._needSync = false;
  34553. if (this._noUBO) {
  34554. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  34555. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  34556. this.updateFloat = this._updateFloatForEffect;
  34557. this.updateFloat2 = this._updateFloat2ForEffect;
  34558. this.updateFloat3 = this._updateFloat3ForEffect;
  34559. this.updateFloat4 = this._updateFloat4ForEffect;
  34560. this.updateMatrix = this._updateMatrixForEffect;
  34561. this.updateVector3 = this._updateVector3ForEffect;
  34562. this.updateVector4 = this._updateVector4ForEffect;
  34563. this.updateColor3 = this._updateColor3ForEffect;
  34564. this.updateColor4 = this._updateColor4ForEffect;
  34565. }
  34566. else {
  34567. this._engine._uniformBuffers.push(this);
  34568. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  34569. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  34570. this.updateFloat = this._updateFloatForUniform;
  34571. this.updateFloat2 = this._updateFloat2ForUniform;
  34572. this.updateFloat3 = this._updateFloat3ForUniform;
  34573. this.updateFloat4 = this._updateFloat4ForUniform;
  34574. this.updateMatrix = this._updateMatrixForUniform;
  34575. this.updateVector3 = this._updateVector3ForUniform;
  34576. this.updateVector4 = this._updateVector4ForUniform;
  34577. this.updateColor3 = this._updateColor3ForUniform;
  34578. this.updateColor4 = this._updateColor4ForUniform;
  34579. }
  34580. }
  34581. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  34582. // Properties
  34583. /**
  34584. * Indicates if the buffer is using the WebGL2 UBO implementation,
  34585. * or just falling back on setUniformXXX calls.
  34586. */
  34587. get: function () {
  34588. return !this._noUBO;
  34589. },
  34590. enumerable: true,
  34591. configurable: true
  34592. });
  34593. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  34594. /**
  34595. * Indicates if the WebGL underlying uniform buffer is in sync
  34596. * with the javascript cache data.
  34597. */
  34598. get: function () {
  34599. return !this._needSync;
  34600. },
  34601. enumerable: true,
  34602. configurable: true
  34603. });
  34604. /**
  34605. * Indicates if the WebGL underlying uniform buffer is dynamic.
  34606. * Also, a dynamic UniformBuffer will disable cache verification and always
  34607. * update the underlying WebGL uniform buffer to the GPU.
  34608. */
  34609. UniformBuffer.prototype.isDynamic = function () {
  34610. return this._dynamic !== undefined;
  34611. };
  34612. /**
  34613. * The data cache on JS side.
  34614. */
  34615. UniformBuffer.prototype.getData = function () {
  34616. return this._bufferData;
  34617. };
  34618. /**
  34619. * The underlying WebGL Uniform buffer.
  34620. */
  34621. UniformBuffer.prototype.getBuffer = function () {
  34622. return this._buffer;
  34623. };
  34624. /**
  34625. * std140 layout specifies how to align data within an UBO structure.
  34626. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  34627. * for specs.
  34628. */
  34629. UniformBuffer.prototype._fillAlignment = function (size) {
  34630. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  34631. // and 4x4 matrices
  34632. // TODO : change if other types are used
  34633. var alignment;
  34634. if (size <= 2) {
  34635. alignment = size;
  34636. }
  34637. else {
  34638. alignment = 4;
  34639. }
  34640. if ((this._uniformLocationPointer % alignment) !== 0) {
  34641. var oldPointer = this._uniformLocationPointer;
  34642. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  34643. var diff = this._uniformLocationPointer - oldPointer;
  34644. for (var i = 0; i < diff; i++) {
  34645. this._data.push(0);
  34646. }
  34647. }
  34648. };
  34649. /**
  34650. * Adds an uniform in the buffer.
  34651. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  34652. * for the layout to be correct !
  34653. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34654. * @param {number|number[]} size Data size, or data directly.
  34655. */
  34656. UniformBuffer.prototype.addUniform = function (name, size) {
  34657. if (this._noUBO) {
  34658. return;
  34659. }
  34660. if (this._uniformLocations[name] !== undefined) {
  34661. // Already existing uniform
  34662. return;
  34663. }
  34664. // This function must be called in the order of the shader layout !
  34665. // size can be the size of the uniform, or data directly
  34666. var data;
  34667. if (size instanceof Array) {
  34668. data = size;
  34669. size = data.length;
  34670. }
  34671. else {
  34672. size = size;
  34673. data = [];
  34674. // Fill with zeros
  34675. for (var i = 0; i < size; i++) {
  34676. data.push(0);
  34677. }
  34678. }
  34679. this._fillAlignment(size);
  34680. this._uniformSizes[name] = size;
  34681. this._uniformLocations[name] = this._uniformLocationPointer;
  34682. this._uniformLocationPointer += size;
  34683. for (var i = 0; i < size; i++) {
  34684. this._data.push(data[i]);
  34685. }
  34686. this._needSync = true;
  34687. };
  34688. /**
  34689. * Wrapper for addUniform.
  34690. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34691. * @param {Matrix} mat A 4x4 matrix.
  34692. */
  34693. UniformBuffer.prototype.addMatrix = function (name, mat) {
  34694. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  34695. };
  34696. /**
  34697. * Wrapper for addUniform.
  34698. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34699. * @param {number} x
  34700. * @param {number} y
  34701. */
  34702. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  34703. var temp = [x, y];
  34704. this.addUniform(name, temp);
  34705. };
  34706. /**
  34707. * Wrapper for addUniform.
  34708. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34709. * @param {number} x
  34710. * @param {number} y
  34711. * @param {number} z
  34712. */
  34713. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  34714. var temp = [x, y, z];
  34715. this.addUniform(name, temp);
  34716. };
  34717. /**
  34718. * Wrapper for addUniform.
  34719. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34720. * @param {Color3} color
  34721. */
  34722. UniformBuffer.prototype.addColor3 = function (name, color) {
  34723. var temp = new Array();
  34724. color.toArray(temp);
  34725. this.addUniform(name, temp);
  34726. };
  34727. /**
  34728. * Wrapper for addUniform.
  34729. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34730. * @param {Color3} color
  34731. * @param {number} alpha
  34732. */
  34733. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  34734. var temp = new Array();
  34735. color.toArray(temp);
  34736. temp.push(alpha);
  34737. this.addUniform(name, temp);
  34738. };
  34739. /**
  34740. * Wrapper for addUniform.
  34741. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34742. * @param {Vector3} vector
  34743. */
  34744. UniformBuffer.prototype.addVector3 = function (name, vector) {
  34745. var temp = new Array();
  34746. vector.toArray(temp);
  34747. this.addUniform(name, temp);
  34748. };
  34749. /**
  34750. * Wrapper for addUniform.
  34751. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34752. */
  34753. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  34754. this.addUniform(name, 12);
  34755. };
  34756. /**
  34757. * Wrapper for addUniform.
  34758. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  34759. */
  34760. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  34761. this.addUniform(name, 8);
  34762. };
  34763. /**
  34764. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  34765. */
  34766. UniformBuffer.prototype.create = function () {
  34767. if (this._noUBO) {
  34768. return;
  34769. }
  34770. if (this._buffer) {
  34771. return; // nothing to do
  34772. }
  34773. // See spec, alignment must be filled as a vec4
  34774. this._fillAlignment(4);
  34775. this._bufferData = new Float32Array(this._data);
  34776. this._rebuild();
  34777. this._needSync = true;
  34778. };
  34779. UniformBuffer.prototype._rebuild = function () {
  34780. if (this._noUBO) {
  34781. return;
  34782. }
  34783. if (this._dynamic) {
  34784. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  34785. }
  34786. else {
  34787. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  34788. }
  34789. };
  34790. /**
  34791. * Updates the WebGL Uniform Buffer on the GPU.
  34792. * If the `dynamic` flag is set to true, no cache comparison is done.
  34793. * Otherwise, the buffer will be updated only if the cache differs.
  34794. */
  34795. UniformBuffer.prototype.update = function () {
  34796. if (!this._buffer) {
  34797. this.create();
  34798. return;
  34799. }
  34800. if (!this._dynamic && !this._needSync) {
  34801. return;
  34802. }
  34803. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  34804. this._needSync = false;
  34805. };
  34806. /**
  34807. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  34808. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  34809. * @param {number[]|Float32Array} data Flattened data
  34810. * @param {number} size Size of the data.
  34811. */
  34812. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  34813. var location = this._uniformLocations[uniformName];
  34814. if (location === undefined) {
  34815. if (this._buffer) {
  34816. // Cannot add an uniform if the buffer is already created
  34817. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  34818. return;
  34819. }
  34820. this.addUniform(uniformName, size);
  34821. location = this._uniformLocations[uniformName];
  34822. }
  34823. if (!this._buffer) {
  34824. this.create();
  34825. }
  34826. if (!this._dynamic) {
  34827. // Cache for static uniform buffers
  34828. var changed = false;
  34829. for (var i = 0; i < size; i++) {
  34830. if (this._bufferData[location + i] !== data[i]) {
  34831. changed = true;
  34832. this._bufferData[location + i] = data[i];
  34833. }
  34834. }
  34835. this._needSync = this._needSync || changed;
  34836. }
  34837. else {
  34838. // No cache for dynamic
  34839. for (var i = 0; i < size; i++) {
  34840. this._bufferData[location + i] = data[i];
  34841. }
  34842. }
  34843. };
  34844. // Update methods
  34845. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  34846. // To match std140, matrix must be realigned
  34847. for (var i = 0; i < 3; i++) {
  34848. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  34849. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  34850. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  34851. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  34852. }
  34853. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  34854. };
  34855. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  34856. this._currentEffect.setMatrix3x3(name, matrix);
  34857. };
  34858. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  34859. this._currentEffect.setMatrix2x2(name, matrix);
  34860. };
  34861. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  34862. // To match std140, matrix must be realigned
  34863. for (var i = 0; i < 2; i++) {
  34864. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  34865. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  34866. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  34867. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  34868. }
  34869. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  34870. };
  34871. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  34872. this._currentEffect.setFloat(name, x);
  34873. };
  34874. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  34875. UniformBuffer._tempBuffer[0] = x;
  34876. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  34877. };
  34878. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  34879. if (suffix === void 0) { suffix = ""; }
  34880. this._currentEffect.setFloat2(name + suffix, x, y);
  34881. };
  34882. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  34883. if (suffix === void 0) { suffix = ""; }
  34884. UniformBuffer._tempBuffer[0] = x;
  34885. UniformBuffer._tempBuffer[1] = y;
  34886. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  34887. };
  34888. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  34889. if (suffix === void 0) { suffix = ""; }
  34890. this._currentEffect.setFloat3(name + suffix, x, y, z);
  34891. };
  34892. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  34893. if (suffix === void 0) { suffix = ""; }
  34894. UniformBuffer._tempBuffer[0] = x;
  34895. UniformBuffer._tempBuffer[1] = y;
  34896. UniformBuffer._tempBuffer[2] = z;
  34897. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  34898. };
  34899. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  34900. if (suffix === void 0) { suffix = ""; }
  34901. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  34902. };
  34903. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  34904. if (suffix === void 0) { suffix = ""; }
  34905. UniformBuffer._tempBuffer[0] = x;
  34906. UniformBuffer._tempBuffer[1] = y;
  34907. UniformBuffer._tempBuffer[2] = z;
  34908. UniformBuffer._tempBuffer[3] = w;
  34909. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  34910. };
  34911. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  34912. this._currentEffect.setMatrix(name, mat);
  34913. };
  34914. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  34915. this.updateUniform(name, mat.toArray(), 16);
  34916. };
  34917. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  34918. this._currentEffect.setVector3(name, vector);
  34919. };
  34920. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  34921. vector.toArray(UniformBuffer._tempBuffer);
  34922. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  34923. };
  34924. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  34925. this._currentEffect.setVector4(name, vector);
  34926. };
  34927. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  34928. vector.toArray(UniformBuffer._tempBuffer);
  34929. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  34930. };
  34931. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  34932. if (suffix === void 0) { suffix = ""; }
  34933. this._currentEffect.setColor3(name + suffix, color);
  34934. };
  34935. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  34936. if (suffix === void 0) { suffix = ""; }
  34937. color.toArray(UniformBuffer._tempBuffer);
  34938. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  34939. };
  34940. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  34941. if (suffix === void 0) { suffix = ""; }
  34942. this._currentEffect.setColor4(name + suffix, color, alpha);
  34943. };
  34944. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  34945. if (suffix === void 0) { suffix = ""; }
  34946. color.toArray(UniformBuffer._tempBuffer);
  34947. UniformBuffer._tempBuffer[3] = alpha;
  34948. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  34949. };
  34950. /**
  34951. * Sets a sampler uniform on the effect.
  34952. * @param {string} name Name of the sampler.
  34953. * @param {Texture} texture
  34954. */
  34955. UniformBuffer.prototype.setTexture = function (name, texture) {
  34956. this._currentEffect.setTexture(name, texture);
  34957. };
  34958. /**
  34959. * Directly updates the value of the uniform in the cache AND on the GPU.
  34960. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  34961. * @param {number[]|Float32Array} data Flattened data
  34962. */
  34963. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  34964. this.updateUniform(uniformName, data, data.length);
  34965. this.update();
  34966. };
  34967. /**
  34968. * Binds this uniform buffer to an effect.
  34969. * @param {Effect} effect
  34970. * @param {string} name Name of the uniform block in the shader.
  34971. */
  34972. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  34973. this._currentEffect = effect;
  34974. if (this._noUBO || !this._buffer) {
  34975. return;
  34976. }
  34977. effect.bindUniformBuffer(this._buffer, name);
  34978. };
  34979. /**
  34980. * Disposes the uniform buffer.
  34981. */
  34982. UniformBuffer.prototype.dispose = function () {
  34983. if (this._noUBO) {
  34984. return;
  34985. }
  34986. var index = this._engine._uniformBuffers.indexOf(this);
  34987. if (index !== -1) {
  34988. this._engine._uniformBuffers.splice(index, 1);
  34989. }
  34990. if (!this._buffer) {
  34991. return;
  34992. }
  34993. if (this._engine._releaseBuffer(this._buffer)) {
  34994. this._buffer = null;
  34995. }
  34996. };
  34997. // Pool for avoiding memory leaks
  34998. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  34999. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35000. return UniformBuffer;
  35001. }());
  35002. BABYLON.UniformBuffer = UniformBuffer;
  35003. })(BABYLON || (BABYLON = {}));
  35004. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35005. "use strict";
  35006. var BABYLON;
  35007. (function (BABYLON) {
  35008. var VertexData = /** @class */ (function () {
  35009. function VertexData() {
  35010. }
  35011. VertexData.prototype.set = function (data, kind) {
  35012. switch (kind) {
  35013. case BABYLON.VertexBuffer.PositionKind:
  35014. this.positions = data;
  35015. break;
  35016. case BABYLON.VertexBuffer.NormalKind:
  35017. this.normals = data;
  35018. break;
  35019. case BABYLON.VertexBuffer.TangentKind:
  35020. this.tangents = data;
  35021. break;
  35022. case BABYLON.VertexBuffer.UVKind:
  35023. this.uvs = data;
  35024. break;
  35025. case BABYLON.VertexBuffer.UV2Kind:
  35026. this.uvs2 = data;
  35027. break;
  35028. case BABYLON.VertexBuffer.UV3Kind:
  35029. this.uvs3 = data;
  35030. break;
  35031. case BABYLON.VertexBuffer.UV4Kind:
  35032. this.uvs4 = data;
  35033. break;
  35034. case BABYLON.VertexBuffer.UV5Kind:
  35035. this.uvs5 = data;
  35036. break;
  35037. case BABYLON.VertexBuffer.UV6Kind:
  35038. this.uvs6 = data;
  35039. break;
  35040. case BABYLON.VertexBuffer.ColorKind:
  35041. this.colors = data;
  35042. break;
  35043. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35044. this.matricesIndices = data;
  35045. break;
  35046. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35047. this.matricesWeights = data;
  35048. break;
  35049. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35050. this.matricesIndicesExtra = data;
  35051. break;
  35052. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35053. this.matricesWeightsExtra = data;
  35054. break;
  35055. }
  35056. };
  35057. /**
  35058. * Associates the vertexData to the passed Mesh.
  35059. * Sets it as updatable or not (default `false`).
  35060. * Returns the VertexData.
  35061. */
  35062. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35063. this._applyTo(mesh, updatable);
  35064. return this;
  35065. };
  35066. /**
  35067. * Associates the vertexData to the passed Geometry.
  35068. * Sets it as updatable or not (default `false`).
  35069. * Returns the VertexData.
  35070. */
  35071. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35072. this._applyTo(geometry, updatable);
  35073. return this;
  35074. };
  35075. /**
  35076. * Updates the associated mesh.
  35077. * Returns the VertexData.
  35078. */
  35079. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35080. this._update(mesh);
  35081. return this;
  35082. };
  35083. /**
  35084. * Updates the associated geometry.
  35085. * Returns the VertexData.
  35086. */
  35087. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35088. this._update(geometry);
  35089. return this;
  35090. };
  35091. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35092. if (updatable === void 0) { updatable = false; }
  35093. if (this.positions) {
  35094. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35095. }
  35096. if (this.normals) {
  35097. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35098. }
  35099. if (this.tangents) {
  35100. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35101. }
  35102. if (this.uvs) {
  35103. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35104. }
  35105. if (this.uvs2) {
  35106. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35107. }
  35108. if (this.uvs3) {
  35109. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35110. }
  35111. if (this.uvs4) {
  35112. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35113. }
  35114. if (this.uvs5) {
  35115. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35116. }
  35117. if (this.uvs6) {
  35118. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35119. }
  35120. if (this.colors) {
  35121. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35122. }
  35123. if (this.matricesIndices) {
  35124. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35125. }
  35126. if (this.matricesWeights) {
  35127. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35128. }
  35129. if (this.matricesIndicesExtra) {
  35130. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35131. }
  35132. if (this.matricesWeightsExtra) {
  35133. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35134. }
  35135. if (this.indices) {
  35136. meshOrGeometry.setIndices(this.indices, null, updatable);
  35137. }
  35138. return this;
  35139. };
  35140. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35141. if (this.positions) {
  35142. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35143. }
  35144. if (this.normals) {
  35145. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35146. }
  35147. if (this.tangents) {
  35148. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35149. }
  35150. if (this.uvs) {
  35151. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35152. }
  35153. if (this.uvs2) {
  35154. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35155. }
  35156. if (this.uvs3) {
  35157. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35158. }
  35159. if (this.uvs4) {
  35160. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35161. }
  35162. if (this.uvs5) {
  35163. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35164. }
  35165. if (this.uvs6) {
  35166. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35167. }
  35168. if (this.colors) {
  35169. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35170. }
  35171. if (this.matricesIndices) {
  35172. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35173. }
  35174. if (this.matricesWeights) {
  35175. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35176. }
  35177. if (this.matricesIndicesExtra) {
  35178. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35179. }
  35180. if (this.matricesWeightsExtra) {
  35181. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35182. }
  35183. if (this.indices) {
  35184. meshOrGeometry.setIndices(this.indices, null);
  35185. }
  35186. return this;
  35187. };
  35188. /**
  35189. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  35190. * Returns the VertexData.
  35191. */
  35192. VertexData.prototype.transform = function (matrix) {
  35193. var transformed = BABYLON.Vector3.Zero();
  35194. var index;
  35195. if (this.positions) {
  35196. var position = BABYLON.Vector3.Zero();
  35197. for (index = 0; index < this.positions.length; index += 3) {
  35198. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35199. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35200. this.positions[index] = transformed.x;
  35201. this.positions[index + 1] = transformed.y;
  35202. this.positions[index + 2] = transformed.z;
  35203. }
  35204. }
  35205. if (this.normals) {
  35206. var normal = BABYLON.Vector3.Zero();
  35207. for (index = 0; index < this.normals.length; index += 3) {
  35208. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35209. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35210. this.normals[index] = transformed.x;
  35211. this.normals[index + 1] = transformed.y;
  35212. this.normals[index + 2] = transformed.z;
  35213. }
  35214. }
  35215. if (this.tangents) {
  35216. var tangent = BABYLON.Vector4.Zero();
  35217. var tangentTransformed = BABYLON.Vector4.Zero();
  35218. for (index = 0; index < this.tangents.length; index += 4) {
  35219. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35220. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35221. this.tangents[index] = tangentTransformed.x;
  35222. this.tangents[index + 1] = tangentTransformed.y;
  35223. this.tangents[index + 2] = tangentTransformed.z;
  35224. this.tangents[index + 3] = tangentTransformed.w;
  35225. }
  35226. }
  35227. return this;
  35228. };
  35229. /**
  35230. * Merges the passed VertexData into the current one.
  35231. * Returns the modified VertexData.
  35232. */
  35233. VertexData.prototype.merge = function (other) {
  35234. this._validate();
  35235. other._validate();
  35236. if (!this.normals !== !other.normals ||
  35237. !this.tangents !== !other.tangents ||
  35238. !this.uvs !== !other.uvs ||
  35239. !this.uvs2 !== !other.uvs2 ||
  35240. !this.uvs3 !== !other.uvs3 ||
  35241. !this.uvs4 !== !other.uvs4 ||
  35242. !this.uvs5 !== !other.uvs5 ||
  35243. !this.uvs6 !== !other.uvs6 ||
  35244. !this.colors !== !other.colors ||
  35245. !this.matricesIndices !== !other.matricesIndices ||
  35246. !this.matricesWeights !== !other.matricesWeights ||
  35247. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35248. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35249. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35250. }
  35251. if (other.indices) {
  35252. if (!this.indices) {
  35253. this.indices = [];
  35254. }
  35255. var offset = this.positions ? this.positions.length / 3 : 0;
  35256. for (var index = 0; index < other.indices.length; index++) {
  35257. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35258. this.indices.push(other.indices[index] + offset);
  35259. }
  35260. }
  35261. this.positions = this._mergeElement(this.positions, other.positions);
  35262. this.normals = this._mergeElement(this.normals, other.normals);
  35263. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35264. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35265. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35266. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35267. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35268. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35269. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35270. this.colors = this._mergeElement(this.colors, other.colors);
  35271. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35272. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35273. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35274. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35275. return this;
  35276. };
  35277. VertexData.prototype._mergeElement = function (source, other) {
  35278. if (!source) {
  35279. return other;
  35280. }
  35281. if (!other) {
  35282. return source;
  35283. }
  35284. var len = other.length + source.length;
  35285. var isSrcTypedArray = source instanceof Float32Array;
  35286. var isOthTypedArray = other instanceof Float32Array;
  35287. // use non-loop method when the source is Float32Array
  35288. if (isSrcTypedArray) {
  35289. var ret32 = new Float32Array(len);
  35290. ret32.set(source);
  35291. ret32.set(other, source.length);
  35292. return ret32;
  35293. // source is number[], when other is also use concat
  35294. }
  35295. else if (!isOthTypedArray) {
  35296. return source.concat(other);
  35297. // source is a number[], but other is a Float32Array, loop required
  35298. }
  35299. else {
  35300. var ret = source.slice(0); // copy source to a separate array
  35301. for (var i = 0, len = other.length; i < len; i++) {
  35302. ret.push(other[i]);
  35303. }
  35304. return ret;
  35305. }
  35306. };
  35307. VertexData.prototype._validate = function () {
  35308. if (!this.positions) {
  35309. throw new Error("Positions are required");
  35310. }
  35311. var getElementCount = function (kind, values) {
  35312. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35313. if ((values.length % stride) !== 0) {
  35314. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35315. }
  35316. return values.length / stride;
  35317. };
  35318. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35319. var validateElementCount = function (kind, values) {
  35320. var elementCount = getElementCount(kind, values);
  35321. if (elementCount !== positionsElementCount) {
  35322. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35323. }
  35324. };
  35325. if (this.normals)
  35326. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35327. if (this.tangents)
  35328. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35329. if (this.uvs)
  35330. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35331. if (this.uvs2)
  35332. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35333. if (this.uvs3)
  35334. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35335. if (this.uvs4)
  35336. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35337. if (this.uvs5)
  35338. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35339. if (this.uvs6)
  35340. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35341. if (this.colors)
  35342. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35343. if (this.matricesIndices)
  35344. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35345. if (this.matricesWeights)
  35346. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35347. if (this.matricesIndicesExtra)
  35348. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35349. if (this.matricesWeightsExtra)
  35350. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35351. };
  35352. /**
  35353. * Serializes the VertexData.
  35354. * Returns a serialized object.
  35355. */
  35356. VertexData.prototype.serialize = function () {
  35357. var serializationObject = this.serialize();
  35358. if (this.positions) {
  35359. serializationObject.positions = this.positions;
  35360. }
  35361. if (this.normals) {
  35362. serializationObject.normals = this.normals;
  35363. }
  35364. if (this.tangents) {
  35365. serializationObject.tangents = this.tangents;
  35366. }
  35367. if (this.uvs) {
  35368. serializationObject.uvs = this.uvs;
  35369. }
  35370. if (this.uvs2) {
  35371. serializationObject.uvs2 = this.uvs2;
  35372. }
  35373. if (this.uvs3) {
  35374. serializationObject.uvs3 = this.uvs3;
  35375. }
  35376. if (this.uvs4) {
  35377. serializationObject.uvs4 = this.uvs4;
  35378. }
  35379. if (this.uvs5) {
  35380. serializationObject.uvs5 = this.uvs5;
  35381. }
  35382. if (this.uvs6) {
  35383. serializationObject.uvs6 = this.uvs6;
  35384. }
  35385. if (this.colors) {
  35386. serializationObject.colors = this.colors;
  35387. }
  35388. if (this.matricesIndices) {
  35389. serializationObject.matricesIndices = this.matricesIndices;
  35390. serializationObject.matricesIndices._isExpanded = true;
  35391. }
  35392. if (this.matricesWeights) {
  35393. serializationObject.matricesWeights = this.matricesWeights;
  35394. }
  35395. if (this.matricesIndicesExtra) {
  35396. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35397. serializationObject.matricesIndicesExtra._isExpanded = true;
  35398. }
  35399. if (this.matricesWeightsExtra) {
  35400. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35401. }
  35402. serializationObject.indices = this.indices;
  35403. return serializationObject;
  35404. };
  35405. // Statics
  35406. /**
  35407. * Returns the object VertexData associated to the passed mesh.
  35408. */
  35409. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  35410. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  35411. };
  35412. /**
  35413. * Returns the object VertexData associated to the passed geometry.
  35414. */
  35415. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  35416. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  35417. };
  35418. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  35419. var result = new VertexData();
  35420. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35421. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  35422. }
  35423. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35424. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  35425. }
  35426. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35427. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  35428. }
  35429. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35430. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  35431. }
  35432. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35433. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  35434. }
  35435. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35436. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  35437. }
  35438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35439. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  35440. }
  35441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35442. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  35443. }
  35444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35445. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  35446. }
  35447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35448. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  35449. }
  35450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35451. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  35452. }
  35453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35454. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  35455. }
  35456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35457. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  35458. }
  35459. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35460. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  35461. }
  35462. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35463. return result;
  35464. };
  35465. /**
  35466. * Creates the vertexData of the Ribbon.
  35467. */
  35468. VertexData.CreateRibbon = function (options) {
  35469. var pathArray = options.pathArray;
  35470. var closeArray = options.closeArray || false;
  35471. var closePath = options.closePath || false;
  35472. var invertUV = options.invertUV || false;
  35473. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35474. var offset = options.offset || defaultOffset;
  35475. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35476. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35477. var customUV = options.uvs;
  35478. var customColors = options.colors;
  35479. var positions = [];
  35480. var indices = [];
  35481. var normals = [];
  35482. var uvs = [];
  35483. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35484. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35485. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35486. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35487. var minlg; // minimal length among all paths from pathArray
  35488. var lg = []; // array of path lengths : nb of vertex per path
  35489. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35490. var p; // path iterator
  35491. var i; // point iterator
  35492. var j; // point iterator
  35493. // if single path in pathArray
  35494. if (pathArray.length < 2) {
  35495. var ar1 = [];
  35496. var ar2 = [];
  35497. for (i = 0; i < pathArray[0].length - offset; i++) {
  35498. ar1.push(pathArray[0][i]);
  35499. ar2.push(pathArray[0][i + offset]);
  35500. }
  35501. pathArray = [ar1, ar2];
  35502. }
  35503. // positions and horizontal distances (u)
  35504. var idc = 0;
  35505. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  35506. var path;
  35507. var l;
  35508. minlg = pathArray[0].length;
  35509. var vectlg;
  35510. var dist;
  35511. for (p = 0; p < pathArray.length; p++) {
  35512. uTotalDistance[p] = 0;
  35513. us[p] = [0];
  35514. path = pathArray[p];
  35515. l = path.length;
  35516. minlg = (minlg < l) ? minlg : l;
  35517. j = 0;
  35518. while (j < l) {
  35519. positions.push(path[j].x, path[j].y, path[j].z);
  35520. if (j > 0) {
  35521. vectlg = path[j].subtract(path[j - 1]).length();
  35522. dist = vectlg + uTotalDistance[p];
  35523. us[p].push(dist);
  35524. uTotalDistance[p] = dist;
  35525. }
  35526. j++;
  35527. }
  35528. if (closePath) {
  35529. j--;
  35530. positions.push(path[0].x, path[0].y, path[0].z);
  35531. vectlg = path[j].subtract(path[0]).length();
  35532. dist = vectlg + uTotalDistance[p];
  35533. us[p].push(dist);
  35534. uTotalDistance[p] = dist;
  35535. }
  35536. lg[p] = l + closePathCorr;
  35537. idx[p] = idc;
  35538. idc += (l + closePathCorr);
  35539. }
  35540. // vertical distances (v)
  35541. var path1;
  35542. var path2;
  35543. var vertex1 = null;
  35544. var vertex2 = null;
  35545. for (i = 0; i < minlg + closePathCorr; i++) {
  35546. vTotalDistance[i] = 0;
  35547. vs[i] = [0];
  35548. for (p = 0; p < pathArray.length - 1; p++) {
  35549. path1 = pathArray[p];
  35550. path2 = pathArray[p + 1];
  35551. if (i === minlg) {
  35552. vertex1 = path1[0];
  35553. vertex2 = path2[0];
  35554. }
  35555. else {
  35556. vertex1 = path1[i];
  35557. vertex2 = path2[i];
  35558. }
  35559. vectlg = vertex2.subtract(vertex1).length();
  35560. dist = vectlg + vTotalDistance[i];
  35561. vs[i].push(dist);
  35562. vTotalDistance[i] = dist;
  35563. }
  35564. if (closeArray && vertex2 && vertex1) {
  35565. path1 = pathArray[p];
  35566. path2 = pathArray[0];
  35567. if (i === minlg) {
  35568. vertex2 = path2[0];
  35569. }
  35570. vectlg = vertex2.subtract(vertex1).length();
  35571. dist = vectlg + vTotalDistance[i];
  35572. vTotalDistance[i] = dist;
  35573. }
  35574. }
  35575. // uvs
  35576. var u;
  35577. var v;
  35578. if (customUV) {
  35579. for (p = 0; p < customUV.length; p++) {
  35580. uvs.push(customUV[p].x, customUV[p].y);
  35581. }
  35582. }
  35583. else {
  35584. for (p = 0; p < pathArray.length; p++) {
  35585. for (i = 0; i < minlg + closePathCorr; i++) {
  35586. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  35587. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  35588. if (invertUV) {
  35589. uvs.push(v, u);
  35590. }
  35591. else {
  35592. uvs.push(u, v);
  35593. }
  35594. }
  35595. }
  35596. }
  35597. // indices
  35598. p = 0; // path index
  35599. var pi = 0; // positions array index
  35600. var l1 = lg[p] - 1; // path1 length
  35601. var l2 = lg[p + 1] - 1; // path2 length
  35602. var min = (l1 < l2) ? l1 : l2; // current path stop index
  35603. var shft = idx[1] - idx[0]; // shift
  35604. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  35605. while (pi <= min && p < path1nb) {
  35606. // 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
  35607. indices.push(pi, pi + shft, pi + 1);
  35608. indices.push(pi + shft + 1, pi + 1, pi + shft);
  35609. pi += 1;
  35610. if (pi === min) {
  35611. p++;
  35612. if (p === lg.length - 1) {
  35613. shft = idx[0] - idx[p];
  35614. l1 = lg[p] - 1;
  35615. l2 = lg[0] - 1;
  35616. }
  35617. else {
  35618. shft = idx[p + 1] - idx[p];
  35619. l1 = lg[p] - 1;
  35620. l2 = lg[p + 1] - 1;
  35621. }
  35622. pi = idx[p];
  35623. min = (l1 < l2) ? l1 + pi : l2 + pi;
  35624. }
  35625. }
  35626. // normals
  35627. VertexData.ComputeNormals(positions, indices, normals);
  35628. if (closePath) {
  35629. var indexFirst = 0;
  35630. var indexLast = 0;
  35631. for (p = 0; p < pathArray.length; p++) {
  35632. indexFirst = idx[p] * 3;
  35633. if (p + 1 < pathArray.length) {
  35634. indexLast = (idx[p + 1] - 1) * 3;
  35635. }
  35636. else {
  35637. indexLast = normals.length - 3;
  35638. }
  35639. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  35640. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  35641. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  35642. normals[indexLast] = normals[indexFirst];
  35643. normals[indexLast + 1] = normals[indexFirst + 1];
  35644. normals[indexLast + 2] = normals[indexFirst + 2];
  35645. }
  35646. }
  35647. // sides
  35648. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35649. // Colors
  35650. var colors = null;
  35651. if (customColors) {
  35652. colors = new Float32Array(customColors.length * 4);
  35653. for (var c = 0; c < customColors.length; c++) {
  35654. colors[c * 4] = customColors[c].r;
  35655. colors[c * 4 + 1] = customColors[c].g;
  35656. colors[c * 4 + 2] = customColors[c].b;
  35657. colors[c * 4 + 3] = customColors[c].a;
  35658. }
  35659. }
  35660. // Result
  35661. var vertexData = new VertexData();
  35662. var positions32 = new Float32Array(positions);
  35663. var normals32 = new Float32Array(normals);
  35664. var uvs32 = new Float32Array(uvs);
  35665. vertexData.indices = indices;
  35666. vertexData.positions = positions32;
  35667. vertexData.normals = normals32;
  35668. vertexData.uvs = uvs32;
  35669. if (colors) {
  35670. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  35671. }
  35672. if (closePath) {
  35673. vertexData._idx = idx;
  35674. }
  35675. return vertexData;
  35676. };
  35677. /**
  35678. * Creates the VertexData of the Box.
  35679. */
  35680. VertexData.CreateBox = function (options) {
  35681. var normalsSource = [
  35682. new BABYLON.Vector3(0, 0, 1),
  35683. new BABYLON.Vector3(0, 0, -1),
  35684. new BABYLON.Vector3(1, 0, 0),
  35685. new BABYLON.Vector3(-1, 0, 0),
  35686. new BABYLON.Vector3(0, 1, 0),
  35687. new BABYLON.Vector3(0, -1, 0)
  35688. ];
  35689. var indices = [];
  35690. var positions = [];
  35691. var normals = [];
  35692. var uvs = [];
  35693. var width = options.width || options.size || 1;
  35694. var height = options.height || options.size || 1;
  35695. var depth = options.depth || options.size || 1;
  35696. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35697. var faceUV = options.faceUV || new Array(6);
  35698. var faceColors = options.faceColors;
  35699. var colors = [];
  35700. // default face colors and UV if undefined
  35701. for (var f = 0; f < 6; f++) {
  35702. if (faceUV[f] === undefined) {
  35703. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35704. }
  35705. if (faceColors && faceColors[f] === undefined) {
  35706. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35707. }
  35708. }
  35709. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  35710. // Create each face in turn.
  35711. for (var index = 0; index < normalsSource.length; index++) {
  35712. var normal = normalsSource[index];
  35713. // Get two vectors perpendicular to the face normal and to each other.
  35714. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  35715. var side2 = BABYLON.Vector3.Cross(normal, side1);
  35716. // Six indices (two triangles) per face.
  35717. var verticesLength = positions.length / 3;
  35718. indices.push(verticesLength);
  35719. indices.push(verticesLength + 1);
  35720. indices.push(verticesLength + 2);
  35721. indices.push(verticesLength);
  35722. indices.push(verticesLength + 2);
  35723. indices.push(verticesLength + 3);
  35724. // Four vertices per face.
  35725. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  35726. positions.push(vertex.x, vertex.y, vertex.z);
  35727. normals.push(normal.x, normal.y, normal.z);
  35728. uvs.push(faceUV[index].z, faceUV[index].w);
  35729. if (faceColors) {
  35730. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35731. }
  35732. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  35733. positions.push(vertex.x, vertex.y, vertex.z);
  35734. normals.push(normal.x, normal.y, normal.z);
  35735. uvs.push(faceUV[index].x, faceUV[index].w);
  35736. if (faceColors) {
  35737. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35738. }
  35739. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  35740. positions.push(vertex.x, vertex.y, vertex.z);
  35741. normals.push(normal.x, normal.y, normal.z);
  35742. uvs.push(faceUV[index].x, faceUV[index].y);
  35743. if (faceColors) {
  35744. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35745. }
  35746. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  35747. positions.push(vertex.x, vertex.y, vertex.z);
  35748. normals.push(normal.x, normal.y, normal.z);
  35749. uvs.push(faceUV[index].z, faceUV[index].y);
  35750. if (faceColors) {
  35751. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  35752. }
  35753. }
  35754. // sides
  35755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35756. // Result
  35757. var vertexData = new VertexData();
  35758. vertexData.indices = indices;
  35759. vertexData.positions = positions;
  35760. vertexData.normals = normals;
  35761. vertexData.uvs = uvs;
  35762. if (faceColors) {
  35763. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  35764. vertexData.colors = totalColors;
  35765. }
  35766. return vertexData;
  35767. };
  35768. /**
  35769. * Creates the VertexData of the Sphere.
  35770. */
  35771. VertexData.CreateSphere = function (options) {
  35772. var segments = options.segments || 32;
  35773. var diameterX = options.diameterX || options.diameter || 1;
  35774. var diameterY = options.diameterY || options.diameter || 1;
  35775. var diameterZ = options.diameterZ || options.diameter || 1;
  35776. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  35777. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  35778. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35779. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  35780. var totalZRotationSteps = 2 + segments;
  35781. var totalYRotationSteps = 2 * totalZRotationSteps;
  35782. var indices = [];
  35783. var positions = [];
  35784. var normals = [];
  35785. var uvs = [];
  35786. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  35787. var normalizedZ = zRotationStep / totalZRotationSteps;
  35788. var angleZ = normalizedZ * Math.PI * slice;
  35789. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  35790. var normalizedY = yRotationStep / totalYRotationSteps;
  35791. var angleY = normalizedY * Math.PI * 2 * arc;
  35792. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  35793. var rotationY = BABYLON.Matrix.RotationY(angleY);
  35794. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  35795. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  35796. var vertex = complete.multiply(radius);
  35797. var normal = complete.divide(radius).normalize();
  35798. positions.push(vertex.x, vertex.y, vertex.z);
  35799. normals.push(normal.x, normal.y, normal.z);
  35800. uvs.push(normalizedY, normalizedZ);
  35801. }
  35802. if (zRotationStep > 0) {
  35803. var verticesCount = positions.length / 3;
  35804. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  35805. indices.push((firstIndex));
  35806. indices.push((firstIndex + 1));
  35807. indices.push(firstIndex + totalYRotationSteps + 1);
  35808. indices.push((firstIndex + totalYRotationSteps + 1));
  35809. indices.push((firstIndex + 1));
  35810. indices.push((firstIndex + totalYRotationSteps + 2));
  35811. }
  35812. }
  35813. }
  35814. // Sides
  35815. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35816. // Result
  35817. var vertexData = new VertexData();
  35818. vertexData.indices = indices;
  35819. vertexData.positions = positions;
  35820. vertexData.normals = normals;
  35821. vertexData.uvs = uvs;
  35822. return vertexData;
  35823. };
  35824. /**
  35825. * Creates the VertexData of the Cylinder or Cone.
  35826. */
  35827. VertexData.CreateCylinder = function (options) {
  35828. var height = options.height || 2;
  35829. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  35830. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  35831. var tessellation = options.tessellation || 24;
  35832. var subdivisions = options.subdivisions || 1;
  35833. var hasRings = options.hasRings ? true : false;
  35834. var enclose = options.enclose ? true : false;
  35835. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  35836. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35837. var faceUV = options.faceUV || new Array(3);
  35838. var faceColors = options.faceColors;
  35839. // default face colors and UV if undefined
  35840. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  35841. var ringNb = (hasRings) ? subdivisions : 1;
  35842. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  35843. var f;
  35844. for (f = 0; f < surfaceNb; f++) {
  35845. if (faceColors && faceColors[f] === undefined) {
  35846. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35847. }
  35848. }
  35849. for (f = 0; f < surfaceNb; f++) {
  35850. if (faceUV && faceUV[f] === undefined) {
  35851. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35852. }
  35853. }
  35854. var indices = new Array();
  35855. var positions = new Array();
  35856. var normals = new Array();
  35857. var uvs = new Array();
  35858. var colors = new Array();
  35859. var angle_step = Math.PI * 2 * arc / tessellation;
  35860. var angle;
  35861. var h;
  35862. var radius;
  35863. var tan = (diameterBottom - diameterTop) / 2 / height;
  35864. var ringVertex = BABYLON.Vector3.Zero();
  35865. var ringNormal = BABYLON.Vector3.Zero();
  35866. var ringFirstVertex = BABYLON.Vector3.Zero();
  35867. var ringFirstNormal = BABYLON.Vector3.Zero();
  35868. var quadNormal = BABYLON.Vector3.Zero();
  35869. var Y = BABYLON.Axis.Y;
  35870. // positions, normals, uvs
  35871. var i;
  35872. var j;
  35873. var r;
  35874. var ringIdx = 1;
  35875. var s = 1; // surface index
  35876. var cs = 0;
  35877. var v = 0;
  35878. for (i = 0; i <= subdivisions; i++) {
  35879. h = i / subdivisions;
  35880. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  35881. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  35882. for (r = 0; r < ringIdx; r++) {
  35883. if (hasRings) {
  35884. s += r;
  35885. }
  35886. if (enclose) {
  35887. s += 2 * r;
  35888. }
  35889. for (j = 0; j <= tessellation; j++) {
  35890. angle = j * angle_step;
  35891. // position
  35892. ringVertex.x = Math.cos(-angle) * radius;
  35893. ringVertex.y = -height / 2 + h * height;
  35894. ringVertex.z = Math.sin(-angle) * radius;
  35895. // normal
  35896. if (diameterTop === 0 && i === subdivisions) {
  35897. // if no top cap, reuse former normals
  35898. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  35899. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  35900. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  35901. }
  35902. else {
  35903. ringNormal.x = ringVertex.x;
  35904. ringNormal.z = ringVertex.z;
  35905. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  35906. ringNormal.normalize();
  35907. }
  35908. // keep first ring vertex values for enclose
  35909. if (j === 0) {
  35910. ringFirstVertex.copyFrom(ringVertex);
  35911. ringFirstNormal.copyFrom(ringNormal);
  35912. }
  35913. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  35914. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  35915. if (hasRings) {
  35916. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  35917. }
  35918. else {
  35919. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  35920. }
  35921. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  35922. if (faceColors) {
  35923. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  35924. }
  35925. }
  35926. // if enclose, add four vertices and their dedicated normals
  35927. if (arc !== 1 && enclose) {
  35928. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  35929. positions.push(0, ringVertex.y, 0);
  35930. positions.push(0, ringVertex.y, 0);
  35931. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  35932. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  35933. quadNormal.normalize();
  35934. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  35935. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  35936. quadNormal.normalize();
  35937. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  35938. if (hasRings) {
  35939. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  35940. }
  35941. else {
  35942. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  35943. }
  35944. uvs.push(faceUV[s + 1].x, v);
  35945. uvs.push(faceUV[s + 1].z, v);
  35946. if (hasRings) {
  35947. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  35948. }
  35949. else {
  35950. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  35951. }
  35952. uvs.push(faceUV[s + 2].x, v);
  35953. uvs.push(faceUV[s + 2].z, v);
  35954. if (faceColors) {
  35955. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  35956. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  35957. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  35958. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  35959. }
  35960. }
  35961. if (cs !== s) {
  35962. cs = s;
  35963. }
  35964. }
  35965. }
  35966. // indices
  35967. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  35968. var s;
  35969. i = 0;
  35970. for (s = 0; s < subdivisions; s++) {
  35971. var i0 = 0;
  35972. var i1 = 0;
  35973. var i2 = 0;
  35974. var i3 = 0;
  35975. for (j = 0; j < tessellation; j++) {
  35976. i0 = i * (e + 1) + j;
  35977. i1 = (i + 1) * (e + 1) + j;
  35978. i2 = i * (e + 1) + (j + 1);
  35979. i3 = (i + 1) * (e + 1) + (j + 1);
  35980. indices.push(i0, i1, i2);
  35981. indices.push(i3, i2, i1);
  35982. }
  35983. if (arc !== 1 && enclose) {
  35984. indices.push(i0 + 2, i1 + 2, i2 + 2);
  35985. indices.push(i3 + 2, i2 + 2, i1 + 2);
  35986. indices.push(i0 + 4, i1 + 4, i2 + 4);
  35987. indices.push(i3 + 4, i2 + 4, i1 + 4);
  35988. }
  35989. i = (hasRings) ? (i + 2) : (i + 1);
  35990. }
  35991. // Caps
  35992. var createCylinderCap = function (isTop) {
  35993. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  35994. if (radius === 0) {
  35995. return;
  35996. }
  35997. // Cap positions, normals & uvs
  35998. var angle;
  35999. var circleVector;
  36000. var i;
  36001. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36002. var c = null;
  36003. if (faceColors) {
  36004. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36005. }
  36006. // cap center
  36007. var vbase = positions.length / 3;
  36008. var offset = isTop ? height / 2 : -height / 2;
  36009. var center = new BABYLON.Vector3(0, offset, 0);
  36010. positions.push(center.x, center.y, center.z);
  36011. normals.push(0, isTop ? 1 : -1, 0);
  36012. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36013. if (c) {
  36014. colors.push(c.r, c.g, c.b, c.a);
  36015. }
  36016. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36017. for (i = 0; i <= tessellation; i++) {
  36018. angle = Math.PI * 2 * i * arc / tessellation;
  36019. var cos = Math.cos(-angle);
  36020. var sin = Math.sin(-angle);
  36021. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36022. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36023. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36024. normals.push(0, isTop ? 1 : -1, 0);
  36025. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36026. if (c) {
  36027. colors.push(c.r, c.g, c.b, c.a);
  36028. }
  36029. }
  36030. // Cap indices
  36031. for (i = 0; i < tessellation; i++) {
  36032. if (!isTop) {
  36033. indices.push(vbase);
  36034. indices.push(vbase + (i + 1));
  36035. indices.push(vbase + (i + 2));
  36036. }
  36037. else {
  36038. indices.push(vbase);
  36039. indices.push(vbase + (i + 2));
  36040. indices.push(vbase + (i + 1));
  36041. }
  36042. }
  36043. };
  36044. // add caps to geometry
  36045. createCylinderCap(false);
  36046. createCylinderCap(true);
  36047. // Sides
  36048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36049. var vertexData = new VertexData();
  36050. vertexData.indices = indices;
  36051. vertexData.positions = positions;
  36052. vertexData.normals = normals;
  36053. vertexData.uvs = uvs;
  36054. if (faceColors) {
  36055. vertexData.colors = colors;
  36056. }
  36057. return vertexData;
  36058. };
  36059. /**
  36060. * Creates the VertexData of the Torus.
  36061. */
  36062. VertexData.CreateTorus = function (options) {
  36063. var indices = [];
  36064. var positions = [];
  36065. var normals = [];
  36066. var uvs = [];
  36067. var diameter = options.diameter || 1;
  36068. var thickness = options.thickness || 0.5;
  36069. var tessellation = options.tessellation || 16;
  36070. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36071. var stride = tessellation + 1;
  36072. for (var i = 0; i <= tessellation; i++) {
  36073. var u = i / tessellation;
  36074. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36075. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36076. for (var j = 0; j <= tessellation; j++) {
  36077. var v = 1 - j / tessellation;
  36078. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36079. var dx = Math.cos(innerAngle);
  36080. var dy = Math.sin(innerAngle);
  36081. // Create a vertex.
  36082. var normal = new BABYLON.Vector3(dx, dy, 0);
  36083. var position = normal.scale(thickness / 2);
  36084. var textureCoordinate = new BABYLON.Vector2(u, v);
  36085. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36086. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36087. positions.push(position.x, position.y, position.z);
  36088. normals.push(normal.x, normal.y, normal.z);
  36089. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36090. // And create indices for two triangles.
  36091. var nextI = (i + 1) % stride;
  36092. var nextJ = (j + 1) % stride;
  36093. indices.push(i * stride + j);
  36094. indices.push(i * stride + nextJ);
  36095. indices.push(nextI * stride + j);
  36096. indices.push(i * stride + nextJ);
  36097. indices.push(nextI * stride + nextJ);
  36098. indices.push(nextI * stride + j);
  36099. }
  36100. }
  36101. // Sides
  36102. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36103. // Result
  36104. var vertexData = new VertexData();
  36105. vertexData.indices = indices;
  36106. vertexData.positions = positions;
  36107. vertexData.normals = normals;
  36108. vertexData.uvs = uvs;
  36109. return vertexData;
  36110. };
  36111. /**
  36112. * Creates the VertexData of the LineSystem.
  36113. */
  36114. VertexData.CreateLineSystem = function (options) {
  36115. var indices = [];
  36116. var positions = [];
  36117. var lines = options.lines;
  36118. var colors = options.colors;
  36119. var vertexColors = [];
  36120. var idx = 0;
  36121. for (var l = 0; l < lines.length; l++) {
  36122. var points = lines[l];
  36123. for (var index = 0; index < points.length; index++) {
  36124. positions.push(points[index].x, points[index].y, points[index].z);
  36125. if (colors) {
  36126. var color = colors[l];
  36127. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36128. }
  36129. if (index > 0) {
  36130. indices.push(idx - 1);
  36131. indices.push(idx);
  36132. }
  36133. idx++;
  36134. }
  36135. }
  36136. var vertexData = new VertexData();
  36137. vertexData.indices = indices;
  36138. vertexData.positions = positions;
  36139. if (colors) {
  36140. vertexData.colors = vertexColors;
  36141. }
  36142. return vertexData;
  36143. };
  36144. /**
  36145. * Create the VertexData of the DashedLines.
  36146. */
  36147. VertexData.CreateDashedLines = function (options) {
  36148. var dashSize = options.dashSize || 3;
  36149. var gapSize = options.gapSize || 1;
  36150. var dashNb = options.dashNb || 200;
  36151. var points = options.points;
  36152. var positions = new Array();
  36153. var indices = new Array();
  36154. var curvect = BABYLON.Vector3.Zero();
  36155. var lg = 0;
  36156. var nb = 0;
  36157. var shft = 0;
  36158. var dashshft = 0;
  36159. var curshft = 0;
  36160. var idx = 0;
  36161. var i = 0;
  36162. for (i = 0; i < points.length - 1; i++) {
  36163. points[i + 1].subtractToRef(points[i], curvect);
  36164. lg += curvect.length();
  36165. }
  36166. shft = lg / dashNb;
  36167. dashshft = dashSize * shft / (dashSize + gapSize);
  36168. for (i = 0; i < points.length - 1; i++) {
  36169. points[i + 1].subtractToRef(points[i], curvect);
  36170. nb = Math.floor(curvect.length() / shft);
  36171. curvect.normalize();
  36172. for (var j = 0; j < nb; j++) {
  36173. curshft = shft * j;
  36174. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36175. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36176. indices.push(idx, idx + 1);
  36177. idx += 2;
  36178. }
  36179. }
  36180. // Result
  36181. var vertexData = new VertexData();
  36182. vertexData.positions = positions;
  36183. vertexData.indices = indices;
  36184. return vertexData;
  36185. };
  36186. /**
  36187. * Creates the VertexData of the Ground.
  36188. */
  36189. VertexData.CreateGround = function (options) {
  36190. var indices = [];
  36191. var positions = [];
  36192. var normals = [];
  36193. var uvs = [];
  36194. var row, col;
  36195. var width = options.width || 1;
  36196. var height = options.height || 1;
  36197. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36198. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36199. for (row = 0; row <= subdivisionsY; row++) {
  36200. for (col = 0; col <= subdivisionsX; col++) {
  36201. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36202. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36203. positions.push(position.x, position.y, position.z);
  36204. normals.push(normal.x, normal.y, normal.z);
  36205. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36206. }
  36207. }
  36208. for (row = 0; row < subdivisionsY; row++) {
  36209. for (col = 0; col < subdivisionsX; col++) {
  36210. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36211. indices.push(col + 1 + row * (subdivisionsX + 1));
  36212. indices.push(col + row * (subdivisionsX + 1));
  36213. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36214. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36215. indices.push(col + row * (subdivisionsX + 1));
  36216. }
  36217. }
  36218. // Result
  36219. var vertexData = new VertexData();
  36220. vertexData.indices = indices;
  36221. vertexData.positions = positions;
  36222. vertexData.normals = normals;
  36223. vertexData.uvs = uvs;
  36224. return vertexData;
  36225. };
  36226. /**
  36227. * Creates the VertexData of the TiledGround.
  36228. */
  36229. VertexData.CreateTiledGround = function (options) {
  36230. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36231. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36232. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36233. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36234. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36235. var precision = options.precision || { w: 1, h: 1 };
  36236. var indices = new Array();
  36237. var positions = new Array();
  36238. var normals = new Array();
  36239. var uvs = new Array();
  36240. var row, col, tileRow, tileCol;
  36241. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36242. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36243. precision.w = (precision.w < 1) ? 1 : precision.w;
  36244. precision.h = (precision.h < 1) ? 1 : precision.h;
  36245. var tileSize = {
  36246. 'w': (xmax - xmin) / subdivisions.w,
  36247. 'h': (zmax - zmin) / subdivisions.h
  36248. };
  36249. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36250. // Indices
  36251. var base = positions.length / 3;
  36252. var rowLength = precision.w + 1;
  36253. for (row = 0; row < precision.h; row++) {
  36254. for (col = 0; col < precision.w; col++) {
  36255. var square = [
  36256. base + col + row * rowLength,
  36257. base + (col + 1) + row * rowLength,
  36258. base + (col + 1) + (row + 1) * rowLength,
  36259. base + col + (row + 1) * rowLength
  36260. ];
  36261. indices.push(square[1]);
  36262. indices.push(square[2]);
  36263. indices.push(square[3]);
  36264. indices.push(square[0]);
  36265. indices.push(square[1]);
  36266. indices.push(square[3]);
  36267. }
  36268. }
  36269. // Position, normals and uvs
  36270. var position = BABYLON.Vector3.Zero();
  36271. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36272. for (row = 0; row <= precision.h; row++) {
  36273. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36274. for (col = 0; col <= precision.w; col++) {
  36275. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36276. position.y = 0;
  36277. positions.push(position.x, position.y, position.z);
  36278. normals.push(normal.x, normal.y, normal.z);
  36279. uvs.push(col / precision.w, row / precision.h);
  36280. }
  36281. }
  36282. }
  36283. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36284. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36285. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36286. }
  36287. }
  36288. // Result
  36289. var vertexData = new VertexData();
  36290. vertexData.indices = indices;
  36291. vertexData.positions = positions;
  36292. vertexData.normals = normals;
  36293. vertexData.uvs = uvs;
  36294. return vertexData;
  36295. };
  36296. /**
  36297. * Creates the VertexData of the Ground designed from a heightmap.
  36298. */
  36299. VertexData.CreateGroundFromHeightMap = function (options) {
  36300. var indices = [];
  36301. var positions = [];
  36302. var normals = [];
  36303. var uvs = [];
  36304. var row, col;
  36305. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36306. // Vertices
  36307. for (row = 0; row <= options.subdivisions; row++) {
  36308. for (col = 0; col <= options.subdivisions; col++) {
  36309. 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));
  36310. // Compute height
  36311. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36312. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36313. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36314. var r = options.buffer[pos] / 255.0;
  36315. var g = options.buffer[pos + 1] / 255.0;
  36316. var b = options.buffer[pos + 2] / 255.0;
  36317. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36318. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36319. // Add vertex
  36320. positions.push(position.x, position.y, position.z);
  36321. normals.push(0, 0, 0);
  36322. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36323. }
  36324. }
  36325. // Indices
  36326. for (row = 0; row < options.subdivisions; row++) {
  36327. for (col = 0; col < options.subdivisions; col++) {
  36328. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36329. indices.push(col + 1 + row * (options.subdivisions + 1));
  36330. indices.push(col + row * (options.subdivisions + 1));
  36331. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36332. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36333. indices.push(col + row * (options.subdivisions + 1));
  36334. }
  36335. }
  36336. // Normals
  36337. VertexData.ComputeNormals(positions, indices, normals);
  36338. // Result
  36339. var vertexData = new VertexData();
  36340. vertexData.indices = indices;
  36341. vertexData.positions = positions;
  36342. vertexData.normals = normals;
  36343. vertexData.uvs = uvs;
  36344. return vertexData;
  36345. };
  36346. /**
  36347. * Creates the VertexData of the Plane.
  36348. */
  36349. VertexData.CreatePlane = function (options) {
  36350. var indices = [];
  36351. var positions = [];
  36352. var normals = [];
  36353. var uvs = [];
  36354. var width = options.width || options.size || 1;
  36355. var height = options.height || options.size || 1;
  36356. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36357. // Vertices
  36358. var halfWidth = width / 2.0;
  36359. var halfHeight = height / 2.0;
  36360. positions.push(-halfWidth, -halfHeight, 0);
  36361. normals.push(0, 0, -1.0);
  36362. uvs.push(0.0, 0.0);
  36363. positions.push(halfWidth, -halfHeight, 0);
  36364. normals.push(0, 0, -1.0);
  36365. uvs.push(1.0, 0.0);
  36366. positions.push(halfWidth, halfHeight, 0);
  36367. normals.push(0, 0, -1.0);
  36368. uvs.push(1.0, 1.0);
  36369. positions.push(-halfWidth, halfHeight, 0);
  36370. normals.push(0, 0, -1.0);
  36371. uvs.push(0.0, 1.0);
  36372. // Indices
  36373. indices.push(0);
  36374. indices.push(1);
  36375. indices.push(2);
  36376. indices.push(0);
  36377. indices.push(2);
  36378. indices.push(3);
  36379. // Sides
  36380. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36381. // Result
  36382. var vertexData = new VertexData();
  36383. vertexData.indices = indices;
  36384. vertexData.positions = positions;
  36385. vertexData.normals = normals;
  36386. vertexData.uvs = uvs;
  36387. return vertexData;
  36388. };
  36389. /**
  36390. * Creates the VertexData of the Disc or regular Polygon.
  36391. */
  36392. VertexData.CreateDisc = function (options) {
  36393. var positions = new Array();
  36394. var indices = new Array();
  36395. var normals = new Array();
  36396. var uvs = new Array();
  36397. var radius = options.radius || 0.5;
  36398. var tessellation = options.tessellation || 64;
  36399. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36400. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36401. // positions and uvs
  36402. positions.push(0, 0, 0); // disc center first
  36403. uvs.push(0.5, 0.5);
  36404. var theta = Math.PI * 2 * arc;
  36405. var step = theta / tessellation;
  36406. for (var a = 0; a < theta; a += step) {
  36407. var x = Math.cos(a);
  36408. var y = Math.sin(a);
  36409. var u = (x + 1) / 2;
  36410. var v = (1 - y) / 2;
  36411. positions.push(radius * x, radius * y, 0);
  36412. uvs.push(u, v);
  36413. }
  36414. if (arc === 1) {
  36415. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36416. uvs.push(uvs[2], uvs[3]);
  36417. }
  36418. //indices
  36419. var vertexNb = positions.length / 3;
  36420. for (var i = 1; i < vertexNb - 1; i++) {
  36421. indices.push(i + 1, 0, i);
  36422. }
  36423. // result
  36424. VertexData.ComputeNormals(positions, indices, normals);
  36425. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36426. var vertexData = new VertexData();
  36427. vertexData.indices = indices;
  36428. vertexData.positions = positions;
  36429. vertexData.normals = normals;
  36430. vertexData.uvs = uvs;
  36431. return vertexData;
  36432. };
  36433. /**
  36434. * Re-creates the VertexData of the Polygon for sideOrientation.
  36435. */
  36436. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  36437. var faceUV = fUV || new Array(3);
  36438. var faceColors = fColors;
  36439. var colors = [];
  36440. // default face colors and UV if undefined
  36441. for (var f = 0; f < 3; f++) {
  36442. if (faceUV[f] === undefined) {
  36443. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36444. }
  36445. if (faceColors && faceColors[f] === undefined) {
  36446. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36447. }
  36448. }
  36449. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36450. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36451. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36452. var indices = polygon.getIndices();
  36453. // set face colours and textures
  36454. var idx = 0;
  36455. var face = 0;
  36456. for (var index = 0; index < normals.length; index += 3) {
  36457. //Edge Face no. 1
  36458. if (Math.abs(normals[index + 1]) < 0.001) {
  36459. face = 1;
  36460. }
  36461. //Top Face no. 0
  36462. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  36463. face = 0;
  36464. }
  36465. //Bottom Face no. 2
  36466. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  36467. face = 2;
  36468. }
  36469. idx = index / 3;
  36470. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  36471. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  36472. if (faceColors) {
  36473. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  36474. }
  36475. }
  36476. // sides
  36477. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  36478. // Result
  36479. var vertexData = new VertexData();
  36480. vertexData.indices = indices;
  36481. vertexData.positions = positions;
  36482. vertexData.normals = normals;
  36483. vertexData.uvs = uvs;
  36484. if (faceColors) {
  36485. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36486. vertexData.colors = totalColors;
  36487. }
  36488. return vertexData;
  36489. };
  36490. /**
  36491. * Creates the VertexData of the IcoSphere.
  36492. */
  36493. VertexData.CreateIcoSphere = function (options) {
  36494. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36495. var radius = options.radius || 1;
  36496. var flat = (options.flat === undefined) ? true : options.flat;
  36497. var subdivisions = options.subdivisions || 4;
  36498. var radiusX = options.radiusX || radius;
  36499. var radiusY = options.radiusY || radius;
  36500. var radiusZ = options.radiusZ || radius;
  36501. var t = (1 + Math.sqrt(5)) / 2;
  36502. // 12 vertex x,y,z
  36503. var ico_vertices = [
  36504. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  36505. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  36506. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  36507. ];
  36508. // index of 3 vertex makes a face of icopshere
  36509. var ico_indices = [
  36510. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  36511. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  36512. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  36513. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  36514. ];
  36515. // vertex for uv have aliased position, not for UV
  36516. var vertices_unalias_id = [
  36517. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  36518. // vertex alias
  36519. 0,
  36520. 2,
  36521. 3,
  36522. 3,
  36523. 3,
  36524. 4,
  36525. 7,
  36526. 8,
  36527. 9,
  36528. 9,
  36529. 10,
  36530. 11 // 23: B + 12
  36531. ];
  36532. // uv as integer step (not pixels !)
  36533. var ico_vertexuv = [
  36534. 5, 1, 3, 1, 6, 4, 0, 0,
  36535. 5, 3, 4, 2, 2, 2, 4, 0,
  36536. 2, 0, 1, 1, 6, 0, 6, 2,
  36537. // vertex alias (for same vertex on different faces)
  36538. 0, 4,
  36539. 3, 3,
  36540. 4, 4,
  36541. 3, 1,
  36542. 4, 2,
  36543. 4, 4,
  36544. 0, 2,
  36545. 1, 1,
  36546. 2, 2,
  36547. 3, 3,
  36548. 1, 3,
  36549. 2, 4 // 23: B + 12
  36550. ];
  36551. // Vertices[0, 1, ...9, A, B] : position on UV plane
  36552. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  36553. // First island of uv mapping
  36554. // v = 4h 3+ 2
  36555. // v = 3h 9+ 4
  36556. // v = 2h 9+ 5 B
  36557. // v = 1h 9 1 0
  36558. // v = 0h 3 8 7 A
  36559. // u = 0 1 2 3 4 5 6 *a
  36560. // Second island of uv mapping
  36561. // v = 4h 0+ B+ 4+
  36562. // v = 3h A+ 2+
  36563. // v = 2h 7+ 6 3+
  36564. // v = 1h 8+ 3+
  36565. // v = 0h
  36566. // u = 0 1 2 3 4 5 6 *a
  36567. // Face layout on texture UV mapping
  36568. // ============
  36569. // \ 4 /\ 16 / ======
  36570. // \ / \ / /\ 11 /
  36571. // \/ 7 \/ / \ /
  36572. // ======= / 10 \/
  36573. // /\ 17 /\ =======
  36574. // / \ / \ \ 15 /\
  36575. // / 8 \/ 12 \ \ / \
  36576. // ============ \/ 6 \
  36577. // \ 18 /\ ============
  36578. // \ / \ \ 5 /\ 0 /
  36579. // \/ 13 \ \ / \ /
  36580. // ======= \/ 1 \/
  36581. // =============
  36582. // /\ 19 /\ 2 /\
  36583. // / \ / \ / \
  36584. // / 14 \/ 9 \/ 3 \
  36585. // ===================
  36586. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  36587. var ustep = 138 / 1024;
  36588. var vstep = 239 / 1024;
  36589. var uoffset = 60 / 1024;
  36590. var voffset = 26 / 1024;
  36591. // Second island should have margin, not to touch the first island
  36592. // avoid any borderline artefact in pixel rounding
  36593. var island_u_offset = -40 / 1024;
  36594. var island_v_offset = +20 / 1024;
  36595. // face is either island 0 or 1 :
  36596. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  36597. var island = [
  36598. 0, 0, 0, 0, 1,
  36599. 0, 0, 1, 1, 0,
  36600. 0, 0, 1, 1, 0,
  36601. 0, 1, 1, 1, 0 // 15 - 19
  36602. ];
  36603. var indices = new Array();
  36604. var positions = new Array();
  36605. var normals = new Array();
  36606. var uvs = new Array();
  36607. var current_indice = 0;
  36608. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  36609. var face_vertex_pos = new Array(3);
  36610. var face_vertex_uv = new Array(3);
  36611. var v012;
  36612. for (v012 = 0; v012 < 3; v012++) {
  36613. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  36614. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  36615. }
  36616. // create all with normals
  36617. for (var face = 0; face < 20; face++) {
  36618. // 3 vertex per face
  36619. for (v012 = 0; v012 < 3; v012++) {
  36620. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  36621. var v_id = ico_indices[3 * face + v012];
  36622. // vertex have 3D position (x,y,z)
  36623. 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]);
  36624. // Normalize to get normal, then scale to radius
  36625. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  36626. // uv Coordinates from vertex ID
  36627. 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);
  36628. }
  36629. // Subdivide the face (interpolate pos, norm, uv)
  36630. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  36631. // - norm is linear interpolation of vertex corner normal
  36632. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  36633. // - uv is linear interpolation
  36634. //
  36635. // Topology is as below for sub-divide by 2
  36636. // vertex shown as v0,v1,v2
  36637. // interp index is i1 to progress in range [v0,v1[
  36638. // interp index is i2 to progress in range [v0,v2[
  36639. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  36640. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36641. //
  36642. //
  36643. // i2 v2
  36644. // ^ ^
  36645. // / / \
  36646. // / / \
  36647. // / / \
  36648. // / / (0,1) \
  36649. // / #---------\
  36650. // / / \ (0,0)'/ \
  36651. // / / \ / \
  36652. // / / \ / \
  36653. // / / (0,0) \ / (1,0) \
  36654. // / #---------#---------\
  36655. // v0 v1
  36656. //
  36657. // --------------------> i1
  36658. //
  36659. // interp of (i1,i2):
  36660. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  36661. // along i1 : lerp(x0,x1, i1/(S-i2))
  36662. //
  36663. // centroid of triangle is needed to get help normal computation
  36664. // (c1,c2) are used for centroid location
  36665. var interp_vertex = function (i1, i2, c1, c2) {
  36666. // vertex is interpolated from
  36667. // - face_vertex_pos[0..2]
  36668. // - face_vertex_uv[0..2]
  36669. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  36670. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  36671. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  36672. pos_interp.normalize();
  36673. var vertex_normal;
  36674. if (flat) {
  36675. // in flat mode, recalculate normal as face centroid normal
  36676. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  36677. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  36678. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  36679. }
  36680. else {
  36681. // in smooth mode, recalculate normal from each single vertex position
  36682. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  36683. }
  36684. // Vertex normal need correction due to X,Y,Z radius scaling
  36685. vertex_normal.x /= radiusX;
  36686. vertex_normal.y /= radiusY;
  36687. vertex_normal.z /= radiusZ;
  36688. vertex_normal.normalize();
  36689. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  36690. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  36691. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  36692. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  36693. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  36694. uvs.push(uv_interp.x, uv_interp.y);
  36695. // push each vertex has member of a face
  36696. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  36697. indices.push(current_indice);
  36698. current_indice++;
  36699. };
  36700. for (var i2 = 0; i2 < subdivisions; i2++) {
  36701. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  36702. // face : (i1,i2) for /\ :
  36703. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  36704. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36705. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36706. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  36707. if (i1 + i2 + 1 < subdivisions) {
  36708. // face : (i1,i2)' for \/ :
  36709. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36710. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36711. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36712. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  36713. }
  36714. }
  36715. }
  36716. }
  36717. // Sides
  36718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36719. // Result
  36720. var vertexData = new VertexData();
  36721. vertexData.indices = indices;
  36722. vertexData.positions = positions;
  36723. vertexData.normals = normals;
  36724. vertexData.uvs = uvs;
  36725. return vertexData;
  36726. };
  36727. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  36728. /**
  36729. * Creates the VertexData of the Polyhedron.
  36730. */
  36731. VertexData.CreatePolyhedron = function (options) {
  36732. // provided polyhedron types :
  36733. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  36734. // 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)
  36735. var polyhedra = [];
  36736. 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]] };
  36737. 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]] };
  36738. polyhedra[2] = {
  36739. 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]],
  36740. 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]]
  36741. };
  36742. polyhedra[3] = {
  36743. 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]],
  36744. 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]]
  36745. };
  36746. polyhedra[4] = {
  36747. 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]],
  36748. 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]]
  36749. };
  36750. 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]] };
  36751. 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]] };
  36752. 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]] };
  36753. 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]] };
  36754. 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]] };
  36755. 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]] };
  36756. 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]] };
  36757. 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]] };
  36758. 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]] };
  36759. polyhedra[14] = {
  36760. 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]],
  36761. 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]]
  36762. };
  36763. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  36764. var size = options.size;
  36765. var sizeX = options.sizeX || size || 1;
  36766. var sizeY = options.sizeY || size || 1;
  36767. var sizeZ = options.sizeZ || size || 1;
  36768. var data = options.custom || polyhedra[type];
  36769. var nbfaces = data.face.length;
  36770. var faceUV = options.faceUV || new Array(nbfaces);
  36771. var faceColors = options.faceColors;
  36772. var flat = (options.flat === undefined) ? true : options.flat;
  36773. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36774. var positions = new Array();
  36775. var indices = new Array();
  36776. var normals = new Array();
  36777. var uvs = new Array();
  36778. var colors = new Array();
  36779. var index = 0;
  36780. var faceIdx = 0; // face cursor in the array "indexes"
  36781. var indexes = new Array();
  36782. var i = 0;
  36783. var f = 0;
  36784. var u, v, ang, x, y, tmp;
  36785. // default face colors and UV if undefined
  36786. if (flat) {
  36787. for (f = 0; f < nbfaces; f++) {
  36788. if (faceColors && faceColors[f] === undefined) {
  36789. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36790. }
  36791. if (faceUV && faceUV[f] === undefined) {
  36792. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36793. }
  36794. }
  36795. }
  36796. if (!flat) {
  36797. for (i = 0; i < data.vertex.length; i++) {
  36798. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  36799. uvs.push(0, 0);
  36800. }
  36801. for (f = 0; f < nbfaces; f++) {
  36802. for (i = 0; i < data.face[f].length - 2; i++) {
  36803. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  36804. }
  36805. }
  36806. }
  36807. else {
  36808. for (f = 0; f < nbfaces; f++) {
  36809. var fl = data.face[f].length; // number of vertices of the current face
  36810. ang = 2 * Math.PI / fl;
  36811. x = 0.5 * Math.tan(ang / 2);
  36812. y = 0.5;
  36813. // positions, uvs, colors
  36814. for (i = 0; i < fl; i++) {
  36815. // positions
  36816. 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);
  36817. indexes.push(index);
  36818. index++;
  36819. // uvs
  36820. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  36821. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  36822. uvs.push(u, v);
  36823. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  36824. y = x * Math.sin(ang) + y * Math.cos(ang);
  36825. x = tmp;
  36826. // colors
  36827. if (faceColors) {
  36828. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  36829. }
  36830. }
  36831. // indices from indexes
  36832. for (i = 0; i < fl - 2; i++) {
  36833. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  36834. }
  36835. faceIdx += fl;
  36836. }
  36837. }
  36838. VertexData.ComputeNormals(positions, indices, normals);
  36839. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36840. var vertexData = new VertexData();
  36841. vertexData.positions = positions;
  36842. vertexData.indices = indices;
  36843. vertexData.normals = normals;
  36844. vertexData.uvs = uvs;
  36845. if (faceColors && flat) {
  36846. vertexData.colors = colors;
  36847. }
  36848. return vertexData;
  36849. };
  36850. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  36851. /**
  36852. * Creates the VertexData of the Torus Knot.
  36853. */
  36854. VertexData.CreateTorusKnot = function (options) {
  36855. var indices = new Array();
  36856. var positions = new Array();
  36857. var normals = new Array();
  36858. var uvs = new Array();
  36859. var radius = options.radius || 2;
  36860. var tube = options.tube || 0.5;
  36861. var radialSegments = options.radialSegments || 32;
  36862. var tubularSegments = options.tubularSegments || 32;
  36863. var p = options.p || 2;
  36864. var q = options.q || 3;
  36865. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36866. // Helper
  36867. var getPos = function (angle) {
  36868. var cu = Math.cos(angle);
  36869. var su = Math.sin(angle);
  36870. var quOverP = q / p * angle;
  36871. var cs = Math.cos(quOverP);
  36872. var tx = radius * (2 + cs) * 0.5 * cu;
  36873. var ty = radius * (2 + cs) * su * 0.5;
  36874. var tz = radius * Math.sin(quOverP) * 0.5;
  36875. return new BABYLON.Vector3(tx, ty, tz);
  36876. };
  36877. // Vertices
  36878. var i;
  36879. var j;
  36880. for (i = 0; i <= radialSegments; i++) {
  36881. var modI = i % radialSegments;
  36882. var u = modI / radialSegments * 2 * p * Math.PI;
  36883. var p1 = getPos(u);
  36884. var p2 = getPos(u + 0.01);
  36885. var tang = p2.subtract(p1);
  36886. var n = p2.add(p1);
  36887. var bitan = BABYLON.Vector3.Cross(tang, n);
  36888. n = BABYLON.Vector3.Cross(bitan, tang);
  36889. bitan.normalize();
  36890. n.normalize();
  36891. for (j = 0; j < tubularSegments; j++) {
  36892. var modJ = j % tubularSegments;
  36893. var v = modJ / tubularSegments * 2 * Math.PI;
  36894. var cx = -tube * Math.cos(v);
  36895. var cy = tube * Math.sin(v);
  36896. positions.push(p1.x + cx * n.x + cy * bitan.x);
  36897. positions.push(p1.y + cx * n.y + cy * bitan.y);
  36898. positions.push(p1.z + cx * n.z + cy * bitan.z);
  36899. uvs.push(i / radialSegments);
  36900. uvs.push(j / tubularSegments);
  36901. }
  36902. }
  36903. for (i = 0; i < radialSegments; i++) {
  36904. for (j = 0; j < tubularSegments; j++) {
  36905. var jNext = (j + 1) % tubularSegments;
  36906. var a = i * tubularSegments + j;
  36907. var b = (i + 1) * tubularSegments + j;
  36908. var c = (i + 1) * tubularSegments + jNext;
  36909. var d = i * tubularSegments + jNext;
  36910. indices.push(d);
  36911. indices.push(b);
  36912. indices.push(a);
  36913. indices.push(d);
  36914. indices.push(c);
  36915. indices.push(b);
  36916. }
  36917. }
  36918. // Normals
  36919. VertexData.ComputeNormals(positions, indices, normals);
  36920. // Sides
  36921. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36922. // Result
  36923. var vertexData = new VertexData();
  36924. vertexData.indices = indices;
  36925. vertexData.positions = positions;
  36926. vertexData.normals = normals;
  36927. vertexData.uvs = uvs;
  36928. return vertexData;
  36929. };
  36930. // Tools
  36931. /**
  36932. * @param {any} - positions (number[] or Float32Array)
  36933. * @param {any} - indices (number[] or Uint16Array)
  36934. * @param {any} - normals (number[] or Float32Array)
  36935. * options (optional) :
  36936. * facetPositions : optional array of facet positions (vector3)
  36937. * facetNormals : optional array of facet normals (vector3)
  36938. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  36939. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  36940. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  36941. * bbSize : optional bounding box size data, required for facetPartitioning computation
  36942. * bInfo : optional bounding info, required for facetPartitioning computation
  36943. * useRightHandedSystem: optional boolean to for right handed system computation
  36944. * depthSort : optional boolean to enable the facet depth sort computation
  36945. * distanceTo : optional Vector3 to compute the facet depth from this location
  36946. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  36947. */
  36948. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  36949. // temporary scalar variables
  36950. var index = 0; // facet index
  36951. var p1p2x = 0.0; // p1p2 vector x coordinate
  36952. var p1p2y = 0.0; // p1p2 vector y coordinate
  36953. var p1p2z = 0.0; // p1p2 vector z coordinate
  36954. var p3p2x = 0.0; // p3p2 vector x coordinate
  36955. var p3p2y = 0.0; // p3p2 vector y coordinate
  36956. var p3p2z = 0.0; // p3p2 vector z coordinate
  36957. var faceNormalx = 0.0; // facet normal x coordinate
  36958. var faceNormaly = 0.0; // facet normal y coordinate
  36959. var faceNormalz = 0.0; // facet normal z coordinate
  36960. var length = 0.0; // facet normal length before normalization
  36961. var v1x = 0; // vector1 x index in the positions array
  36962. var v1y = 0; // vector1 y index in the positions array
  36963. var v1z = 0; // vector1 z index in the positions array
  36964. var v2x = 0; // vector2 x index in the positions array
  36965. var v2y = 0; // vector2 y index in the positions array
  36966. var v2z = 0; // vector2 z index in the positions array
  36967. var v3x = 0; // vector3 x index in the positions array
  36968. var v3y = 0; // vector3 y index in the positions array
  36969. var v3z = 0; // vector3 z index in the positions array
  36970. var computeFacetNormals = false;
  36971. var computeFacetPositions = false;
  36972. var computeFacetPartitioning = false;
  36973. var computeDepthSort = false;
  36974. var faceNormalSign = 1;
  36975. var ratio = 0;
  36976. var distanceTo = null;
  36977. if (options) {
  36978. computeFacetNormals = (options.facetNormals) ? true : false;
  36979. computeFacetPositions = (options.facetPositions) ? true : false;
  36980. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  36981. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  36982. ratio = options.ratio || 0;
  36983. computeDepthSort = (options.depthSort) ? true : false;
  36984. distanceTo = (options.distanceTo);
  36985. if (computeDepthSort) {
  36986. if (distanceTo === undefined) {
  36987. distanceTo = BABYLON.Vector3.Zero();
  36988. }
  36989. var depthSortedFacets = options.depthSortedFacets;
  36990. }
  36991. }
  36992. // facetPartitioning reinit if needed
  36993. var xSubRatio = 0;
  36994. var ySubRatio = 0;
  36995. var zSubRatio = 0;
  36996. var subSq = 0;
  36997. if (computeFacetPartitioning && options && options.bbSize) {
  36998. var ox = 0; // X partitioning index for facet position
  36999. var oy = 0; // Y partinioning index for facet position
  37000. var oz = 0; // Z partinioning index for facet position
  37001. var b1x = 0; // X partitioning index for facet v1 vertex
  37002. var b1y = 0; // Y partitioning index for facet v1 vertex
  37003. var b1z = 0; // z partitioning index for facet v1 vertex
  37004. var b2x = 0; // X partitioning index for facet v2 vertex
  37005. var b2y = 0; // Y partitioning index for facet v2 vertex
  37006. var b2z = 0; // Z partitioning index for facet v2 vertex
  37007. var b3x = 0; // X partitioning index for facet v3 vertex
  37008. var b3y = 0; // Y partitioning index for facet v3 vertex
  37009. var b3z = 0; // Z partitioning index for facet v3 vertex
  37010. var block_idx_o = 0; // facet barycenter block index
  37011. var block_idx_v1 = 0; // v1 vertex block index
  37012. var block_idx_v2 = 0; // v2 vertex block index
  37013. var block_idx_v3 = 0; // v3 vertex block index
  37014. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37015. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37016. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37017. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37018. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37019. subSq = options.subDiv.max * options.subDiv.max;
  37020. options.facetPartitioning.length = 0;
  37021. }
  37022. // reset the normals
  37023. for (index = 0; index < positions.length; index++) {
  37024. normals[index] = 0.0;
  37025. }
  37026. // Loop : 1 indice triplet = 1 facet
  37027. var nbFaces = (indices.length / 3) | 0;
  37028. for (index = 0; index < nbFaces; index++) {
  37029. // get the indexes of the coordinates of each vertex of the facet
  37030. v1x = indices[index * 3] * 3;
  37031. v1y = v1x + 1;
  37032. v1z = v1x + 2;
  37033. v2x = indices[index * 3 + 1] * 3;
  37034. v2y = v2x + 1;
  37035. v2z = v2x + 2;
  37036. v3x = indices[index * 3 + 2] * 3;
  37037. v3y = v3x + 1;
  37038. v3z = v3x + 2;
  37039. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37040. p1p2y = positions[v1y] - positions[v2y];
  37041. p1p2z = positions[v1z] - positions[v2z];
  37042. p3p2x = positions[v3x] - positions[v2x];
  37043. p3p2y = positions[v3y] - positions[v2y];
  37044. p3p2z = positions[v3z] - positions[v2z];
  37045. // compute the face normal with the cross product
  37046. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37047. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37048. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37049. // normalize this normal and store it in the array facetData
  37050. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37051. length = (length === 0) ? 1.0 : length;
  37052. faceNormalx /= length;
  37053. faceNormaly /= length;
  37054. faceNormalz /= length;
  37055. if (computeFacetNormals && options) {
  37056. options.facetNormals[index].x = faceNormalx;
  37057. options.facetNormals[index].y = faceNormaly;
  37058. options.facetNormals[index].z = faceNormalz;
  37059. }
  37060. if (computeFacetPositions && options) {
  37061. // compute and the facet barycenter coordinates in the array facetPositions
  37062. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37063. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37064. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37065. }
  37066. if (computeFacetPartitioning && options) {
  37067. // store the facet indexes in arrays in the main facetPartitioning array :
  37068. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37069. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37070. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37071. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37072. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37073. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37074. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37075. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37076. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37077. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37078. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37079. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37080. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37081. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37082. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37083. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37084. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37085. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37086. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37087. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37088. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37089. // push each facet index in each block containing the vertex
  37090. options.facetPartitioning[block_idx_v1].push(index);
  37091. if (block_idx_v2 != block_idx_v1) {
  37092. options.facetPartitioning[block_idx_v2].push(index);
  37093. }
  37094. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37095. options.facetPartitioning[block_idx_v3].push(index);
  37096. }
  37097. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37098. options.facetPartitioning[block_idx_o].push(index);
  37099. }
  37100. }
  37101. if (computeDepthSort && options && options.facetPositions) {
  37102. var dsf = depthSortedFacets[index];
  37103. dsf.ind = index * 3;
  37104. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37105. }
  37106. // compute the normals anyway
  37107. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37108. normals[v1y] += faceNormaly;
  37109. normals[v1z] += faceNormalz;
  37110. normals[v2x] += faceNormalx;
  37111. normals[v2y] += faceNormaly;
  37112. normals[v2z] += faceNormalz;
  37113. normals[v3x] += faceNormalx;
  37114. normals[v3y] += faceNormaly;
  37115. normals[v3z] += faceNormalz;
  37116. }
  37117. // last normalization of each normal
  37118. for (index = 0; index < normals.length / 3; index++) {
  37119. faceNormalx = normals[index * 3];
  37120. faceNormaly = normals[index * 3 + 1];
  37121. faceNormalz = normals[index * 3 + 2];
  37122. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37123. length = (length === 0) ? 1.0 : length;
  37124. faceNormalx /= length;
  37125. faceNormaly /= length;
  37126. faceNormalz /= length;
  37127. normals[index * 3] = faceNormalx;
  37128. normals[index * 3 + 1] = faceNormaly;
  37129. normals[index * 3 + 2] = faceNormalz;
  37130. }
  37131. };
  37132. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37133. var li = indices.length;
  37134. var ln = normals.length;
  37135. var i;
  37136. var n;
  37137. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37138. switch (sideOrientation) {
  37139. case BABYLON.Mesh.FRONTSIDE:
  37140. // nothing changed
  37141. break;
  37142. case BABYLON.Mesh.BACKSIDE:
  37143. var tmp;
  37144. // indices
  37145. for (i = 0; i < li; i += 3) {
  37146. tmp = indices[i];
  37147. indices[i] = indices[i + 2];
  37148. indices[i + 2] = tmp;
  37149. }
  37150. // normals
  37151. for (n = 0; n < ln; n++) {
  37152. normals[n] = -normals[n];
  37153. }
  37154. break;
  37155. case BABYLON.Mesh.DOUBLESIDE:
  37156. // positions
  37157. var lp = positions.length;
  37158. var l = lp / 3;
  37159. for (var p = 0; p < lp; p++) {
  37160. positions[lp + p] = positions[p];
  37161. }
  37162. // indices
  37163. for (i = 0; i < li; i += 3) {
  37164. indices[i + li] = indices[i + 2] + l;
  37165. indices[i + 1 + li] = indices[i + 1] + l;
  37166. indices[i + 2 + li] = indices[i] + l;
  37167. }
  37168. // normals
  37169. for (n = 0; n < ln; n++) {
  37170. normals[ln + n] = -normals[n];
  37171. }
  37172. // uvs
  37173. var lu = uvs.length;
  37174. var u = 0;
  37175. for (u = 0; u < lu; u++) {
  37176. uvs[u + lu] = uvs[u];
  37177. }
  37178. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37179. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37180. u = 0;
  37181. for (i = 0; i < lu / 2; i++) {
  37182. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37183. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37184. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37185. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37186. u += 2;
  37187. }
  37188. break;
  37189. }
  37190. };
  37191. /**
  37192. * Creates a new VertexData from the imported parameters.
  37193. */
  37194. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37195. var vertexData = new VertexData();
  37196. // positions
  37197. var positions = parsedVertexData.positions;
  37198. if (positions) {
  37199. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37200. }
  37201. // normals
  37202. var normals = parsedVertexData.normals;
  37203. if (normals) {
  37204. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37205. }
  37206. // tangents
  37207. var tangents = parsedVertexData.tangents;
  37208. if (tangents) {
  37209. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  37210. }
  37211. // uvs
  37212. var uvs = parsedVertexData.uvs;
  37213. if (uvs) {
  37214. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37215. }
  37216. // uv2s
  37217. var uv2s = parsedVertexData.uv2s;
  37218. if (uv2s) {
  37219. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37220. }
  37221. // uv3s
  37222. var uv3s = parsedVertexData.uv3s;
  37223. if (uv3s) {
  37224. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37225. }
  37226. // uv4s
  37227. var uv4s = parsedVertexData.uv4s;
  37228. if (uv4s) {
  37229. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37230. }
  37231. // uv5s
  37232. var uv5s = parsedVertexData.uv5s;
  37233. if (uv5s) {
  37234. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37235. }
  37236. // uv6s
  37237. var uv6s = parsedVertexData.uv6s;
  37238. if (uv6s) {
  37239. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37240. }
  37241. // colors
  37242. var colors = parsedVertexData.colors;
  37243. if (colors) {
  37244. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37245. }
  37246. // matricesIndices
  37247. var matricesIndices = parsedVertexData.matricesIndices;
  37248. if (matricesIndices) {
  37249. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37250. }
  37251. // matricesWeights
  37252. var matricesWeights = parsedVertexData.matricesWeights;
  37253. if (matricesWeights) {
  37254. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37255. }
  37256. // indices
  37257. var indices = parsedVertexData.indices;
  37258. if (indices) {
  37259. vertexData.indices = indices;
  37260. }
  37261. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37262. };
  37263. return VertexData;
  37264. }());
  37265. BABYLON.VertexData = VertexData;
  37266. })(BABYLON || (BABYLON = {}));
  37267. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37268. "use strict";
  37269. var BABYLON;
  37270. (function (BABYLON) {
  37271. /**
  37272. * Class used to store geometry data (vertex buffers + index buffer)
  37273. */
  37274. var Geometry = /** @class */ (function () {
  37275. /**
  37276. * Creates a new geometry
  37277. * @param id defines the unique ID
  37278. * @param scene defines the hosting scene
  37279. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  37280. * @param updatable defines if geometry must be updatable (false by default)
  37281. * @param mesh defines the mesh that will be associated with the geometry
  37282. */
  37283. function Geometry(id, scene, vertexData, updatable, mesh) {
  37284. if (updatable === void 0) { updatable = false; }
  37285. if (mesh === void 0) { mesh = null; }
  37286. /**
  37287. * Gets the delay loading state of the geometry (none by default which means not delayed)
  37288. */
  37289. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37290. this._totalVertices = 0;
  37291. this._isDisposed = false;
  37292. this._indexBufferIsUpdatable = false;
  37293. this.id = id;
  37294. this._engine = scene.getEngine();
  37295. this._meshes = [];
  37296. this._scene = scene;
  37297. //Init vertex buffer cache
  37298. this._vertexBuffers = {};
  37299. this._indices = [];
  37300. this._updatable = updatable;
  37301. // vertexData
  37302. if (vertexData) {
  37303. this.setAllVerticesData(vertexData, updatable);
  37304. }
  37305. else {
  37306. this._totalVertices = 0;
  37307. this._indices = [];
  37308. }
  37309. if (this._engine.getCaps().vertexArrayObject) {
  37310. this._vertexArrayObjects = {};
  37311. }
  37312. // applyToMesh
  37313. if (mesh) {
  37314. if (mesh.getClassName() === "LinesMesh") {
  37315. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37316. this._updateExtend();
  37317. }
  37318. this.applyToMesh(mesh);
  37319. mesh.computeWorldMatrix(true);
  37320. }
  37321. }
  37322. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37323. /**
  37324. * 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
  37325. */
  37326. get: function () {
  37327. return this._boundingBias;
  37328. },
  37329. /**
  37330. * 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
  37331. */
  37332. set: function (value) {
  37333. if (this._boundingBias && this._boundingBias.equals(value)) {
  37334. return;
  37335. }
  37336. this._boundingBias = value.clone();
  37337. this._updateBoundingInfo(true, null);
  37338. },
  37339. enumerable: true,
  37340. configurable: true
  37341. });
  37342. /**
  37343. * Static function used to attach a new empty geometry to a mesh
  37344. * @param mesh defines the mesh to attach the geometry to
  37345. * @returns the new {BABYLON.Geometry}
  37346. */
  37347. Geometry.CreateGeometryForMesh = function (mesh) {
  37348. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  37349. geometry.applyToMesh(mesh);
  37350. return geometry;
  37351. };
  37352. Object.defineProperty(Geometry.prototype, "extend", {
  37353. /**
  37354. * Gets the current extend of the geometry
  37355. */
  37356. get: function () {
  37357. return this._extend;
  37358. },
  37359. enumerable: true,
  37360. configurable: true
  37361. });
  37362. /**
  37363. * Gets the hosting scene
  37364. * @returns the hosting {BABYLON.Scene}
  37365. */
  37366. Geometry.prototype.getScene = function () {
  37367. return this._scene;
  37368. };
  37369. /**
  37370. * Gets the hosting engine
  37371. * @returns the hosting {BABYLON.Engine}
  37372. */
  37373. Geometry.prototype.getEngine = function () {
  37374. return this._engine;
  37375. };
  37376. /**
  37377. * Defines if the geometry is ready to use
  37378. * @returns true if the geometry is ready to be used
  37379. */
  37380. Geometry.prototype.isReady = function () {
  37381. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37382. };
  37383. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37384. /**
  37385. * Gets a value indicating that the geometry should not be serialized
  37386. */
  37387. get: function () {
  37388. for (var index = 0; index < this._meshes.length; index++) {
  37389. if (!this._meshes[index].doNotSerialize) {
  37390. return false;
  37391. }
  37392. }
  37393. return true;
  37394. },
  37395. enumerable: true,
  37396. configurable: true
  37397. });
  37398. /** @ignore */
  37399. Geometry.prototype._rebuild = function () {
  37400. if (this._vertexArrayObjects) {
  37401. this._vertexArrayObjects = {};
  37402. }
  37403. // Index buffer
  37404. if (this._meshes.length !== 0 && this._indices) {
  37405. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37406. }
  37407. // Vertex buffers
  37408. for (var key in this._vertexBuffers) {
  37409. var vertexBuffer = this._vertexBuffers[key];
  37410. vertexBuffer._rebuild();
  37411. }
  37412. };
  37413. /**
  37414. * Affects all gemetry data in one call
  37415. * @param vertexData defines the geometry data
  37416. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  37417. */
  37418. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37419. vertexData.applyToGeometry(this, updatable);
  37420. this.notifyUpdate();
  37421. };
  37422. /**
  37423. * Set specific vertex data
  37424. * @param kind defines the data kind (Position, normal, etc...)
  37425. * @param data defines the vertex data to use
  37426. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  37427. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  37428. */
  37429. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37430. if (updatable === void 0) { updatable = false; }
  37431. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37432. this._totalVertices = data.length / (stride || 3);
  37433. }
  37434. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37435. this.setVerticesBuffer(buffer);
  37436. };
  37437. /**
  37438. * Removes a specific vertex data
  37439. * @param kind defines the data kind (Position, normal, etc...)
  37440. */
  37441. Geometry.prototype.removeVerticesData = function (kind) {
  37442. if (this._vertexBuffers[kind]) {
  37443. this._vertexBuffers[kind].dispose();
  37444. delete this._vertexBuffers[kind];
  37445. }
  37446. };
  37447. /**
  37448. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  37449. * @param buffer defines the vertex buffer to use
  37450. * @param totalVertices defines the total number of vertices for position kind (could be null)
  37451. */
  37452. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  37453. if (totalVertices === void 0) { totalVertices = null; }
  37454. var kind = buffer.getKind();
  37455. if (this._vertexBuffers[kind]) {
  37456. this._vertexBuffers[kind].dispose();
  37457. }
  37458. this._vertexBuffers[kind] = buffer;
  37459. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37460. if (totalVertices != null) {
  37461. this._totalVertices = totalVertices;
  37462. }
  37463. this._updateExtend();
  37464. this._resetPointsArrayCache();
  37465. var meshes = this._meshes;
  37466. var numOfMeshes = meshes.length;
  37467. for (var index = 0; index < numOfMeshes; index++) {
  37468. var mesh = meshes[index];
  37469. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37470. mesh._createGlobalSubMesh(false);
  37471. mesh.computeWorldMatrix(true);
  37472. }
  37473. }
  37474. this.notifyUpdate(kind);
  37475. if (this._vertexArrayObjects) {
  37476. this._disposeVertexArrayObjects();
  37477. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37478. }
  37479. };
  37480. /**
  37481. * Update a specific vertex buffer
  37482. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  37483. * It will do nothing if the buffer is not updatable
  37484. * @param kind defines the data kind (Position, normal, etc...)
  37485. * @param data defines the data to use
  37486. * @param offset defines the offset in the target buffer where to store the data
  37487. */
  37488. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37489. var vertexBuffer = this.getVertexBuffer(kind);
  37490. if (!vertexBuffer) {
  37491. return;
  37492. }
  37493. vertexBuffer.updateDirectly(data, offset);
  37494. this.notifyUpdate(kind);
  37495. };
  37496. /**
  37497. * Update a specific vertex buffer
  37498. * This function will create a new buffer if the current one is not updatable
  37499. * @param kind defines the data kind (Position, normal, etc...)
  37500. * @param data defines the data to use
  37501. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  37502. */
  37503. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37504. if (updateExtends === void 0) { updateExtends = false; }
  37505. var vertexBuffer = this.getVertexBuffer(kind);
  37506. if (!vertexBuffer) {
  37507. return;
  37508. }
  37509. vertexBuffer.update(data);
  37510. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37511. this._updateBoundingInfo(updateExtends, data);
  37512. }
  37513. this.notifyUpdate(kind);
  37514. };
  37515. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  37516. if (updateExtends) {
  37517. this._updateExtend(data);
  37518. }
  37519. var meshes = this._meshes;
  37520. var numOfMeshes = meshes.length;
  37521. this._resetPointsArrayCache();
  37522. for (var index = 0; index < numOfMeshes; index++) {
  37523. var mesh = meshes[index];
  37524. if (updateExtends) {
  37525. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37526. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37527. var subMesh = mesh.subMeshes[subIndex];
  37528. subMesh.refreshBoundingInfo();
  37529. }
  37530. }
  37531. }
  37532. };
  37533. /** @ignore */
  37534. Geometry.prototype._bind = function (effect, indexToBind) {
  37535. if (!effect) {
  37536. return;
  37537. }
  37538. if (indexToBind === undefined) {
  37539. indexToBind = this._indexBuffer;
  37540. }
  37541. var vbs = this.getVertexBuffers();
  37542. if (!vbs) {
  37543. return;
  37544. }
  37545. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37546. this._engine.bindBuffers(vbs, indexToBind, effect);
  37547. return;
  37548. }
  37549. // Using VAO
  37550. if (!this._vertexArrayObjects[effect.key]) {
  37551. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  37552. }
  37553. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37554. };
  37555. /**
  37556. * Gets total number of vertices
  37557. * @returns the total number of vertices
  37558. */
  37559. Geometry.prototype.getTotalVertices = function () {
  37560. if (!this.isReady()) {
  37561. return 0;
  37562. }
  37563. return this._totalVertices;
  37564. };
  37565. /**
  37566. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  37567. * @param kind defines the data kind (Position, normal, etc...)
  37568. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  37569. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  37570. * @returns a float array containing vertex data
  37571. */
  37572. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  37573. var vertexBuffer = this.getVertexBuffer(kind);
  37574. if (!vertexBuffer) {
  37575. return null;
  37576. }
  37577. var data = vertexBuffer.getData();
  37578. if (!data) {
  37579. return null;
  37580. }
  37581. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  37582. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  37583. var count = this._totalVertices * defaultStride;
  37584. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  37585. var copy_1 = new Array(count);
  37586. vertexBuffer.forEach(count, function (value, index) {
  37587. copy_1[index] = value;
  37588. });
  37589. return copy_1;
  37590. }
  37591. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  37592. if (data instanceof Array) {
  37593. var offset = vertexBuffer.byteOffset / 4;
  37594. return BABYLON.Tools.Slice(data, offset, offset + count);
  37595. }
  37596. else if (data instanceof ArrayBuffer) {
  37597. return new Float32Array(data, vertexBuffer.byteOffset, count);
  37598. }
  37599. else {
  37600. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  37601. }
  37602. }
  37603. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  37604. return BABYLON.Tools.Slice(data);
  37605. }
  37606. return data;
  37607. };
  37608. /**
  37609. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  37610. * @param kind defines the data kind (Position, normal, etc...)
  37611. * @returns true if the vertex buffer with the specified kind is updatable
  37612. */
  37613. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  37614. var vb = this._vertexBuffers[kind];
  37615. if (!vb) {
  37616. return false;
  37617. }
  37618. return vb.isUpdatable();
  37619. };
  37620. /**
  37621. * Gets a specific vertex buffer
  37622. * @param kind defines the data kind (Position, normal, etc...)
  37623. * @returns a {BABYLON.VertexBuffer}
  37624. */
  37625. Geometry.prototype.getVertexBuffer = function (kind) {
  37626. if (!this.isReady()) {
  37627. return null;
  37628. }
  37629. return this._vertexBuffers[kind];
  37630. };
  37631. /**
  37632. * Returns all vertex buffers
  37633. * @return an object holding all vertex buffers indexed by kind
  37634. */
  37635. Geometry.prototype.getVertexBuffers = function () {
  37636. if (!this.isReady()) {
  37637. return null;
  37638. }
  37639. return this._vertexBuffers;
  37640. };
  37641. /**
  37642. * Gets a boolean indicating if specific vertex buffer is present
  37643. * @param kind defines the data kind (Position, normal, etc...)
  37644. * @returns true if data is present
  37645. */
  37646. Geometry.prototype.isVerticesDataPresent = function (kind) {
  37647. if (!this._vertexBuffers) {
  37648. if (this._delayInfo) {
  37649. return this._delayInfo.indexOf(kind) !== -1;
  37650. }
  37651. return false;
  37652. }
  37653. return this._vertexBuffers[kind] !== undefined;
  37654. };
  37655. /**
  37656. * Gets a list of all attached data kinds (Position, normal, etc...)
  37657. * @returns a list of string containing all kinds
  37658. */
  37659. Geometry.prototype.getVerticesDataKinds = function () {
  37660. var result = [];
  37661. var kind;
  37662. if (!this._vertexBuffers && this._delayInfo) {
  37663. for (kind in this._delayInfo) {
  37664. result.push(kind);
  37665. }
  37666. }
  37667. else {
  37668. for (kind in this._vertexBuffers) {
  37669. result.push(kind);
  37670. }
  37671. }
  37672. return result;
  37673. };
  37674. /**
  37675. * Update index buffer
  37676. * @param indices defines the indices to store in the index buffer
  37677. * @param offset defines the offset in the target buffer where to store the data
  37678. */
  37679. Geometry.prototype.updateIndices = function (indices, offset) {
  37680. if (!this._indexBuffer) {
  37681. return;
  37682. }
  37683. if (!this._indexBufferIsUpdatable) {
  37684. this.setIndices(indices, null, true);
  37685. }
  37686. else {
  37687. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  37688. }
  37689. };
  37690. /**
  37691. * Creates a new index buffer
  37692. * @param indices defines the indices to store in the index buffer
  37693. * @param totalVertices defines the total number of vertices (could be null)
  37694. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  37695. */
  37696. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  37697. if (totalVertices === void 0) { totalVertices = null; }
  37698. if (updatable === void 0) { updatable = false; }
  37699. if (this._indexBuffer) {
  37700. this._engine._releaseBuffer(this._indexBuffer);
  37701. }
  37702. this._disposeVertexArrayObjects();
  37703. this._indices = indices;
  37704. this._indexBufferIsUpdatable = updatable;
  37705. if (this._meshes.length !== 0 && this._indices) {
  37706. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  37707. }
  37708. if (totalVertices != undefined) {
  37709. this._totalVertices = totalVertices;
  37710. }
  37711. var meshes = this._meshes;
  37712. var numOfMeshes = meshes.length;
  37713. for (var index = 0; index < numOfMeshes; index++) {
  37714. meshes[index]._createGlobalSubMesh(true);
  37715. }
  37716. this.notifyUpdate();
  37717. };
  37718. /**
  37719. * Return the total number of indices
  37720. * @returns the total number of indices
  37721. */
  37722. Geometry.prototype.getTotalIndices = function () {
  37723. if (!this.isReady()) {
  37724. return 0;
  37725. }
  37726. return this._indices.length;
  37727. };
  37728. /**
  37729. * Gets the index buffer array
  37730. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  37731. * @returns the index buffer array
  37732. */
  37733. Geometry.prototype.getIndices = function (copyWhenShared) {
  37734. if (!this.isReady()) {
  37735. return null;
  37736. }
  37737. var orig = this._indices;
  37738. if (!copyWhenShared || this._meshes.length === 1) {
  37739. return orig;
  37740. }
  37741. else {
  37742. var len = orig.length;
  37743. var copy = [];
  37744. for (var i = 0; i < len; i++) {
  37745. copy.push(orig[i]);
  37746. }
  37747. return copy;
  37748. }
  37749. };
  37750. /**
  37751. * Gets the index buffer
  37752. * @return the index buffer
  37753. */
  37754. Geometry.prototype.getIndexBuffer = function () {
  37755. if (!this.isReady()) {
  37756. return null;
  37757. }
  37758. return this._indexBuffer;
  37759. };
  37760. /** @ignore */
  37761. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  37762. if (effect === void 0) { effect = null; }
  37763. if (!effect || !this._vertexArrayObjects) {
  37764. return;
  37765. }
  37766. if (this._vertexArrayObjects[effect.key]) {
  37767. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  37768. delete this._vertexArrayObjects[effect.key];
  37769. }
  37770. };
  37771. /**
  37772. * Release the associated resources for a specific mesh
  37773. * @param mesh defines the source mesh
  37774. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  37775. */
  37776. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  37777. var meshes = this._meshes;
  37778. var index = meshes.indexOf(mesh);
  37779. if (index === -1) {
  37780. return;
  37781. }
  37782. meshes.splice(index, 1);
  37783. mesh._geometry = null;
  37784. if (meshes.length === 0 && shouldDispose) {
  37785. this.dispose();
  37786. }
  37787. };
  37788. /**
  37789. * Apply current geometry to a given mesh
  37790. * @param mesh defines the mesh to apply geometry to
  37791. */
  37792. Geometry.prototype.applyToMesh = function (mesh) {
  37793. if (mesh._geometry === this) {
  37794. return;
  37795. }
  37796. var previousGeometry = mesh._geometry;
  37797. if (previousGeometry) {
  37798. previousGeometry.releaseForMesh(mesh);
  37799. }
  37800. var meshes = this._meshes;
  37801. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  37802. mesh._geometry = this;
  37803. this._scene.pushGeometry(this);
  37804. meshes.push(mesh);
  37805. if (this.isReady()) {
  37806. this._applyToMesh(mesh);
  37807. }
  37808. else {
  37809. mesh._boundingInfo = this._boundingInfo;
  37810. }
  37811. };
  37812. Geometry.prototype._updateExtend = function (data) {
  37813. if (data === void 0) { data = null; }
  37814. if (!data) {
  37815. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37816. }
  37817. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  37818. };
  37819. Geometry.prototype._applyToMesh = function (mesh) {
  37820. var numOfMeshes = this._meshes.length;
  37821. // vertexBuffers
  37822. for (var kind in this._vertexBuffers) {
  37823. if (numOfMeshes === 1) {
  37824. this._vertexBuffers[kind].create();
  37825. }
  37826. var buffer = this._vertexBuffers[kind].getBuffer();
  37827. if (buffer)
  37828. buffer.references = numOfMeshes;
  37829. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37830. if (!this._extend) {
  37831. this._updateExtend();
  37832. }
  37833. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37834. mesh._createGlobalSubMesh(false);
  37835. //bounding info was just created again, world matrix should be applied again.
  37836. mesh._updateBoundingInfo();
  37837. }
  37838. }
  37839. // indexBuffer
  37840. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  37841. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37842. }
  37843. if (this._indexBuffer) {
  37844. this._indexBuffer.references = numOfMeshes;
  37845. }
  37846. };
  37847. Geometry.prototype.notifyUpdate = function (kind) {
  37848. if (this.onGeometryUpdated) {
  37849. this.onGeometryUpdated(this, kind);
  37850. }
  37851. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  37852. var mesh = _a[_i];
  37853. mesh._markSubMeshesAsAttributesDirty();
  37854. }
  37855. };
  37856. /**
  37857. * Load the geometry if it was flagged as delay loaded
  37858. * @param scene defines the hosting scene
  37859. * @param onLoaded defines a callback called when the geometry is loaded
  37860. */
  37861. Geometry.prototype.load = function (scene, onLoaded) {
  37862. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  37863. return;
  37864. }
  37865. if (this.isReady()) {
  37866. if (onLoaded) {
  37867. onLoaded();
  37868. }
  37869. return;
  37870. }
  37871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  37872. this._queueLoad(scene, onLoaded);
  37873. };
  37874. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  37875. var _this = this;
  37876. if (!this.delayLoadingFile) {
  37877. return;
  37878. }
  37879. scene._addPendingData(this);
  37880. scene._loadFile(this.delayLoadingFile, function (data) {
  37881. if (!_this._delayLoadingFunction) {
  37882. return;
  37883. }
  37884. _this._delayLoadingFunction(JSON.parse(data), _this);
  37885. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37886. _this._delayInfo = [];
  37887. scene._removePendingData(_this);
  37888. var meshes = _this._meshes;
  37889. var numOfMeshes = meshes.length;
  37890. for (var index = 0; index < numOfMeshes; index++) {
  37891. _this._applyToMesh(meshes[index]);
  37892. }
  37893. if (onLoaded) {
  37894. onLoaded();
  37895. }
  37896. }, undefined, true);
  37897. };
  37898. /**
  37899. * Invert the geometry to move from a right handed system to a left handed one.
  37900. */
  37901. Geometry.prototype.toLeftHanded = function () {
  37902. // Flip faces
  37903. var tIndices = this.getIndices(false);
  37904. if (tIndices != null && tIndices.length > 0) {
  37905. for (var i = 0; i < tIndices.length; i += 3) {
  37906. var tTemp = tIndices[i + 0];
  37907. tIndices[i + 0] = tIndices[i + 2];
  37908. tIndices[i + 2] = tTemp;
  37909. }
  37910. this.setIndices(tIndices);
  37911. }
  37912. // Negate position.z
  37913. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  37914. if (tPositions != null && tPositions.length > 0) {
  37915. for (var i = 0; i < tPositions.length; i += 3) {
  37916. tPositions[i + 2] = -tPositions[i + 2];
  37917. }
  37918. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  37919. }
  37920. // Negate normal.z
  37921. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  37922. if (tNormals != null && tNormals.length > 0) {
  37923. for (var i = 0; i < tNormals.length; i += 3) {
  37924. tNormals[i + 2] = -tNormals[i + 2];
  37925. }
  37926. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  37927. }
  37928. };
  37929. // Cache
  37930. /** @ignore */
  37931. Geometry.prototype._resetPointsArrayCache = function () {
  37932. this._positions = null;
  37933. };
  37934. /** @ignore */
  37935. Geometry.prototype._generatePointsArray = function () {
  37936. if (this._positions)
  37937. return true;
  37938. this._positions = [];
  37939. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37940. if (!data) {
  37941. return false;
  37942. }
  37943. for (var index = 0; index < data.length; index += 3) {
  37944. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  37945. }
  37946. return true;
  37947. };
  37948. /**
  37949. * Gets a value indicating if the geometry is disposed
  37950. * @returns true if the geometry was disposed
  37951. */
  37952. Geometry.prototype.isDisposed = function () {
  37953. return this._isDisposed;
  37954. };
  37955. Geometry.prototype._disposeVertexArrayObjects = function () {
  37956. if (this._vertexArrayObjects) {
  37957. for (var kind in this._vertexArrayObjects) {
  37958. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  37959. }
  37960. this._vertexArrayObjects = {};
  37961. }
  37962. };
  37963. /**
  37964. * Free all associated resources
  37965. */
  37966. Geometry.prototype.dispose = function () {
  37967. var meshes = this._meshes;
  37968. var numOfMeshes = meshes.length;
  37969. var index;
  37970. for (index = 0; index < numOfMeshes; index++) {
  37971. this.releaseForMesh(meshes[index]);
  37972. }
  37973. this._meshes = [];
  37974. this._disposeVertexArrayObjects();
  37975. for (var kind in this._vertexBuffers) {
  37976. this._vertexBuffers[kind].dispose();
  37977. }
  37978. this._vertexBuffers = {};
  37979. this._totalVertices = 0;
  37980. if (this._indexBuffer) {
  37981. this._engine._releaseBuffer(this._indexBuffer);
  37982. }
  37983. this._indexBuffer = null;
  37984. this._indices = [];
  37985. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37986. this.delayLoadingFile = null;
  37987. this._delayLoadingFunction = null;
  37988. this._delayInfo = [];
  37989. this._boundingInfo = null;
  37990. this._scene.removeGeometry(this);
  37991. this._isDisposed = true;
  37992. };
  37993. /**
  37994. * Clone the current geometry into a new geometry
  37995. * @param id defines the unique ID of the new geometry
  37996. * @returns a new geometry object
  37997. */
  37998. Geometry.prototype.copy = function (id) {
  37999. var vertexData = new BABYLON.VertexData();
  38000. vertexData.indices = [];
  38001. var indices = this.getIndices();
  38002. if (indices) {
  38003. for (var index = 0; index < indices.length; index++) {
  38004. vertexData.indices.push(indices[index]);
  38005. }
  38006. }
  38007. var updatable = false;
  38008. var stopChecking = false;
  38009. var kind;
  38010. for (kind in this._vertexBuffers) {
  38011. // using slice() to make a copy of the array and not just reference it
  38012. var data = this.getVerticesData(kind);
  38013. if (data instanceof Float32Array) {
  38014. vertexData.set(new Float32Array(data), kind);
  38015. }
  38016. else {
  38017. vertexData.set(data.slice(0), kind);
  38018. }
  38019. if (!stopChecking) {
  38020. var vb = this.getVertexBuffer(kind);
  38021. if (vb) {
  38022. updatable = vb.isUpdatable();
  38023. stopChecking = !updatable;
  38024. }
  38025. }
  38026. }
  38027. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38028. geometry.delayLoadState = this.delayLoadState;
  38029. geometry.delayLoadingFile = this.delayLoadingFile;
  38030. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38031. for (kind in this._delayInfo) {
  38032. geometry._delayInfo = geometry._delayInfo || [];
  38033. geometry._delayInfo.push(kind);
  38034. }
  38035. // Bounding info
  38036. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38037. return geometry;
  38038. };
  38039. /**
  38040. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38041. * @return a JSON representation of the current geometry data (without the vertices data)
  38042. */
  38043. Geometry.prototype.serialize = function () {
  38044. var serializationObject = {};
  38045. serializationObject.id = this.id;
  38046. serializationObject.updatable = this._updatable;
  38047. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38048. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38049. }
  38050. return serializationObject;
  38051. };
  38052. Geometry.prototype.toNumberArray = function (origin) {
  38053. if (Array.isArray(origin)) {
  38054. return origin;
  38055. }
  38056. else {
  38057. return Array.prototype.slice.call(origin);
  38058. }
  38059. };
  38060. /**
  38061. * Serialize all vertices data into a JSON oject
  38062. * @returns a JSON representation of the current geometry data
  38063. */
  38064. Geometry.prototype.serializeVerticeData = function () {
  38065. var serializationObject = this.serialize();
  38066. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38067. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38068. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38069. serializationObject.positions._updatable = true;
  38070. }
  38071. }
  38072. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38073. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38074. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38075. serializationObject.normals._updatable = true;
  38076. }
  38077. }
  38078. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38079. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38080. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38081. serializationObject.tangets._updatable = true;
  38082. }
  38083. }
  38084. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38085. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38086. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38087. serializationObject.uvs._updatable = true;
  38088. }
  38089. }
  38090. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38091. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38092. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38093. serializationObject.uv2s._updatable = true;
  38094. }
  38095. }
  38096. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38097. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38098. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38099. serializationObject.uv3s._updatable = true;
  38100. }
  38101. }
  38102. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38103. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38104. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38105. serializationObject.uv4s._updatable = true;
  38106. }
  38107. }
  38108. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38109. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38110. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38111. serializationObject.uv5s._updatable = true;
  38112. }
  38113. }
  38114. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38115. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38116. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38117. serializationObject.uv6s._updatable = true;
  38118. }
  38119. }
  38120. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38121. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38122. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38123. serializationObject.colors._updatable = true;
  38124. }
  38125. }
  38126. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38127. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38128. serializationObject.matricesIndices._isExpanded = true;
  38129. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38130. serializationObject.matricesIndices._updatable = true;
  38131. }
  38132. }
  38133. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38134. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38135. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38136. serializationObject.matricesWeights._updatable = true;
  38137. }
  38138. }
  38139. serializationObject.indices = this.toNumberArray(this.getIndices());
  38140. return serializationObject;
  38141. };
  38142. // Statics
  38143. /**
  38144. * Extracts a clone of a mesh geometry
  38145. * @param mesh defines the source mesh
  38146. * @param id defines the unique ID of the new geometry object
  38147. * @returns the new geometry object
  38148. */
  38149. Geometry.ExtractFromMesh = function (mesh, id) {
  38150. var geometry = mesh._geometry;
  38151. if (!geometry) {
  38152. return null;
  38153. }
  38154. return geometry.copy(id);
  38155. };
  38156. /**
  38157. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38158. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38159. * Be aware Math.random() could cause collisions, but:
  38160. * "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"
  38161. * @returns a string containing a new GUID
  38162. */
  38163. Geometry.RandomId = function () {
  38164. return BABYLON.Tools.RandomId();
  38165. };
  38166. /** @ignore */
  38167. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38168. var scene = mesh.getScene();
  38169. // Geometry
  38170. var geometryId = parsedGeometry.geometryId;
  38171. if (geometryId) {
  38172. var geometry = scene.getGeometryByID(geometryId);
  38173. if (geometry) {
  38174. geometry.applyToMesh(mesh);
  38175. }
  38176. }
  38177. else if (parsedGeometry instanceof ArrayBuffer) {
  38178. var binaryInfo = mesh._binaryInfo;
  38179. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38180. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  38181. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  38182. }
  38183. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  38184. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  38185. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  38186. }
  38187. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  38188. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  38189. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  38190. }
  38191. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  38192. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  38193. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  38194. }
  38195. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  38196. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  38197. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  38198. }
  38199. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  38200. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  38201. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  38202. }
  38203. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  38204. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  38205. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  38206. }
  38207. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  38208. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  38209. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  38210. }
  38211. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  38212. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  38213. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  38214. }
  38215. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  38216. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  38217. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  38218. }
  38219. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  38220. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  38221. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  38222. }
  38223. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  38224. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  38225. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  38226. }
  38227. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  38228. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  38229. mesh.setIndices(indicesData, null);
  38230. }
  38231. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  38232. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  38233. mesh.subMeshes = [];
  38234. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  38235. var materialIndex = subMeshesData[(i * 5) + 0];
  38236. var verticesStart = subMeshesData[(i * 5) + 1];
  38237. var verticesCount = subMeshesData[(i * 5) + 2];
  38238. var indexStart = subMeshesData[(i * 5) + 3];
  38239. var indexCount = subMeshesData[(i * 5) + 4];
  38240. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  38241. }
  38242. }
  38243. }
  38244. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  38245. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  38246. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  38247. if (parsedGeometry.tangents) {
  38248. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  38249. }
  38250. if (parsedGeometry.uvs) {
  38251. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  38252. }
  38253. if (parsedGeometry.uvs2) {
  38254. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  38255. }
  38256. if (parsedGeometry.uvs3) {
  38257. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  38258. }
  38259. if (parsedGeometry.uvs4) {
  38260. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  38261. }
  38262. if (parsedGeometry.uvs5) {
  38263. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  38264. }
  38265. if (parsedGeometry.uvs6) {
  38266. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  38267. }
  38268. if (parsedGeometry.colors) {
  38269. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  38270. }
  38271. if (parsedGeometry.matricesIndices) {
  38272. if (!parsedGeometry.matricesIndices._isExpanded) {
  38273. var floatIndices = [];
  38274. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  38275. var matricesIndex = parsedGeometry.matricesIndices[i];
  38276. floatIndices.push(matricesIndex & 0x000000FF);
  38277. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38278. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38279. floatIndices.push(matricesIndex >> 24);
  38280. }
  38281. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  38282. }
  38283. else {
  38284. delete parsedGeometry.matricesIndices._isExpanded;
  38285. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  38286. }
  38287. }
  38288. if (parsedGeometry.matricesIndicesExtra) {
  38289. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  38290. var floatIndices = [];
  38291. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  38292. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  38293. floatIndices.push(matricesIndex & 0x000000FF);
  38294. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38295. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38296. floatIndices.push(matricesIndex >> 24);
  38297. }
  38298. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  38299. }
  38300. else {
  38301. delete parsedGeometry.matricesIndices._isExpanded;
  38302. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  38303. }
  38304. }
  38305. if (parsedGeometry.matricesWeights) {
  38306. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  38307. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  38308. }
  38309. if (parsedGeometry.matricesWeightsExtra) {
  38310. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  38311. }
  38312. mesh.setIndices(parsedGeometry.indices, null);
  38313. }
  38314. // SubMeshes
  38315. if (parsedGeometry.subMeshes) {
  38316. mesh.subMeshes = [];
  38317. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  38318. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  38319. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  38320. }
  38321. }
  38322. // Flat shading
  38323. if (mesh._shouldGenerateFlatShading) {
  38324. mesh.convertToFlatShadedMesh();
  38325. delete mesh._shouldGenerateFlatShading;
  38326. }
  38327. // Update
  38328. mesh.computeWorldMatrix(true);
  38329. // Octree
  38330. var sceneOctree = scene.selectionOctree;
  38331. if (sceneOctree !== undefined && sceneOctree !== null) {
  38332. sceneOctree.addMesh(mesh);
  38333. }
  38334. };
  38335. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  38336. var epsilon = 1e-3;
  38337. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  38338. return;
  38339. }
  38340. var noInfluenceBoneIndex = 0.0;
  38341. if (parsedGeometry.skeletonId > -1) {
  38342. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  38343. if (!skeleton) {
  38344. return;
  38345. }
  38346. noInfluenceBoneIndex = skeleton.bones.length;
  38347. }
  38348. else {
  38349. return;
  38350. }
  38351. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  38352. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38353. var matricesWeights = parsedGeometry.matricesWeights;
  38354. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  38355. var influencers = parsedGeometry.numBoneInfluencer;
  38356. var size = matricesWeights.length;
  38357. for (var i = 0; i < size; i += 4) {
  38358. var weight = 0.0;
  38359. var firstZeroWeight = -1;
  38360. for (var j = 0; j < 4; j++) {
  38361. var w = matricesWeights[i + j];
  38362. weight += w;
  38363. if (w < epsilon && firstZeroWeight < 0) {
  38364. firstZeroWeight = j;
  38365. }
  38366. }
  38367. if (matricesWeightsExtra) {
  38368. for (var j = 0; j < 4; j++) {
  38369. var w = matricesWeightsExtra[i + j];
  38370. weight += w;
  38371. if (w < epsilon && firstZeroWeight < 0) {
  38372. firstZeroWeight = j + 4;
  38373. }
  38374. }
  38375. }
  38376. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  38377. firstZeroWeight = influencers - 1;
  38378. }
  38379. if (weight > epsilon) {
  38380. var mweight = 1.0 / weight;
  38381. for (var j = 0; j < 4; j++) {
  38382. matricesWeights[i + j] *= mweight;
  38383. }
  38384. if (matricesWeightsExtra) {
  38385. for (var j = 0; j < 4; j++) {
  38386. matricesWeightsExtra[i + j] *= mweight;
  38387. }
  38388. }
  38389. }
  38390. else {
  38391. if (firstZeroWeight >= 4) {
  38392. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  38393. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  38394. }
  38395. else {
  38396. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  38397. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  38398. }
  38399. }
  38400. }
  38401. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  38402. if (parsedGeometry.matricesWeightsExtra) {
  38403. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  38404. }
  38405. };
  38406. /**
  38407. * Create a new geometry from persisted data (Using .babylon file format)
  38408. * @param parsedVertexData defines the persisted data
  38409. * @param scene defines the hosting scene
  38410. * @param rootUrl defines the root url to use to load assets (like delayed data)
  38411. * @returns the new geometry object
  38412. */
  38413. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  38414. if (scene.getGeometryByID(parsedVertexData.id)) {
  38415. return null; // null since geometry could be something else than a box...
  38416. }
  38417. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  38418. if (BABYLON.Tags) {
  38419. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  38420. }
  38421. if (parsedVertexData.delayLoadingFile) {
  38422. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38423. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  38424. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  38425. geometry._delayInfo = [];
  38426. if (parsedVertexData.hasUVs) {
  38427. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  38428. }
  38429. if (parsedVertexData.hasUVs2) {
  38430. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  38431. }
  38432. if (parsedVertexData.hasUVs3) {
  38433. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  38434. }
  38435. if (parsedVertexData.hasUVs4) {
  38436. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  38437. }
  38438. if (parsedVertexData.hasUVs5) {
  38439. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  38440. }
  38441. if (parsedVertexData.hasUVs6) {
  38442. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  38443. }
  38444. if (parsedVertexData.hasColors) {
  38445. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  38446. }
  38447. if (parsedVertexData.hasMatricesIndices) {
  38448. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38449. }
  38450. if (parsedVertexData.hasMatricesWeights) {
  38451. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38452. }
  38453. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  38454. }
  38455. else {
  38456. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  38457. }
  38458. scene.pushGeometry(geometry, true);
  38459. return geometry;
  38460. };
  38461. return Geometry;
  38462. }());
  38463. BABYLON.Geometry = Geometry;
  38464. // Primitives
  38465. /// Abstract class
  38466. /**
  38467. * Abstract class used to provide common services for all typed geometries
  38468. */
  38469. var _PrimitiveGeometry = /** @class */ (function (_super) {
  38470. __extends(_PrimitiveGeometry, _super);
  38471. /**
  38472. * Creates a new typed geometry
  38473. * @param id defines the unique ID of the geometry
  38474. * @param scene defines the hosting scene
  38475. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38476. * @param mesh defines the hosting mesh (can be null)
  38477. */
  38478. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  38479. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  38480. if (mesh === void 0) { mesh = null; }
  38481. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  38482. _this._canBeRegenerated = _canBeRegenerated;
  38483. _this._beingRegenerated = true;
  38484. _this.regenerate();
  38485. _this._beingRegenerated = false;
  38486. return _this;
  38487. }
  38488. /**
  38489. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  38490. * @returns true if the geometry can be regenerated
  38491. */
  38492. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  38493. return this._canBeRegenerated;
  38494. };
  38495. /**
  38496. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  38497. */
  38498. _PrimitiveGeometry.prototype.regenerate = function () {
  38499. if (!this._canBeRegenerated) {
  38500. return;
  38501. }
  38502. this._beingRegenerated = true;
  38503. this.setAllVerticesData(this._regenerateVertexData(), false);
  38504. this._beingRegenerated = false;
  38505. };
  38506. /**
  38507. * Clone the geometry
  38508. * @param id defines the unique ID of the new geometry
  38509. * @returns the new geometry
  38510. */
  38511. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  38512. return _super.prototype.copy.call(this, id);
  38513. };
  38514. // overrides
  38515. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38516. if (!this._beingRegenerated) {
  38517. return;
  38518. }
  38519. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  38520. };
  38521. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  38522. if (!this._beingRegenerated) {
  38523. return;
  38524. }
  38525. _super.prototype.setVerticesData.call(this, kind, data, false);
  38526. };
  38527. // to override
  38528. /** @ignore */
  38529. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  38530. throw new Error("Abstract method");
  38531. };
  38532. _PrimitiveGeometry.prototype.copy = function (id) {
  38533. throw new Error("Must be overriden in sub-classes.");
  38534. };
  38535. _PrimitiveGeometry.prototype.serialize = function () {
  38536. var serializationObject = _super.prototype.serialize.call(this);
  38537. serializationObject.canBeRegenerated = this.canBeRegenerated();
  38538. return serializationObject;
  38539. };
  38540. return _PrimitiveGeometry;
  38541. }(Geometry));
  38542. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  38543. /**
  38544. * Creates a ribbon geometry
  38545. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  38546. */
  38547. var RibbonGeometry = /** @class */ (function (_super) {
  38548. __extends(RibbonGeometry, _super);
  38549. /**
  38550. * Creates a ribbon geometry
  38551. * @param id defines the unique ID of the geometry
  38552. * @param scene defines the hosting scene
  38553. * @param pathArray defines the array of paths to use
  38554. * @param closeArray defines if the last path and the first path must be joined
  38555. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  38556. * @param offset defines the offset between points
  38557. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38558. * @param mesh defines the hosting mesh (can be null)
  38559. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38560. */
  38561. function RibbonGeometry(id, scene,
  38562. /**
  38563. * Defines the array of paths to use
  38564. */
  38565. pathArray,
  38566. /**
  38567. * Defines if the last and first points of each path in your pathArray must be joined
  38568. */
  38569. closeArray,
  38570. /**
  38571. * Defines if the last and first points of each path in your pathArray must be joined
  38572. */
  38573. closePath,
  38574. /**
  38575. * Defines the offset between points
  38576. */
  38577. offset, canBeRegenerated, mesh,
  38578. /**
  38579. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38580. */
  38581. side) {
  38582. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38583. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38584. _this.pathArray = pathArray;
  38585. _this.closeArray = closeArray;
  38586. _this.closePath = closePath;
  38587. _this.offset = offset;
  38588. _this.side = side;
  38589. return _this;
  38590. }
  38591. /** @ignore */
  38592. RibbonGeometry.prototype._regenerateVertexData = function () {
  38593. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  38594. };
  38595. RibbonGeometry.prototype.copy = function (id) {
  38596. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  38597. };
  38598. return RibbonGeometry;
  38599. }(_PrimitiveGeometry));
  38600. BABYLON.RibbonGeometry = RibbonGeometry;
  38601. /**
  38602. * Creates a box geometry
  38603. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  38604. */
  38605. var BoxGeometry = /** @class */ (function (_super) {
  38606. __extends(BoxGeometry, _super);
  38607. /**
  38608. * Creates a box geometry
  38609. * @param id defines the unique ID of the geometry
  38610. * @param scene defines the hosting scene
  38611. * @param size defines the zise of the box (width, height and depth are the same)
  38612. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38613. * @param mesh defines the hosting mesh (can be null)
  38614. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38615. */
  38616. function BoxGeometry(id, scene,
  38617. /**
  38618. * Defines the zise of the box (width, height and depth are the same)
  38619. */
  38620. size, canBeRegenerated, mesh,
  38621. /**
  38622. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38623. */
  38624. side) {
  38625. if (mesh === void 0) { mesh = null; }
  38626. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38627. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38628. _this.size = size;
  38629. _this.side = side;
  38630. return _this;
  38631. }
  38632. BoxGeometry.prototype._regenerateVertexData = function () {
  38633. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  38634. };
  38635. BoxGeometry.prototype.copy = function (id) {
  38636. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  38637. };
  38638. BoxGeometry.prototype.serialize = function () {
  38639. var serializationObject = _super.prototype.serialize.call(this);
  38640. serializationObject.size = this.size;
  38641. return serializationObject;
  38642. };
  38643. BoxGeometry.Parse = function (parsedBox, scene) {
  38644. if (scene.getGeometryByID(parsedBox.id)) {
  38645. return null; // null since geometry could be something else than a box...
  38646. }
  38647. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  38648. if (BABYLON.Tags) {
  38649. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  38650. }
  38651. scene.pushGeometry(box, true);
  38652. return box;
  38653. };
  38654. return BoxGeometry;
  38655. }(_PrimitiveGeometry));
  38656. BABYLON.BoxGeometry = BoxGeometry;
  38657. /**
  38658. * Creates a sphere geometry
  38659. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  38660. */
  38661. var SphereGeometry = /** @class */ (function (_super) {
  38662. __extends(SphereGeometry, _super);
  38663. /**
  38664. * Create a new sphere geometry
  38665. * @param id defines the unique ID of the geometry
  38666. * @param scene defines the hosting scene
  38667. * @param segments defines the number of segments to use to create the sphere
  38668. * @param diameter defines the diameter of the sphere
  38669. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38670. * @param mesh defines the hosting mesh (can be null)
  38671. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38672. */
  38673. function SphereGeometry(id, scene,
  38674. /**
  38675. * Defines the number of segments to use to create the sphere
  38676. */
  38677. segments,
  38678. /**
  38679. * Defines the diameter of the sphere
  38680. */
  38681. diameter, canBeRegenerated, mesh,
  38682. /**
  38683. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38684. */
  38685. side) {
  38686. if (mesh === void 0) { mesh = null; }
  38687. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38688. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38689. _this.segments = segments;
  38690. _this.diameter = diameter;
  38691. _this.side = side;
  38692. return _this;
  38693. }
  38694. SphereGeometry.prototype._regenerateVertexData = function () {
  38695. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  38696. };
  38697. SphereGeometry.prototype.copy = function (id) {
  38698. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  38699. };
  38700. SphereGeometry.prototype.serialize = function () {
  38701. var serializationObject = _super.prototype.serialize.call(this);
  38702. serializationObject.segments = this.segments;
  38703. serializationObject.diameter = this.diameter;
  38704. return serializationObject;
  38705. };
  38706. SphereGeometry.Parse = function (parsedSphere, scene) {
  38707. if (scene.getGeometryByID(parsedSphere.id)) {
  38708. return null; // null since geometry could be something else than a sphere...
  38709. }
  38710. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  38711. if (BABYLON.Tags) {
  38712. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  38713. }
  38714. scene.pushGeometry(sphere, true);
  38715. return sphere;
  38716. };
  38717. return SphereGeometry;
  38718. }(_PrimitiveGeometry));
  38719. BABYLON.SphereGeometry = SphereGeometry;
  38720. /**
  38721. * Creates a disc geometry
  38722. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  38723. */
  38724. var DiscGeometry = /** @class */ (function (_super) {
  38725. __extends(DiscGeometry, _super);
  38726. /**
  38727. * Creates a new disc geometry
  38728. * @param id defines the unique ID of the geometry
  38729. * @param scene defines the hosting scene
  38730. * @param radius defines the radius of the disc
  38731. * @param tessellation defines the tesselation factor to apply to the disc
  38732. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38733. * @param mesh defines the hosting mesh (can be null)
  38734. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38735. */
  38736. function DiscGeometry(id, scene,
  38737. /**
  38738. * Defines the radius of the disc
  38739. */
  38740. radius,
  38741. /**
  38742. * Defines the tesselation factor to apply to the disc
  38743. */
  38744. tessellation, canBeRegenerated, mesh,
  38745. /**
  38746. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38747. */
  38748. side) {
  38749. if (mesh === void 0) { mesh = null; }
  38750. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38751. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38752. _this.radius = radius;
  38753. _this.tessellation = tessellation;
  38754. _this.side = side;
  38755. return _this;
  38756. }
  38757. DiscGeometry.prototype._regenerateVertexData = function () {
  38758. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  38759. };
  38760. DiscGeometry.prototype.copy = function (id) {
  38761. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  38762. };
  38763. return DiscGeometry;
  38764. }(_PrimitiveGeometry));
  38765. BABYLON.DiscGeometry = DiscGeometry;
  38766. /**
  38767. * Creates a new cylinder geometry
  38768. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  38769. */
  38770. var CylinderGeometry = /** @class */ (function (_super) {
  38771. __extends(CylinderGeometry, _super);
  38772. /**
  38773. * Creates a new cylinder geometry
  38774. * @param id defines the unique ID of the geometry
  38775. * @param scene defines the hosting scene
  38776. * @param height defines the height of the cylinder
  38777. * @param diameterTop defines the diameter of the cylinder's top cap
  38778. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  38779. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  38780. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  38781. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38782. * @param mesh defines the hosting mesh (can be null)
  38783. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38784. */
  38785. function CylinderGeometry(id, scene,
  38786. /**
  38787. * Defines the height of the cylinder
  38788. */
  38789. height,
  38790. /**
  38791. * Defines the diameter of the cylinder's top cap
  38792. */
  38793. diameterTop,
  38794. /**
  38795. * Defines the diameter of the cylinder's bottom cap
  38796. */
  38797. diameterBottom,
  38798. /**
  38799. * Defines the tessellation factor to apply to the cylinder
  38800. */
  38801. tessellation,
  38802. /**
  38803. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  38804. */
  38805. subdivisions, canBeRegenerated, mesh,
  38806. /**
  38807. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38808. */
  38809. side) {
  38810. if (subdivisions === void 0) { subdivisions = 1; }
  38811. if (mesh === void 0) { mesh = null; }
  38812. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38813. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38814. _this.height = height;
  38815. _this.diameterTop = diameterTop;
  38816. _this.diameterBottom = diameterBottom;
  38817. _this.tessellation = tessellation;
  38818. _this.subdivisions = subdivisions;
  38819. _this.side = side;
  38820. return _this;
  38821. }
  38822. CylinderGeometry.prototype._regenerateVertexData = function () {
  38823. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  38824. };
  38825. CylinderGeometry.prototype.copy = function (id) {
  38826. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  38827. };
  38828. CylinderGeometry.prototype.serialize = function () {
  38829. var serializationObject = _super.prototype.serialize.call(this);
  38830. serializationObject.height = this.height;
  38831. serializationObject.diameterTop = this.diameterTop;
  38832. serializationObject.diameterBottom = this.diameterBottom;
  38833. serializationObject.tessellation = this.tessellation;
  38834. return serializationObject;
  38835. };
  38836. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  38837. if (scene.getGeometryByID(parsedCylinder.id)) {
  38838. return null; // null since geometry could be something else than a cylinder...
  38839. }
  38840. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  38841. if (BABYLON.Tags) {
  38842. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  38843. }
  38844. scene.pushGeometry(cylinder, true);
  38845. return cylinder;
  38846. };
  38847. return CylinderGeometry;
  38848. }(_PrimitiveGeometry));
  38849. BABYLON.CylinderGeometry = CylinderGeometry;
  38850. /**
  38851. * Creates a new torus geometry
  38852. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  38853. */
  38854. var TorusGeometry = /** @class */ (function (_super) {
  38855. __extends(TorusGeometry, _super);
  38856. /**
  38857. * Creates a new torus geometry
  38858. * @param id defines the unique ID of the geometry
  38859. * @param scene defines the hosting scene
  38860. * @param diameter defines the diameter of the torus
  38861. * @param thickness defines the thickness of the torus (ie. internal diameter)
  38862. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  38863. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38864. * @param mesh defines the hosting mesh (can be null)
  38865. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38866. */
  38867. function TorusGeometry(id, scene,
  38868. /**
  38869. * Defines the diameter of the torus
  38870. */
  38871. diameter,
  38872. /**
  38873. * Defines the thickness of the torus (ie. internal diameter)
  38874. */
  38875. thickness,
  38876. /**
  38877. * Defines the tesselation factor to apply to the torus
  38878. */
  38879. tessellation, canBeRegenerated, mesh,
  38880. /**
  38881. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38882. */
  38883. side) {
  38884. if (mesh === void 0) { mesh = null; }
  38885. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38886. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38887. _this.diameter = diameter;
  38888. _this.thickness = thickness;
  38889. _this.tessellation = tessellation;
  38890. _this.side = side;
  38891. return _this;
  38892. }
  38893. TorusGeometry.prototype._regenerateVertexData = function () {
  38894. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  38895. };
  38896. TorusGeometry.prototype.copy = function (id) {
  38897. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  38898. };
  38899. TorusGeometry.prototype.serialize = function () {
  38900. var serializationObject = _super.prototype.serialize.call(this);
  38901. serializationObject.diameter = this.diameter;
  38902. serializationObject.thickness = this.thickness;
  38903. serializationObject.tessellation = this.tessellation;
  38904. return serializationObject;
  38905. };
  38906. TorusGeometry.Parse = function (parsedTorus, scene) {
  38907. if (scene.getGeometryByID(parsedTorus.id)) {
  38908. return null; // null since geometry could be something else than a torus...
  38909. }
  38910. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  38911. if (BABYLON.Tags) {
  38912. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  38913. }
  38914. scene.pushGeometry(torus, true);
  38915. return torus;
  38916. };
  38917. return TorusGeometry;
  38918. }(_PrimitiveGeometry));
  38919. BABYLON.TorusGeometry = TorusGeometry;
  38920. /**
  38921. * Creates a new ground geometry
  38922. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  38923. */
  38924. var GroundGeometry = /** @class */ (function (_super) {
  38925. __extends(GroundGeometry, _super);
  38926. /**
  38927. * Creates a new ground geometry
  38928. * @param id defines the unique ID of the geometry
  38929. * @param scene defines the hosting scene
  38930. * @param width defines the width of the ground
  38931. * @param height defines the height of the ground
  38932. * @param subdivisions defines the subdivisions to apply to the ground
  38933. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38934. * @param mesh defines the hosting mesh (can be null)
  38935. */
  38936. function GroundGeometry(id, scene,
  38937. /**
  38938. * Defines the width of the ground
  38939. */
  38940. width,
  38941. /**
  38942. * Defines the height of the ground
  38943. */
  38944. height,
  38945. /**
  38946. * Defines the subdivisions to apply to the ground
  38947. */
  38948. subdivisions, canBeRegenerated, mesh) {
  38949. if (mesh === void 0) { mesh = null; }
  38950. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38951. _this.width = width;
  38952. _this.height = height;
  38953. _this.subdivisions = subdivisions;
  38954. return _this;
  38955. }
  38956. GroundGeometry.prototype._regenerateVertexData = function () {
  38957. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  38958. };
  38959. GroundGeometry.prototype.copy = function (id) {
  38960. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  38961. };
  38962. GroundGeometry.prototype.serialize = function () {
  38963. var serializationObject = _super.prototype.serialize.call(this);
  38964. serializationObject.width = this.width;
  38965. serializationObject.height = this.height;
  38966. serializationObject.subdivisions = this.subdivisions;
  38967. return serializationObject;
  38968. };
  38969. GroundGeometry.Parse = function (parsedGround, scene) {
  38970. if (scene.getGeometryByID(parsedGround.id)) {
  38971. return null; // null since geometry could be something else than a ground...
  38972. }
  38973. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  38974. if (BABYLON.Tags) {
  38975. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  38976. }
  38977. scene.pushGeometry(ground, true);
  38978. return ground;
  38979. };
  38980. return GroundGeometry;
  38981. }(_PrimitiveGeometry));
  38982. BABYLON.GroundGeometry = GroundGeometry;
  38983. /**
  38984. * Creates a tiled ground geometry
  38985. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  38986. */
  38987. var TiledGroundGeometry = /** @class */ (function (_super) {
  38988. __extends(TiledGroundGeometry, _super);
  38989. /**
  38990. * Creates a tiled ground geometry
  38991. * @param id defines the unique ID of the geometry
  38992. * @param scene defines the hosting scene
  38993. * @param xmin defines the minimum value on X axis
  38994. * @param zmin defines the minimum value on Z axis
  38995. * @param xmax defines the maximum value on X axis
  38996. * @param zmax defines the maximum value on Z axis
  38997. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  38998. * @param precision defines the precision to use when computing the tiles
  38999. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39000. * @param mesh defines the hosting mesh (can be null)
  39001. */
  39002. function TiledGroundGeometry(id, scene,
  39003. /**
  39004. * Defines the minimum value on X axis
  39005. */
  39006. xmin,
  39007. /**
  39008. * Defines the minimum value on Z axis
  39009. */
  39010. zmin,
  39011. /**
  39012. * Defines the maximum value on X axis
  39013. */
  39014. xmax,
  39015. /**
  39016. * Defines the maximum value on Z axis
  39017. */
  39018. zmax,
  39019. /**
  39020. * Defines the subdivisions to apply to the ground
  39021. */
  39022. subdivisions,
  39023. /**
  39024. * Defines the precision to use when computing the tiles
  39025. */
  39026. precision, canBeRegenerated, mesh) {
  39027. if (mesh === void 0) { mesh = null; }
  39028. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39029. _this.xmin = xmin;
  39030. _this.zmin = zmin;
  39031. _this.xmax = xmax;
  39032. _this.zmax = zmax;
  39033. _this.subdivisions = subdivisions;
  39034. _this.precision = precision;
  39035. return _this;
  39036. }
  39037. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39038. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39039. };
  39040. TiledGroundGeometry.prototype.copy = function (id) {
  39041. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39042. };
  39043. return TiledGroundGeometry;
  39044. }(_PrimitiveGeometry));
  39045. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39046. /**
  39047. * Creates a plane geometry
  39048. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39049. */
  39050. var PlaneGeometry = /** @class */ (function (_super) {
  39051. __extends(PlaneGeometry, _super);
  39052. /**
  39053. * Creates a plane geometry
  39054. * @param id defines the unique ID of the geometry
  39055. * @param scene defines the hosting scene
  39056. * @param size defines the size of the plane (width === height)
  39057. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39058. * @param mesh defines the hosting mesh (can be null)
  39059. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39060. */
  39061. function PlaneGeometry(id, scene,
  39062. /**
  39063. * Defines the size of the plane (width === height)
  39064. */
  39065. size, canBeRegenerated, mesh,
  39066. /**
  39067. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39068. */
  39069. side) {
  39070. if (mesh === void 0) { mesh = null; }
  39071. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39072. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39073. _this.size = size;
  39074. _this.side = side;
  39075. return _this;
  39076. }
  39077. PlaneGeometry.prototype._regenerateVertexData = function () {
  39078. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39079. };
  39080. PlaneGeometry.prototype.copy = function (id) {
  39081. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39082. };
  39083. PlaneGeometry.prototype.serialize = function () {
  39084. var serializationObject = _super.prototype.serialize.call(this);
  39085. serializationObject.size = this.size;
  39086. return serializationObject;
  39087. };
  39088. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39089. if (scene.getGeometryByID(parsedPlane.id)) {
  39090. return null; // null since geometry could be something else than a ground...
  39091. }
  39092. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39093. if (BABYLON.Tags) {
  39094. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39095. }
  39096. scene.pushGeometry(plane, true);
  39097. return plane;
  39098. };
  39099. return PlaneGeometry;
  39100. }(_PrimitiveGeometry));
  39101. BABYLON.PlaneGeometry = PlaneGeometry;
  39102. /**
  39103. * Creates a torus knot geometry
  39104. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39105. */
  39106. var TorusKnotGeometry = /** @class */ (function (_super) {
  39107. __extends(TorusKnotGeometry, _super);
  39108. /**
  39109. * Creates a torus knot geometry
  39110. * @param id defines the unique ID of the geometry
  39111. * @param scene defines the hosting scene
  39112. * @param radius defines the radius of the torus knot
  39113. * @param tube defines the thickness of the torus knot tube
  39114. * @param radialSegments defines the number of radial segments
  39115. * @param tubularSegments defines the number of tubular segments
  39116. * @param p defines the first number of windings
  39117. * @param q defines the second number of windings
  39118. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39119. * @param mesh defines the hosting mesh (can be null)
  39120. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39121. */
  39122. function TorusKnotGeometry(id, scene,
  39123. /**
  39124. * Defines the radius of the torus knot
  39125. */
  39126. radius,
  39127. /**
  39128. * Defines the thickness of the torus knot tube
  39129. */
  39130. tube,
  39131. /**
  39132. * Defines the number of radial segments
  39133. */
  39134. radialSegments,
  39135. /**
  39136. * Defines the number of tubular segments
  39137. */
  39138. tubularSegments,
  39139. /**
  39140. * Defines the first number of windings
  39141. */
  39142. p,
  39143. /**
  39144. * Defines the second number of windings
  39145. */
  39146. q, canBeRegenerated, mesh,
  39147. /**
  39148. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39149. */
  39150. side) {
  39151. if (mesh === void 0) { mesh = null; }
  39152. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39153. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39154. _this.radius = radius;
  39155. _this.tube = tube;
  39156. _this.radialSegments = radialSegments;
  39157. _this.tubularSegments = tubularSegments;
  39158. _this.p = p;
  39159. _this.q = q;
  39160. _this.side = side;
  39161. return _this;
  39162. }
  39163. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39164. 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 });
  39165. };
  39166. TorusKnotGeometry.prototype.copy = function (id) {
  39167. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39168. };
  39169. TorusKnotGeometry.prototype.serialize = function () {
  39170. var serializationObject = _super.prototype.serialize.call(this);
  39171. serializationObject.radius = this.radius;
  39172. serializationObject.tube = this.tube;
  39173. serializationObject.radialSegments = this.radialSegments;
  39174. serializationObject.tubularSegments = this.tubularSegments;
  39175. serializationObject.p = this.p;
  39176. serializationObject.q = this.q;
  39177. return serializationObject;
  39178. };
  39179. ;
  39180. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  39181. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  39182. return null; // null since geometry could be something else than a ground...
  39183. }
  39184. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  39185. if (BABYLON.Tags) {
  39186. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  39187. }
  39188. scene.pushGeometry(torusKnot, true);
  39189. return torusKnot;
  39190. };
  39191. return TorusKnotGeometry;
  39192. }(_PrimitiveGeometry));
  39193. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  39194. //}
  39195. })(BABYLON || (BABYLON = {}));
  39196. //# sourceMappingURL=babylon.geometry.js.map
  39197. "use strict";
  39198. var BABYLON;
  39199. (function (BABYLON) {
  39200. /**
  39201. * PostProcessManager is used to manage one or more post processes or post process pipelines
  39202. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  39203. */
  39204. var PostProcessManager = /** @class */ (function () {
  39205. /**
  39206. * Creates a new instance PostProcess
  39207. * @param scene The scene that the post process is associated with.
  39208. */
  39209. function PostProcessManager(scene) {
  39210. this._vertexBuffers = {};
  39211. this._scene = scene;
  39212. }
  39213. PostProcessManager.prototype._prepareBuffers = function () {
  39214. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  39215. return;
  39216. }
  39217. // VBO
  39218. var vertices = [];
  39219. vertices.push(1, 1);
  39220. vertices.push(-1, 1);
  39221. vertices.push(-1, -1);
  39222. vertices.push(1, -1);
  39223. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39224. this._buildIndexBuffer();
  39225. };
  39226. PostProcessManager.prototype._buildIndexBuffer = function () {
  39227. // Indices
  39228. var indices = [];
  39229. indices.push(0);
  39230. indices.push(1);
  39231. indices.push(2);
  39232. indices.push(0);
  39233. indices.push(2);
  39234. indices.push(3);
  39235. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  39236. };
  39237. /**
  39238. * Rebuilds the vertex buffers of the manager.
  39239. */
  39240. PostProcessManager.prototype._rebuild = function () {
  39241. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39242. if (!vb) {
  39243. return;
  39244. }
  39245. vb._rebuild();
  39246. this._buildIndexBuffer();
  39247. };
  39248. // Methods
  39249. /**
  39250. * Prepares a frame to be run through a post process.
  39251. * @param sourceTexture The input texture to the post procesess. (default: null)
  39252. * @param postProcesses An array of post processes to be run. (default: null)
  39253. * @returns True if the post processes were able to be run.
  39254. */
  39255. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  39256. if (sourceTexture === void 0) { sourceTexture = null; }
  39257. if (postProcesses === void 0) { postProcesses = null; }
  39258. var camera = this._scene.activeCamera;
  39259. if (!camera) {
  39260. return false;
  39261. }
  39262. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39263. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39264. return false;
  39265. }
  39266. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  39267. return true;
  39268. };
  39269. /**
  39270. * Manually render a set of post processes to a texture.
  39271. * @param postProcesses An array of post processes to be run.
  39272. * @param targetTexture The target texture to render to.
  39273. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  39274. */
  39275. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  39276. if (targetTexture === void 0) { targetTexture = null; }
  39277. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39278. var engine = this._scene.getEngine();
  39279. for (var index = 0; index < postProcesses.length; index++) {
  39280. if (index < postProcesses.length - 1) {
  39281. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  39282. }
  39283. else {
  39284. if (targetTexture) {
  39285. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  39286. }
  39287. else {
  39288. engine.restoreDefaultFramebuffer();
  39289. }
  39290. }
  39291. var pp = postProcesses[index];
  39292. var effect = pp.apply();
  39293. if (effect) {
  39294. pp.onBeforeRenderObservable.notifyObservers(effect);
  39295. // VBOs
  39296. this._prepareBuffers();
  39297. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39298. // Draw order
  39299. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39300. pp.onAfterRenderObservable.notifyObservers(effect);
  39301. }
  39302. }
  39303. // Restore depth buffer
  39304. engine.setDepthBuffer(true);
  39305. engine.setDepthWrite(true);
  39306. };
  39307. /**
  39308. * Finalize the result of the output of the postprocesses.
  39309. * @param doNotPresent If true the result will not be displayed to the screen.
  39310. * @param targetTexture The target texture to render to.
  39311. * @param faceIndex The index of the face to bind the target texture to.
  39312. * @param postProcesses The array of post processes to render.
  39313. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  39314. */
  39315. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  39316. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39317. var camera = this._scene.activeCamera;
  39318. if (!camera) {
  39319. return;
  39320. }
  39321. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39322. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39323. return;
  39324. }
  39325. var engine = this._scene.getEngine();
  39326. for (var index = 0, len = postProcesses.length; index < len; index++) {
  39327. var pp = postProcesses[index];
  39328. if (index < len - 1) {
  39329. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  39330. }
  39331. else {
  39332. if (targetTexture) {
  39333. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  39334. pp._outputTexture = targetTexture;
  39335. }
  39336. else {
  39337. engine.restoreDefaultFramebuffer();
  39338. pp._outputTexture = null;
  39339. }
  39340. }
  39341. if (doNotPresent) {
  39342. break;
  39343. }
  39344. var effect = pp.apply();
  39345. if (effect) {
  39346. pp.onBeforeRenderObservable.notifyObservers(effect);
  39347. // VBOs
  39348. this._prepareBuffers();
  39349. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39350. // Draw order
  39351. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39352. pp.onAfterRenderObservable.notifyObservers(effect);
  39353. }
  39354. }
  39355. // Restore states
  39356. engine.setDepthBuffer(true);
  39357. engine.setDepthWrite(true);
  39358. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39359. };
  39360. /**
  39361. * Disposes of the post process manager.
  39362. */
  39363. PostProcessManager.prototype.dispose = function () {
  39364. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39365. if (buffer) {
  39366. buffer.dispose();
  39367. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39368. }
  39369. if (this._indexBuffer) {
  39370. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39371. this._indexBuffer = null;
  39372. }
  39373. };
  39374. return PostProcessManager;
  39375. }());
  39376. BABYLON.PostProcessManager = PostProcessManager;
  39377. })(BABYLON || (BABYLON = {}));
  39378. //# sourceMappingURL=babylon.postProcessManager.js.map
  39379. "use strict";
  39380. var BABYLON;
  39381. (function (BABYLON) {
  39382. /**
  39383. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  39384. */
  39385. var PerformanceMonitor = /** @class */ (function () {
  39386. /**
  39387. * constructor
  39388. * @param frameSampleSize The number of samples required to saturate the sliding window
  39389. */
  39390. function PerformanceMonitor(frameSampleSize) {
  39391. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  39392. this._enabled = true;
  39393. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  39394. }
  39395. /**
  39396. * Samples current frame
  39397. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  39398. */
  39399. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  39400. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  39401. if (!this._enabled)
  39402. return;
  39403. if (this._lastFrameTimeMs != null) {
  39404. var dt = timeMs - this._lastFrameTimeMs;
  39405. this._rollingFrameTime.add(dt);
  39406. }
  39407. this._lastFrameTimeMs = timeMs;
  39408. };
  39409. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  39410. /**
  39411. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39412. * @return Average frame time in milliseconds
  39413. */
  39414. get: function () {
  39415. return this._rollingFrameTime.average;
  39416. },
  39417. enumerable: true,
  39418. configurable: true
  39419. });
  39420. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  39421. /**
  39422. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39423. * @return Frame time variance in milliseconds squared
  39424. */
  39425. get: function () {
  39426. return this._rollingFrameTime.variance;
  39427. },
  39428. enumerable: true,
  39429. configurable: true
  39430. });
  39431. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  39432. /**
  39433. * Returns the frame time of the most recent frame
  39434. * @return Frame time in milliseconds
  39435. */
  39436. get: function () {
  39437. return this._rollingFrameTime.history(0);
  39438. },
  39439. enumerable: true,
  39440. configurable: true
  39441. });
  39442. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  39443. /**
  39444. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  39445. * @return Framerate in frames per second
  39446. */
  39447. get: function () {
  39448. return 1000.0 / this._rollingFrameTime.average;
  39449. },
  39450. enumerable: true,
  39451. configurable: true
  39452. });
  39453. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  39454. /**
  39455. * Returns the average framerate in frames per second using the most recent frame time
  39456. * @return Framerate in frames per second
  39457. */
  39458. get: function () {
  39459. var history = this._rollingFrameTime.history(0);
  39460. if (history === 0) {
  39461. return 0;
  39462. }
  39463. return 1000.0 / history;
  39464. },
  39465. enumerable: true,
  39466. configurable: true
  39467. });
  39468. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  39469. /**
  39470. * Returns true if enough samples have been taken to completely fill the sliding window
  39471. * @return true if saturated
  39472. */
  39473. get: function () {
  39474. return this._rollingFrameTime.isSaturated();
  39475. },
  39476. enumerable: true,
  39477. configurable: true
  39478. });
  39479. /**
  39480. * Enables contributions to the sliding window sample set
  39481. */
  39482. PerformanceMonitor.prototype.enable = function () {
  39483. this._enabled = true;
  39484. };
  39485. /**
  39486. * Disables contributions to the sliding window sample set
  39487. * Samples will not be interpolated over the disabled period
  39488. */
  39489. PerformanceMonitor.prototype.disable = function () {
  39490. this._enabled = false;
  39491. //clear last sample to avoid interpolating over the disabled period when next enabled
  39492. this._lastFrameTimeMs = null;
  39493. };
  39494. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  39495. /**
  39496. * Returns true if sampling is enabled
  39497. * @return true if enabled
  39498. */
  39499. get: function () {
  39500. return this._enabled;
  39501. },
  39502. enumerable: true,
  39503. configurable: true
  39504. });
  39505. /**
  39506. * Resets performance monitor
  39507. */
  39508. PerformanceMonitor.prototype.reset = function () {
  39509. //clear last sample to avoid interpolating over the disabled period when next enabled
  39510. this._lastFrameTimeMs = null;
  39511. //wipe record
  39512. this._rollingFrameTime.reset();
  39513. };
  39514. return PerformanceMonitor;
  39515. }());
  39516. BABYLON.PerformanceMonitor = PerformanceMonitor;
  39517. /**
  39518. * RollingAverage
  39519. *
  39520. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  39521. */
  39522. var RollingAverage = /** @class */ (function () {
  39523. /**
  39524. * constructor
  39525. * @param length The number of samples required to saturate the sliding window
  39526. */
  39527. function RollingAverage(length) {
  39528. this._samples = new Array(length);
  39529. this.reset();
  39530. }
  39531. /**
  39532. * Adds a sample to the sample set
  39533. * @param v The sample value
  39534. */
  39535. RollingAverage.prototype.add = function (v) {
  39536. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  39537. var delta;
  39538. //we need to check if we've already wrapped round
  39539. if (this.isSaturated()) {
  39540. //remove bottom of stack from mean
  39541. var bottomValue = this._samples[this._pos];
  39542. delta = bottomValue - this.average;
  39543. this.average -= delta / (this._sampleCount - 1);
  39544. this._m2 -= delta * (bottomValue - this.average);
  39545. }
  39546. else {
  39547. this._sampleCount++;
  39548. }
  39549. //add new value to mean
  39550. delta = v - this.average;
  39551. this.average += delta / (this._sampleCount);
  39552. this._m2 += delta * (v - this.average);
  39553. //set the new variance
  39554. this.variance = this._m2 / (this._sampleCount - 1);
  39555. this._samples[this._pos] = v;
  39556. this._pos++;
  39557. this._pos %= this._samples.length; //positive wrap around
  39558. };
  39559. /**
  39560. * Returns previously added values or null if outside of history or outside the sliding window domain
  39561. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  39562. * @return Value previously recorded with add() or null if outside of range
  39563. */
  39564. RollingAverage.prototype.history = function (i) {
  39565. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  39566. return 0;
  39567. }
  39568. var i0 = this._wrapPosition(this._pos - 1.0);
  39569. return this._samples[this._wrapPosition(i0 - i)];
  39570. };
  39571. /**
  39572. * Returns true if enough samples have been taken to completely fill the sliding window
  39573. * @return true if sample-set saturated
  39574. */
  39575. RollingAverage.prototype.isSaturated = function () {
  39576. return this._sampleCount >= this._samples.length;
  39577. };
  39578. /**
  39579. * Resets the rolling average (equivalent to 0 samples taken so far)
  39580. */
  39581. RollingAverage.prototype.reset = function () {
  39582. this.average = 0;
  39583. this.variance = 0;
  39584. this._sampleCount = 0;
  39585. this._pos = 0;
  39586. this._m2 = 0;
  39587. };
  39588. /**
  39589. * Wraps a value around the sample range boundaries
  39590. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  39591. * @return Wrapped position in sample range
  39592. */
  39593. RollingAverage.prototype._wrapPosition = function (i) {
  39594. var max = this._samples.length;
  39595. return ((i % max) + max) % max;
  39596. };
  39597. return RollingAverage;
  39598. }());
  39599. BABYLON.RollingAverage = RollingAverage;
  39600. })(BABYLON || (BABYLON = {}));
  39601. //# sourceMappingURL=babylon.performanceMonitor.js.map
  39602. "use strict";
  39603. var BABYLON;
  39604. (function (BABYLON) {
  39605. /**
  39606. * This groups together the common properties used for image processing either in direct forward pass
  39607. * or through post processing effect depending on the use of the image processing pipeline in your scene
  39608. * or not.
  39609. */
  39610. var ImageProcessingConfiguration = /** @class */ (function () {
  39611. function ImageProcessingConfiguration() {
  39612. /**
  39613. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  39614. */
  39615. this.colorCurves = new BABYLON.ColorCurves();
  39616. this._colorCurvesEnabled = false;
  39617. this._colorGradingEnabled = false;
  39618. this._colorGradingWithGreenDepth = true;
  39619. this._colorGradingBGR = true;
  39620. this._exposure = 1.0;
  39621. this._toneMappingEnabled = false;
  39622. this._contrast = 1.0;
  39623. /**
  39624. * Vignette stretch size.
  39625. */
  39626. this.vignetteStretch = 0;
  39627. /**
  39628. * Vignette centre X Offset.
  39629. */
  39630. this.vignetteCentreX = 0;
  39631. /**
  39632. * Vignette centre Y Offset.
  39633. */
  39634. this.vignetteCentreY = 0;
  39635. /**
  39636. * Vignette weight or intensity of the vignette effect.
  39637. */
  39638. this.vignetteWeight = 1.5;
  39639. /**
  39640. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  39641. * if vignetteEnabled is set to true.
  39642. */
  39643. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  39644. /**
  39645. * Camera field of view used by the Vignette effect.
  39646. */
  39647. this.vignetteCameraFov = 0.5;
  39648. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  39649. this._vignetteEnabled = false;
  39650. this._applyByPostProcess = false;
  39651. this._isEnabled = true;
  39652. /**
  39653. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  39654. */
  39655. this.onUpdateParameters = new BABYLON.Observable();
  39656. }
  39657. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  39658. /**
  39659. * Gets wether the color curves effect is enabled.
  39660. */
  39661. get: function () {
  39662. return this._colorCurvesEnabled;
  39663. },
  39664. /**
  39665. * Sets wether the color curves effect is enabled.
  39666. */
  39667. set: function (value) {
  39668. if (this._colorCurvesEnabled === value) {
  39669. return;
  39670. }
  39671. this._colorCurvesEnabled = value;
  39672. this._updateParameters();
  39673. },
  39674. enumerable: true,
  39675. configurable: true
  39676. });
  39677. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  39678. /**
  39679. * Gets wether the color grading effect is enabled.
  39680. */
  39681. get: function () {
  39682. return this._colorGradingEnabled;
  39683. },
  39684. /**
  39685. * Sets wether the color grading effect is enabled.
  39686. */
  39687. set: function (value) {
  39688. if (this._colorGradingEnabled === value) {
  39689. return;
  39690. }
  39691. this._colorGradingEnabled = value;
  39692. this._updateParameters();
  39693. },
  39694. enumerable: true,
  39695. configurable: true
  39696. });
  39697. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  39698. /**
  39699. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  39700. */
  39701. get: function () {
  39702. return this._colorGradingWithGreenDepth;
  39703. },
  39704. /**
  39705. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  39706. */
  39707. set: function (value) {
  39708. if (this._colorGradingWithGreenDepth === value) {
  39709. return;
  39710. }
  39711. this._colorGradingWithGreenDepth = value;
  39712. this._updateParameters();
  39713. },
  39714. enumerable: true,
  39715. configurable: true
  39716. });
  39717. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  39718. /**
  39719. * Gets wether the color grading texture contains BGR values.
  39720. */
  39721. get: function () {
  39722. return this._colorGradingBGR;
  39723. },
  39724. /**
  39725. * Sets wether the color grading texture contains BGR values.
  39726. */
  39727. set: function (value) {
  39728. if (this._colorGradingBGR === value) {
  39729. return;
  39730. }
  39731. this._colorGradingBGR = value;
  39732. this._updateParameters();
  39733. },
  39734. enumerable: true,
  39735. configurable: true
  39736. });
  39737. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  39738. /**
  39739. * Gets the Exposure used in the effect.
  39740. */
  39741. get: function () {
  39742. return this._exposure;
  39743. },
  39744. /**
  39745. * Sets the Exposure used in the effect.
  39746. */
  39747. set: function (value) {
  39748. if (this._exposure === value) {
  39749. return;
  39750. }
  39751. this._exposure = value;
  39752. this._updateParameters();
  39753. },
  39754. enumerable: true,
  39755. configurable: true
  39756. });
  39757. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  39758. /**
  39759. * Gets wether the tone mapping effect is enabled.
  39760. */
  39761. get: function () {
  39762. return this._toneMappingEnabled;
  39763. },
  39764. /**
  39765. * Sets wether the tone mapping effect is enabled.
  39766. */
  39767. set: function (value) {
  39768. if (this._toneMappingEnabled === value) {
  39769. return;
  39770. }
  39771. this._toneMappingEnabled = value;
  39772. this._updateParameters();
  39773. },
  39774. enumerable: true,
  39775. configurable: true
  39776. });
  39777. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  39778. /**
  39779. * Gets the contrast used in the effect.
  39780. */
  39781. get: function () {
  39782. return this._contrast;
  39783. },
  39784. /**
  39785. * Sets the contrast used in the effect.
  39786. */
  39787. set: function (value) {
  39788. if (this._contrast === value) {
  39789. return;
  39790. }
  39791. this._contrast = value;
  39792. this._updateParameters();
  39793. },
  39794. enumerable: true,
  39795. configurable: true
  39796. });
  39797. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  39798. /**
  39799. * Gets the vignette blend mode allowing different kind of effect.
  39800. */
  39801. get: function () {
  39802. return this._vignetteBlendMode;
  39803. },
  39804. /**
  39805. * Sets the vignette blend mode allowing different kind of effect.
  39806. */
  39807. set: function (value) {
  39808. if (this._vignetteBlendMode === value) {
  39809. return;
  39810. }
  39811. this._vignetteBlendMode = value;
  39812. this._updateParameters();
  39813. },
  39814. enumerable: true,
  39815. configurable: true
  39816. });
  39817. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  39818. /**
  39819. * Gets wether the vignette effect is enabled.
  39820. */
  39821. get: function () {
  39822. return this._vignetteEnabled;
  39823. },
  39824. /**
  39825. * Sets wether the vignette effect is enabled.
  39826. */
  39827. set: function (value) {
  39828. if (this._vignetteEnabled === value) {
  39829. return;
  39830. }
  39831. this._vignetteEnabled = value;
  39832. this._updateParameters();
  39833. },
  39834. enumerable: true,
  39835. configurable: true
  39836. });
  39837. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  39838. /**
  39839. * Gets wether the image processing is applied through a post process or not.
  39840. */
  39841. get: function () {
  39842. return this._applyByPostProcess;
  39843. },
  39844. /**
  39845. * Sets wether the image processing is applied through a post process or not.
  39846. */
  39847. set: function (value) {
  39848. if (this._applyByPostProcess === value) {
  39849. return;
  39850. }
  39851. this._applyByPostProcess = value;
  39852. this._updateParameters();
  39853. },
  39854. enumerable: true,
  39855. configurable: true
  39856. });
  39857. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  39858. /**
  39859. * Gets wether the image processing is enabled or not.
  39860. */
  39861. get: function () {
  39862. return this._isEnabled;
  39863. },
  39864. /**
  39865. * Sets wether the image processing is enabled or not.
  39866. */
  39867. set: function (value) {
  39868. if (this._isEnabled === value) {
  39869. return;
  39870. }
  39871. this._isEnabled = value;
  39872. this._updateParameters();
  39873. },
  39874. enumerable: true,
  39875. configurable: true
  39876. });
  39877. /**
  39878. * Method called each time the image processing information changes requires to recompile the effect.
  39879. */
  39880. ImageProcessingConfiguration.prototype._updateParameters = function () {
  39881. this.onUpdateParameters.notifyObservers(this);
  39882. };
  39883. ImageProcessingConfiguration.prototype.getClassName = function () {
  39884. return "ImageProcessingConfiguration";
  39885. };
  39886. /**
  39887. * Prepare the list of uniforms associated with the Image Processing effects.
  39888. * @param uniformsList The list of uniforms used in the effect
  39889. * @param defines the list of defines currently in use
  39890. */
  39891. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  39892. if (defines.EXPOSURE) {
  39893. uniforms.push("exposureLinear");
  39894. }
  39895. if (defines.CONTRAST) {
  39896. uniforms.push("contrast");
  39897. }
  39898. if (defines.COLORGRADING) {
  39899. uniforms.push("colorTransformSettings");
  39900. }
  39901. if (defines.VIGNETTE) {
  39902. uniforms.push("vInverseScreenSize");
  39903. uniforms.push("vignetteSettings1");
  39904. uniforms.push("vignetteSettings2");
  39905. }
  39906. if (defines.COLORCURVES) {
  39907. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  39908. }
  39909. };
  39910. /**
  39911. * Prepare the list of samplers associated with the Image Processing effects.
  39912. * @param uniformsList The list of uniforms used in the effect
  39913. * @param defines the list of defines currently in use
  39914. */
  39915. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  39916. if (defines.COLORGRADING) {
  39917. samplersList.push("txColorTransform");
  39918. }
  39919. };
  39920. /**
  39921. * Prepare the list of defines associated to the shader.
  39922. * @param defines the list of defines to complete
  39923. */
  39924. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  39925. if (forPostProcess === void 0) { forPostProcess = false; }
  39926. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  39927. defines.VIGNETTE = false;
  39928. defines.TONEMAPPING = false;
  39929. defines.CONTRAST = false;
  39930. defines.EXPOSURE = false;
  39931. defines.COLORCURVES = false;
  39932. defines.COLORGRADING = false;
  39933. defines.COLORGRADING3D = false;
  39934. defines.IMAGEPROCESSING = false;
  39935. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  39936. return;
  39937. }
  39938. defines.VIGNETTE = this.vignetteEnabled;
  39939. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  39940. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  39941. defines.TONEMAPPING = this.toneMappingEnabled;
  39942. defines.CONTRAST = (this.contrast !== 1.0);
  39943. defines.EXPOSURE = (this.exposure !== 1.0);
  39944. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  39945. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  39946. if (defines.COLORGRADING) {
  39947. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  39948. }
  39949. else {
  39950. defines.COLORGRADING3D = false;
  39951. }
  39952. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  39953. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  39954. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  39955. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  39956. };
  39957. /**
  39958. * Returns true if all the image processing information are ready.
  39959. */
  39960. ImageProcessingConfiguration.prototype.isReady = function () {
  39961. // Color Grading texure can not be none blocking.
  39962. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  39963. };
  39964. /**
  39965. * Binds the image processing to the shader.
  39966. * @param effect The effect to bind to
  39967. */
  39968. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  39969. if (aspectRatio === void 0) { aspectRatio = 1; }
  39970. // Color Curves
  39971. if (this._colorCurvesEnabled && this.colorCurves) {
  39972. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  39973. }
  39974. // Vignette
  39975. if (this._vignetteEnabled) {
  39976. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  39977. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  39978. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  39979. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  39980. var vignetteScaleX = vignetteScaleY * aspectRatio;
  39981. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  39982. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  39983. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  39984. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  39985. var vignettePower = -2.0 * this.vignetteWeight;
  39986. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  39987. }
  39988. // Exposure
  39989. effect.setFloat("exposureLinear", this.exposure);
  39990. // Contrast
  39991. effect.setFloat("contrast", this.contrast);
  39992. // Color transform settings
  39993. if (this.colorGradingTexture) {
  39994. effect.setTexture("txColorTransform", this.colorGradingTexture);
  39995. var textureSize = this.colorGradingTexture.getSize().height;
  39996. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  39997. 0.5 / textureSize, // textureOffset
  39998. textureSize, // textureSize
  39999. this.colorGradingTexture.level // weight
  40000. );
  40001. }
  40002. };
  40003. /**
  40004. * Clones the current image processing instance.
  40005. * @return The cloned image processing
  40006. */
  40007. ImageProcessingConfiguration.prototype.clone = function () {
  40008. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40009. };
  40010. /**
  40011. * Serializes the current image processing instance to a json representation.
  40012. * @return a JSON representation
  40013. */
  40014. ImageProcessingConfiguration.prototype.serialize = function () {
  40015. return BABYLON.SerializationHelper.Serialize(this);
  40016. };
  40017. /**
  40018. * Parses the image processing from a json representation.
  40019. * @param source the JSON source to parse
  40020. * @return The parsed image processing
  40021. */
  40022. ImageProcessingConfiguration.Parse = function (source) {
  40023. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40024. };
  40025. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40026. /**
  40027. * Used to apply the vignette as a mix with the pixel color.
  40028. */
  40029. get: function () {
  40030. return this._VIGNETTEMODE_MULTIPLY;
  40031. },
  40032. enumerable: true,
  40033. configurable: true
  40034. });
  40035. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40036. /**
  40037. * Used to apply the vignette as a replacement of the pixel color.
  40038. */
  40039. get: function () {
  40040. return this._VIGNETTEMODE_OPAQUE;
  40041. },
  40042. enumerable: true,
  40043. configurable: true
  40044. });
  40045. // Static constants associated to the image processing.
  40046. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40047. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40048. __decorate([
  40049. BABYLON.serializeAsColorCurves()
  40050. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40051. __decorate([
  40052. BABYLON.serialize()
  40053. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40054. __decorate([
  40055. BABYLON.serializeAsTexture()
  40056. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40057. __decorate([
  40058. BABYLON.serialize()
  40059. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40060. __decorate([
  40061. BABYLON.serialize()
  40062. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40063. __decorate([
  40064. BABYLON.serialize()
  40065. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40066. __decorate([
  40067. BABYLON.serialize()
  40068. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40069. __decorate([
  40070. BABYLON.serialize()
  40071. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40072. __decorate([
  40073. BABYLON.serialize()
  40074. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40075. __decorate([
  40076. BABYLON.serialize()
  40077. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40078. __decorate([
  40079. BABYLON.serialize()
  40080. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40081. __decorate([
  40082. BABYLON.serialize()
  40083. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40084. __decorate([
  40085. BABYLON.serialize()
  40086. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40087. __decorate([
  40088. BABYLON.serializeAsColor4()
  40089. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40090. __decorate([
  40091. BABYLON.serialize()
  40092. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40093. __decorate([
  40094. BABYLON.serialize()
  40095. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40096. __decorate([
  40097. BABYLON.serialize()
  40098. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40099. __decorate([
  40100. BABYLON.serialize()
  40101. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40102. __decorate([
  40103. BABYLON.serialize()
  40104. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40105. return ImageProcessingConfiguration;
  40106. }());
  40107. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40108. })(BABYLON || (BABYLON = {}));
  40109. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40110. "use strict";
  40111. var BABYLON;
  40112. (function (BABYLON) {
  40113. /**
  40114. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40115. * It can help converting any input color in a desired output one. This can then be used to create effects
  40116. * from sepia, black and white to sixties or futuristic rendering...
  40117. *
  40118. * The only supported format is currently 3dl.
  40119. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40120. */
  40121. var ColorGradingTexture = /** @class */ (function (_super) {
  40122. __extends(ColorGradingTexture, _super);
  40123. /**
  40124. * Instantiates a ColorGradingTexture from the following parameters.
  40125. *
  40126. * @param url The location of the color gradind data (currently only supporting 3dl)
  40127. * @param scene The scene the texture will be used in
  40128. */
  40129. function ColorGradingTexture(url, scene) {
  40130. var _this = _super.call(this, scene) || this;
  40131. if (!url) {
  40132. return _this;
  40133. }
  40134. _this._engine = scene.getEngine();
  40135. _this._textureMatrix = BABYLON.Matrix.Identity();
  40136. _this.name = url;
  40137. _this.url = url;
  40138. _this.hasAlpha = false;
  40139. _this.isCube = false;
  40140. _this.is3D = _this._engine.webGLVersion > 1;
  40141. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40142. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40143. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40144. _this.anisotropicFilteringLevel = 1;
  40145. _this._texture = _this._getFromCache(url, true);
  40146. if (!_this._texture) {
  40147. if (!scene.useDelayedTextureLoading) {
  40148. _this.loadTexture();
  40149. }
  40150. else {
  40151. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40152. }
  40153. }
  40154. return _this;
  40155. }
  40156. /**
  40157. * Returns the texture matrix used in most of the material.
  40158. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40159. */
  40160. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40161. return this._textureMatrix;
  40162. };
  40163. /**
  40164. * Occurs when the file being loaded is a .3dl LUT file.
  40165. */
  40166. ColorGradingTexture.prototype.load3dlTexture = function () {
  40167. var engine = this._engine;
  40168. var texture;
  40169. if (engine.webGLVersion === 1) {
  40170. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40171. }
  40172. else {
  40173. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40174. }
  40175. this._texture = texture;
  40176. var callback = function (text) {
  40177. if (typeof text !== "string") {
  40178. return;
  40179. }
  40180. var data = null;
  40181. var tempData = null;
  40182. var line;
  40183. var lines = text.split('\n');
  40184. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40185. var maxColor = 0;
  40186. for (var i = 0; i < lines.length; i++) {
  40187. line = lines[i];
  40188. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40189. continue;
  40190. if (line.indexOf('#') === 0)
  40191. continue;
  40192. var words = line.split(" ");
  40193. if (size === 0) {
  40194. // Number of space + one
  40195. size = words.length;
  40196. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40197. tempData = new Float32Array(size * size * size * 4);
  40198. continue;
  40199. }
  40200. if (size != 0) {
  40201. var r = Math.max(parseInt(words[0]), 0);
  40202. var g = Math.max(parseInt(words[1]), 0);
  40203. var b = Math.max(parseInt(words[2]), 0);
  40204. maxColor = Math.max(r, maxColor);
  40205. maxColor = Math.max(g, maxColor);
  40206. maxColor = Math.max(b, maxColor);
  40207. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40208. if (tempData) {
  40209. tempData[pixelStorageIndex + 0] = r;
  40210. tempData[pixelStorageIndex + 1] = g;
  40211. tempData[pixelStorageIndex + 2] = b;
  40212. }
  40213. pixelIndexSlice++;
  40214. if (pixelIndexSlice % size == 0) {
  40215. pixelIndexH++;
  40216. pixelIndexSlice = 0;
  40217. if (pixelIndexH % size == 0) {
  40218. pixelIndexW++;
  40219. pixelIndexH = 0;
  40220. }
  40221. }
  40222. }
  40223. }
  40224. if (tempData && data) {
  40225. for (var i = 0; i < tempData.length; i++) {
  40226. if (i > 0 && (i + 1) % 4 === 0) {
  40227. data[i] = 255;
  40228. }
  40229. else {
  40230. var value = tempData[i];
  40231. data[i] = (value / maxColor * 255);
  40232. }
  40233. }
  40234. }
  40235. if (texture.is3D) {
  40236. texture.updateSize(size, size, size);
  40237. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40238. }
  40239. else {
  40240. texture.updateSize(size * size, size);
  40241. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40242. }
  40243. };
  40244. var scene = this.getScene();
  40245. if (scene) {
  40246. scene._loadFile(this.url, callback);
  40247. }
  40248. else {
  40249. this._engine._loadFile(this.url, callback);
  40250. }
  40251. return this._texture;
  40252. };
  40253. /**
  40254. * Starts the loading process of the texture.
  40255. */
  40256. ColorGradingTexture.prototype.loadTexture = function () {
  40257. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  40258. this.load3dlTexture();
  40259. }
  40260. };
  40261. /**
  40262. * Clones the color gradind texture.
  40263. */
  40264. ColorGradingTexture.prototype.clone = function () {
  40265. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  40266. // Base texture
  40267. newTexture.level = this.level;
  40268. return newTexture;
  40269. };
  40270. /**
  40271. * Called during delayed load for textures.
  40272. */
  40273. ColorGradingTexture.prototype.delayLoad = function () {
  40274. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40275. return;
  40276. }
  40277. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40278. this._texture = this._getFromCache(this.url, true);
  40279. if (!this._texture) {
  40280. this.loadTexture();
  40281. }
  40282. };
  40283. /**
  40284. * Parses a color grading texture serialized by Babylon.
  40285. * @param parsedTexture The texture information being parsedTexture
  40286. * @param scene The scene to load the texture in
  40287. * @param rootUrl The root url of the data assets to load
  40288. * @return A color gradind texture
  40289. */
  40290. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40291. var texture = null;
  40292. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40293. texture = new ColorGradingTexture(parsedTexture.name, scene);
  40294. texture.name = parsedTexture.name;
  40295. texture.level = parsedTexture.level;
  40296. }
  40297. return texture;
  40298. };
  40299. /**
  40300. * Serializes the LUT texture to json format.
  40301. */
  40302. ColorGradingTexture.prototype.serialize = function () {
  40303. if (!this.name) {
  40304. return null;
  40305. }
  40306. var serializationObject = {};
  40307. serializationObject.name = this.name;
  40308. serializationObject.level = this.level;
  40309. serializationObject.customType = "BABYLON.ColorGradingTexture";
  40310. return serializationObject;
  40311. };
  40312. /**
  40313. * Empty line regex stored for GC.
  40314. */
  40315. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  40316. return ColorGradingTexture;
  40317. }(BABYLON.BaseTexture));
  40318. BABYLON.ColorGradingTexture = ColorGradingTexture;
  40319. })(BABYLON || (BABYLON = {}));
  40320. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  40321. "use strict";
  40322. var BABYLON;
  40323. (function (BABYLON) {
  40324. /**
  40325. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40326. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40327. * 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;
  40328. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40329. */
  40330. var ColorCurves = /** @class */ (function () {
  40331. function ColorCurves() {
  40332. this._dirty = true;
  40333. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  40334. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  40335. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40336. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  40337. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40338. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  40339. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  40340. this._globalHue = 30;
  40341. this._globalDensity = 0;
  40342. this._globalSaturation = 0;
  40343. this._globalExposure = 0;
  40344. this._highlightsHue = 30;
  40345. this._highlightsDensity = 0;
  40346. this._highlightsSaturation = 0;
  40347. this._highlightsExposure = 0;
  40348. this._midtonesHue = 30;
  40349. this._midtonesDensity = 0;
  40350. this._midtonesSaturation = 0;
  40351. this._midtonesExposure = 0;
  40352. this._shadowsHue = 30;
  40353. this._shadowsDensity = 0;
  40354. this._shadowsSaturation = 0;
  40355. this._shadowsExposure = 0;
  40356. }
  40357. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  40358. /**
  40359. * Gets the global Hue value.
  40360. * 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).
  40361. */
  40362. get: function () {
  40363. return this._globalHue;
  40364. },
  40365. /**
  40366. * Sets the global Hue value.
  40367. * 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).
  40368. */
  40369. set: function (value) {
  40370. this._globalHue = value;
  40371. this._dirty = true;
  40372. },
  40373. enumerable: true,
  40374. configurable: true
  40375. });
  40376. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  40377. /**
  40378. * Gets the global Density value.
  40379. * 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.
  40380. * Values less than zero provide a filter of opposite hue.
  40381. */
  40382. get: function () {
  40383. return this._globalDensity;
  40384. },
  40385. /**
  40386. * Sets the global Density value.
  40387. * 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.
  40388. * Values less than zero provide a filter of opposite hue.
  40389. */
  40390. set: function (value) {
  40391. this._globalDensity = value;
  40392. this._dirty = true;
  40393. },
  40394. enumerable: true,
  40395. configurable: true
  40396. });
  40397. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  40398. /**
  40399. * Gets the global Saturation value.
  40400. * 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.
  40401. */
  40402. get: function () {
  40403. return this._globalSaturation;
  40404. },
  40405. /**
  40406. * Sets the global Saturation value.
  40407. * 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.
  40408. */
  40409. set: function (value) {
  40410. this._globalSaturation = value;
  40411. this._dirty = true;
  40412. },
  40413. enumerable: true,
  40414. configurable: true
  40415. });
  40416. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  40417. /**
  40418. * Gets the highlights Hue value.
  40419. * 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).
  40420. */
  40421. get: function () {
  40422. return this._highlightsHue;
  40423. },
  40424. /**
  40425. * Sets the highlights Hue value.
  40426. * 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).
  40427. */
  40428. set: function (value) {
  40429. this._highlightsHue = value;
  40430. this._dirty = true;
  40431. },
  40432. enumerable: true,
  40433. configurable: true
  40434. });
  40435. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  40436. /**
  40437. * Gets the highlights Density value.
  40438. * 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.
  40439. * Values less than zero provide a filter of opposite hue.
  40440. */
  40441. get: function () {
  40442. return this._highlightsDensity;
  40443. },
  40444. /**
  40445. * Sets the highlights Density value.
  40446. * 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.
  40447. * Values less than zero provide a filter of opposite hue.
  40448. */
  40449. set: function (value) {
  40450. this._highlightsDensity = value;
  40451. this._dirty = true;
  40452. },
  40453. enumerable: true,
  40454. configurable: true
  40455. });
  40456. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  40457. /**
  40458. * Gets the highlights Saturation value.
  40459. * 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.
  40460. */
  40461. get: function () {
  40462. return this._highlightsSaturation;
  40463. },
  40464. /**
  40465. * Sets the highlights Saturation value.
  40466. * 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.
  40467. */
  40468. set: function (value) {
  40469. this._highlightsSaturation = value;
  40470. this._dirty = true;
  40471. },
  40472. enumerable: true,
  40473. configurable: true
  40474. });
  40475. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  40476. /**
  40477. * Gets the highlights Exposure value.
  40478. * 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.
  40479. */
  40480. get: function () {
  40481. return this._highlightsExposure;
  40482. },
  40483. /**
  40484. * Sets the highlights Exposure value.
  40485. * 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.
  40486. */
  40487. set: function (value) {
  40488. this._highlightsExposure = value;
  40489. this._dirty = true;
  40490. },
  40491. enumerable: true,
  40492. configurable: true
  40493. });
  40494. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  40495. /**
  40496. * Gets the midtones Hue value.
  40497. * 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).
  40498. */
  40499. get: function () {
  40500. return this._midtonesHue;
  40501. },
  40502. /**
  40503. * Sets the midtones Hue value.
  40504. * 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).
  40505. */
  40506. set: function (value) {
  40507. this._midtonesHue = value;
  40508. this._dirty = true;
  40509. },
  40510. enumerable: true,
  40511. configurable: true
  40512. });
  40513. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  40514. /**
  40515. * Gets the midtones Density value.
  40516. * 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.
  40517. * Values less than zero provide a filter of opposite hue.
  40518. */
  40519. get: function () {
  40520. return this._midtonesDensity;
  40521. },
  40522. /**
  40523. * Sets the midtones Density value.
  40524. * 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.
  40525. * Values less than zero provide a filter of opposite hue.
  40526. */
  40527. set: function (value) {
  40528. this._midtonesDensity = value;
  40529. this._dirty = true;
  40530. },
  40531. enumerable: true,
  40532. configurable: true
  40533. });
  40534. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  40535. /**
  40536. * Gets the midtones Saturation value.
  40537. * 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.
  40538. */
  40539. get: function () {
  40540. return this._midtonesSaturation;
  40541. },
  40542. /**
  40543. * Sets the midtones Saturation value.
  40544. * 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.
  40545. */
  40546. set: function (value) {
  40547. this._midtonesSaturation = value;
  40548. this._dirty = true;
  40549. },
  40550. enumerable: true,
  40551. configurable: true
  40552. });
  40553. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  40554. /**
  40555. * Gets the midtones Exposure value.
  40556. * 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.
  40557. */
  40558. get: function () {
  40559. return this._midtonesExposure;
  40560. },
  40561. /**
  40562. * Sets the midtones Exposure value.
  40563. * 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.
  40564. */
  40565. set: function (value) {
  40566. this._midtonesExposure = value;
  40567. this._dirty = true;
  40568. },
  40569. enumerable: true,
  40570. configurable: true
  40571. });
  40572. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  40573. /**
  40574. * Gets the shadows Hue value.
  40575. * 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).
  40576. */
  40577. get: function () {
  40578. return this._shadowsHue;
  40579. },
  40580. /**
  40581. * Sets the shadows Hue value.
  40582. * 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).
  40583. */
  40584. set: function (value) {
  40585. this._shadowsHue = value;
  40586. this._dirty = true;
  40587. },
  40588. enumerable: true,
  40589. configurable: true
  40590. });
  40591. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  40592. /**
  40593. * Gets the shadows Density value.
  40594. * 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.
  40595. * Values less than zero provide a filter of opposite hue.
  40596. */
  40597. get: function () {
  40598. return this._shadowsDensity;
  40599. },
  40600. /**
  40601. * Sets the shadows Density value.
  40602. * 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.
  40603. * Values less than zero provide a filter of opposite hue.
  40604. */
  40605. set: function (value) {
  40606. this._shadowsDensity = value;
  40607. this._dirty = true;
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  40613. /**
  40614. * Gets the shadows Saturation value.
  40615. * 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.
  40616. */
  40617. get: function () {
  40618. return this._shadowsSaturation;
  40619. },
  40620. /**
  40621. * Sets the shadows Saturation value.
  40622. * 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.
  40623. */
  40624. set: function (value) {
  40625. this._shadowsSaturation = value;
  40626. this._dirty = true;
  40627. },
  40628. enumerable: true,
  40629. configurable: true
  40630. });
  40631. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  40632. /**
  40633. * Gets the shadows Exposure value.
  40634. * 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.
  40635. */
  40636. get: function () {
  40637. return this._shadowsExposure;
  40638. },
  40639. /**
  40640. * Sets the shadows Exposure value.
  40641. * 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.
  40642. */
  40643. set: function (value) {
  40644. this._shadowsExposure = value;
  40645. this._dirty = true;
  40646. },
  40647. enumerable: true,
  40648. configurable: true
  40649. });
  40650. ColorCurves.prototype.getClassName = function () {
  40651. return "ColorCurves";
  40652. };
  40653. /**
  40654. * Binds the color curves to the shader.
  40655. * @param colorCurves The color curve to bind
  40656. * @param effect The effect to bind to
  40657. */
  40658. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  40659. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  40660. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  40661. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  40662. if (colorCurves._dirty) {
  40663. colorCurves._dirty = false;
  40664. // Fill in global info.
  40665. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  40666. // Compute highlights info.
  40667. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  40668. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  40669. // Compute midtones info.
  40670. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  40671. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  40672. // Compute shadows info.
  40673. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  40674. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  40675. // Compute deltas (neutral is midtones).
  40676. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  40677. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  40678. }
  40679. if (effect) {
  40680. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  40681. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  40682. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  40683. }
  40684. };
  40685. /**
  40686. * Prepare the list of uniforms associated with the ColorCurves effects.
  40687. * @param uniformsList The list of uniforms used in the effect
  40688. */
  40689. ColorCurves.PrepareUniforms = function (uniformsList) {
  40690. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  40691. };
  40692. /**
  40693. * Returns color grading data based on a hue, density, saturation and exposure value.
  40694. * @param filterHue The hue of the color filter.
  40695. * @param filterDensity The density of the color filter.
  40696. * @param saturation The saturation.
  40697. * @param exposure The exposure.
  40698. * @param result The result data container.
  40699. */
  40700. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  40701. if (hue == null) {
  40702. return;
  40703. }
  40704. hue = ColorCurves.clamp(hue, 0, 360);
  40705. density = ColorCurves.clamp(density, -100, 100);
  40706. saturation = ColorCurves.clamp(saturation, -100, 100);
  40707. exposure = ColorCurves.clamp(exposure, -100, 100);
  40708. // Remap the slider/config filter density with non-linear mapping and also scale by half
  40709. // so that the maximum filter density is only 50% control. This provides fine control
  40710. // for small values and reasonable range.
  40711. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  40712. density *= 0.5;
  40713. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  40714. if (density < 0) {
  40715. density *= -1;
  40716. hue = (hue + 180) % 360;
  40717. }
  40718. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  40719. result.scaleToRef(2, result);
  40720. result.a = 1 + 0.01 * saturation;
  40721. };
  40722. /**
  40723. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  40724. * @param value The input slider value in range [-100,100].
  40725. * @returns Adjusted value.
  40726. */
  40727. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  40728. value /= 100;
  40729. var x = Math.abs(value);
  40730. x = Math.pow(x, 2);
  40731. if (value < 0) {
  40732. x *= -1;
  40733. }
  40734. x *= 100;
  40735. return x;
  40736. };
  40737. /**
  40738. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  40739. * @param hue The hue (H) input.
  40740. * @param saturation The saturation (S) input.
  40741. * @param brightness The brightness (B) input.
  40742. * @result An RGBA color represented as Vector4.
  40743. */
  40744. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  40745. var h = ColorCurves.clamp(hue, 0, 360);
  40746. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  40747. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  40748. if (s === 0) {
  40749. result.r = v;
  40750. result.g = v;
  40751. result.b = v;
  40752. }
  40753. else {
  40754. // sector 0 to 5
  40755. h /= 60;
  40756. var i = Math.floor(h);
  40757. // fractional part of h
  40758. var f = h - i;
  40759. var p = v * (1 - s);
  40760. var q = v * (1 - s * f);
  40761. var t = v * (1 - s * (1 - f));
  40762. switch (i) {
  40763. case 0:
  40764. result.r = v;
  40765. result.g = t;
  40766. result.b = p;
  40767. break;
  40768. case 1:
  40769. result.r = q;
  40770. result.g = v;
  40771. result.b = p;
  40772. break;
  40773. case 2:
  40774. result.r = p;
  40775. result.g = v;
  40776. result.b = t;
  40777. break;
  40778. case 3:
  40779. result.r = p;
  40780. result.g = q;
  40781. result.b = v;
  40782. break;
  40783. case 4:
  40784. result.r = t;
  40785. result.g = p;
  40786. result.b = v;
  40787. break;
  40788. default:// case 5:
  40789. result.r = v;
  40790. result.g = p;
  40791. result.b = q;
  40792. break;
  40793. }
  40794. }
  40795. result.a = 1;
  40796. };
  40797. /**
  40798. * Returns a value clamped between min and max
  40799. * @param value The value to clamp
  40800. * @param min The minimum of value
  40801. * @param max The maximum of value
  40802. * @returns The clamped value.
  40803. */
  40804. ColorCurves.clamp = function (value, min, max) {
  40805. return Math.min(Math.max(value, min), max);
  40806. };
  40807. /**
  40808. * Clones the current color curve instance.
  40809. * @return The cloned curves
  40810. */
  40811. ColorCurves.prototype.clone = function () {
  40812. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  40813. };
  40814. /**
  40815. * Serializes the current color curve instance to a json representation.
  40816. * @return a JSON representation
  40817. */
  40818. ColorCurves.prototype.serialize = function () {
  40819. return BABYLON.SerializationHelper.Serialize(this);
  40820. };
  40821. /**
  40822. * Parses the color curve from a json representation.
  40823. * @param source the JSON source to parse
  40824. * @return The parsed curves
  40825. */
  40826. ColorCurves.Parse = function (source) {
  40827. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  40828. };
  40829. __decorate([
  40830. BABYLON.serialize()
  40831. ], ColorCurves.prototype, "_globalHue", void 0);
  40832. __decorate([
  40833. BABYLON.serialize()
  40834. ], ColorCurves.prototype, "_globalDensity", void 0);
  40835. __decorate([
  40836. BABYLON.serialize()
  40837. ], ColorCurves.prototype, "_globalSaturation", void 0);
  40838. __decorate([
  40839. BABYLON.serialize()
  40840. ], ColorCurves.prototype, "_globalExposure", void 0);
  40841. __decorate([
  40842. BABYLON.serialize()
  40843. ], ColorCurves.prototype, "_highlightsHue", void 0);
  40844. __decorate([
  40845. BABYLON.serialize()
  40846. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  40847. __decorate([
  40848. BABYLON.serialize()
  40849. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  40850. __decorate([
  40851. BABYLON.serialize()
  40852. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  40853. __decorate([
  40854. BABYLON.serialize()
  40855. ], ColorCurves.prototype, "_midtonesHue", void 0);
  40856. __decorate([
  40857. BABYLON.serialize()
  40858. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  40859. __decorate([
  40860. BABYLON.serialize()
  40861. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  40862. __decorate([
  40863. BABYLON.serialize()
  40864. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  40865. return ColorCurves;
  40866. }());
  40867. BABYLON.ColorCurves = ColorCurves;
  40868. })(BABYLON || (BABYLON = {}));
  40869. //# sourceMappingURL=babylon.colorCurves.js.map
  40870. "use strict";
  40871. //# sourceMappingURL=babylon.behavior.js.map
  40872. "use strict";
  40873. var BABYLON;
  40874. (function (BABYLON) {
  40875. /**
  40876. * "Static Class" containing the most commonly used helper while dealing with material for
  40877. * rendering purpose.
  40878. *
  40879. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40880. *
  40881. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40882. */
  40883. var MaterialHelper = /** @class */ (function () {
  40884. function MaterialHelper() {
  40885. }
  40886. /**
  40887. * Bind the current view position to an effect.
  40888. * @param effect The effect to be bound
  40889. * @param scene The scene the eyes position is used from
  40890. */
  40891. MaterialHelper.BindEyePosition = function (effect, scene) {
  40892. if (scene._forcedViewPosition) {
  40893. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40894. return;
  40895. }
  40896. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40897. };
  40898. /**
  40899. * Helps preparing the defines values about the UVs in used in the effect.
  40900. * UVs are shared as much as we can accross chanels in the shaders.
  40901. * @param texture The texture we are preparing the UVs for
  40902. * @param defines The defines to update
  40903. * @param key The chanel key "diffuse", "specular"... used in the shader
  40904. */
  40905. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40906. defines._needUVs = true;
  40907. defines[key] = true;
  40908. if (texture.getTextureMatrix().isIdentity(true)) {
  40909. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40910. if (texture.coordinatesIndex === 0) {
  40911. defines["MAINUV1"] = true;
  40912. }
  40913. else {
  40914. defines["MAINUV2"] = true;
  40915. }
  40916. }
  40917. else {
  40918. defines[key + "DIRECTUV"] = 0;
  40919. }
  40920. };
  40921. /**
  40922. * Binds a texture matrix value to its corrsponding uniform
  40923. * @param texture The texture to bind the matrix for
  40924. * @param uniformBuffer The uniform buffer receivin the data
  40925. * @param key The chanel key "diffuse", "specular"... used in the shader
  40926. */
  40927. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40928. var matrix = texture.getTextureMatrix();
  40929. if (!matrix.isIdentity(true)) {
  40930. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40931. }
  40932. };
  40933. /**
  40934. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40935. * @param mesh defines the current mesh
  40936. * @param scene defines the current scene
  40937. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40938. * @param pointsCloud defines if point cloud rendering has to be turned on
  40939. * @param fogEnabled defines if fog has to be turned on
  40940. * @param alphaTest defines if alpha testing has to be turned on
  40941. * @param defines defines the current list of defines
  40942. */
  40943. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40944. if (defines._areMiscDirty) {
  40945. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40946. defines["POINTSIZE"] = pointsCloud;
  40947. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40948. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40949. defines["ALPHATEST"] = alphaTest;
  40950. }
  40951. };
  40952. /**
  40953. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40954. * @param scene defines the current scene
  40955. * @param engine defines the current engine
  40956. * @param defines specifies the list of active defines
  40957. * @param useInstances defines if instances have to be turned on
  40958. * @param useClipPlane defines if clip plane have to be turned on
  40959. */
  40960. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40961. if (useClipPlane === void 0) { useClipPlane = null; }
  40962. var changed = false;
  40963. if (useClipPlane == null) {
  40964. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40965. }
  40966. if (defines["CLIPPLANE"] !== useClipPlane) {
  40967. defines["CLIPPLANE"] = useClipPlane;
  40968. changed = true;
  40969. }
  40970. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40971. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40972. changed = true;
  40973. }
  40974. if (defines["INSTANCES"] !== useInstances) {
  40975. defines["INSTANCES"] = useInstances;
  40976. changed = true;
  40977. }
  40978. if (changed) {
  40979. defines.markAsUnprocessed();
  40980. }
  40981. };
  40982. /**
  40983. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40984. * @param mesh The mesh containing the geometry data we will draw
  40985. * @param defines The defines to update
  40986. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40987. * @param useBones Precise whether bones should be used or not (override mesh info)
  40988. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40989. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40990. * @returns false if defines are considered not dirty and have not been checked
  40991. */
  40992. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40993. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40994. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40995. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40996. return false;
  40997. }
  40998. defines._normals = defines._needNormals;
  40999. defines._uvs = defines._needUVs;
  41000. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41001. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41002. defines["TANGENT"] = true;
  41003. }
  41004. if (defines._needUVs) {
  41005. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41006. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41007. }
  41008. else {
  41009. defines["UV1"] = false;
  41010. defines["UV2"] = false;
  41011. }
  41012. if (useVertexColor) {
  41013. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41014. defines["VERTEXCOLOR"] = hasVertexColors;
  41015. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41016. }
  41017. if (useBones) {
  41018. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41019. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41020. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41021. }
  41022. else {
  41023. defines["NUM_BONE_INFLUENCERS"] = 0;
  41024. defines["BonesPerMesh"] = 0;
  41025. }
  41026. }
  41027. if (useMorphTargets) {
  41028. var manager = mesh.morphTargetManager;
  41029. if (manager) {
  41030. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41031. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41032. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41033. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41034. }
  41035. else {
  41036. defines["MORPHTARGETS_TANGENT"] = false;
  41037. defines["MORPHTARGETS_NORMAL"] = false;
  41038. defines["MORPHTARGETS"] = false;
  41039. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41040. }
  41041. }
  41042. return true;
  41043. };
  41044. /**
  41045. * Prepares the defines related to the light information passed in parameter
  41046. * @param scene The scene we are intending to draw
  41047. * @param mesh The mesh the effect is compiling for
  41048. * @param defines The defines to update
  41049. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41050. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41051. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41052. * @returns true if normals will be required for the rest of the effect
  41053. */
  41054. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41055. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41056. if (disableLighting === void 0) { disableLighting = false; }
  41057. if (!defines._areLightsDirty) {
  41058. return defines._needNormals;
  41059. }
  41060. var lightIndex = 0;
  41061. var needNormals = false;
  41062. var needRebuild = false;
  41063. var lightmapMode = false;
  41064. var shadowEnabled = false;
  41065. var specularEnabled = false;
  41066. if (scene.lightsEnabled && !disableLighting) {
  41067. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41068. var light = _a[_i];
  41069. needNormals = true;
  41070. if (defines["LIGHT" + lightIndex] === undefined) {
  41071. needRebuild = true;
  41072. }
  41073. defines["LIGHT" + lightIndex] = true;
  41074. defines["SPOTLIGHT" + lightIndex] = false;
  41075. defines["HEMILIGHT" + lightIndex] = false;
  41076. defines["POINTLIGHT" + lightIndex] = false;
  41077. defines["DIRLIGHT" + lightIndex] = false;
  41078. var type;
  41079. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41080. type = "SPOTLIGHT" + lightIndex;
  41081. var spotLight = light;
  41082. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41083. }
  41084. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41085. type = "HEMILIGHT" + lightIndex;
  41086. }
  41087. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41088. type = "POINTLIGHT" + lightIndex;
  41089. }
  41090. else {
  41091. type = "DIRLIGHT" + lightIndex;
  41092. }
  41093. defines[type] = true;
  41094. // Specular
  41095. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41096. specularEnabled = true;
  41097. }
  41098. // Shadows
  41099. defines["SHADOW" + lightIndex] = false;
  41100. defines["SHADOWPCF" + lightIndex] = false;
  41101. defines["SHADOWPCSS" + lightIndex] = false;
  41102. defines["SHADOWPOISSON" + lightIndex] = false;
  41103. defines["SHADOWESM" + lightIndex] = false;
  41104. defines["SHADOWCUBE" + lightIndex] = false;
  41105. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41106. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41107. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41108. var shadowGenerator = light.getShadowGenerator();
  41109. if (shadowGenerator) {
  41110. shadowEnabled = true;
  41111. shadowGenerator.prepareDefines(defines, lightIndex);
  41112. }
  41113. }
  41114. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41115. lightmapMode = true;
  41116. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41117. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41118. }
  41119. else {
  41120. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41121. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41122. }
  41123. lightIndex++;
  41124. if (lightIndex === maxSimultaneousLights)
  41125. break;
  41126. }
  41127. }
  41128. defines["SPECULARTERM"] = specularEnabled;
  41129. defines["SHADOWS"] = shadowEnabled;
  41130. // Resetting all other lights if any
  41131. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41132. if (defines["LIGHT" + index] !== undefined) {
  41133. defines["LIGHT" + index] = false;
  41134. defines["HEMILIGHT" + lightIndex] = false;
  41135. defines["POINTLIGHT" + lightIndex] = false;
  41136. defines["DIRLIGHT" + lightIndex] = false;
  41137. defines["SPOTLIGHT" + lightIndex] = false;
  41138. defines["SHADOW" + lightIndex] = false;
  41139. }
  41140. }
  41141. var caps = scene.getEngine().getCaps();
  41142. if (defines["SHADOWFLOAT"] === undefined) {
  41143. needRebuild = true;
  41144. }
  41145. defines["SHADOWFLOAT"] = shadowEnabled &&
  41146. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41147. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41148. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41149. if (needRebuild) {
  41150. defines.rebuild();
  41151. }
  41152. return needNormals;
  41153. };
  41154. /**
  41155. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41156. * that won t be acctive due to defines being turned off.
  41157. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41158. * @param samplersList The samplers list
  41159. * @param defines The defines helping in the list generation
  41160. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41161. */
  41162. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41163. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41164. var uniformsList;
  41165. var uniformBuffersList = null;
  41166. if (uniformsListOrOptions.uniformsNames) {
  41167. var options = uniformsListOrOptions;
  41168. uniformsList = options.uniformsNames;
  41169. uniformBuffersList = options.uniformBuffersNames;
  41170. samplersList = options.samplers;
  41171. defines = options.defines;
  41172. maxSimultaneousLights = options.maxSimultaneousLights;
  41173. }
  41174. else {
  41175. uniformsList = uniformsListOrOptions;
  41176. if (!samplersList) {
  41177. samplersList = [];
  41178. }
  41179. }
  41180. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41181. if (!defines["LIGHT" + lightIndex]) {
  41182. break;
  41183. }
  41184. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41185. if (uniformBuffersList) {
  41186. uniformBuffersList.push("Light" + lightIndex);
  41187. }
  41188. samplersList.push("shadowSampler" + lightIndex);
  41189. samplersList.push("depthSampler" + lightIndex);
  41190. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41191. samplersList.push("projectionLightSampler" + lightIndex);
  41192. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41193. }
  41194. }
  41195. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41196. uniformsList.push("morphTargetInfluences");
  41197. }
  41198. };
  41199. /**
  41200. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41201. * @param defines The defines to update while falling back
  41202. * @param fallbacks The authorized effect fallbacks
  41203. * @param maxSimultaneousLights The maximum number of lights allowed
  41204. * @param rank the current rank of the Effect
  41205. * @returns The newly affected rank
  41206. */
  41207. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41208. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41209. if (rank === void 0) { rank = 0; }
  41210. var lightFallbackRank = 0;
  41211. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41212. if (!defines["LIGHT" + lightIndex]) {
  41213. break;
  41214. }
  41215. if (lightIndex > 0) {
  41216. lightFallbackRank = rank + lightIndex;
  41217. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41218. }
  41219. if (!defines["SHADOWS"]) {
  41220. if (defines["SHADOW" + lightIndex]) {
  41221. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41222. }
  41223. if (defines["SHADOWPCF" + lightIndex]) {
  41224. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41225. }
  41226. if (defines["SHADOWPCSS" + lightIndex]) {
  41227. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41228. }
  41229. if (defines["SHADOWPOISSON" + lightIndex]) {
  41230. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41231. }
  41232. if (defines["SHADOWESM" + lightIndex]) {
  41233. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41234. }
  41235. }
  41236. }
  41237. return lightFallbackRank++;
  41238. };
  41239. /**
  41240. * Prepares the list of attributes required for morph targets according to the effect defines.
  41241. * @param attribs The current list of supported attribs
  41242. * @param mesh The mesh to prepare the morph targets attributes for
  41243. * @param defines The current Defines of the effect
  41244. */
  41245. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41246. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41247. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41248. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41249. var manager = mesh.morphTargetManager;
  41250. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41251. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41252. for (var index = 0; index < influencers; index++) {
  41253. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41254. if (normal) {
  41255. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41256. }
  41257. if (tangent) {
  41258. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41259. }
  41260. if (attribs.length > maxAttributesCount) {
  41261. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41262. }
  41263. }
  41264. }
  41265. };
  41266. /**
  41267. * Prepares the list of attributes required for bones according to the effect defines.
  41268. * @param attribs The current list of supported attribs
  41269. * @param mesh The mesh to prepare the bones attributes for
  41270. * @param defines The current Defines of the effect
  41271. * @param fallbacks The current efffect fallback strategy
  41272. */
  41273. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41274. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41275. fallbacks.addCPUSkinningFallback(0, mesh);
  41276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41278. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41279. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41280. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41281. }
  41282. }
  41283. };
  41284. /**
  41285. * Prepares the list of attributes required for instances according to the effect defines.
  41286. * @param attribs The current list of supported attribs
  41287. * @param defines The current Defines of the effect
  41288. */
  41289. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41290. if (defines["INSTANCES"]) {
  41291. attribs.push("world0");
  41292. attribs.push("world1");
  41293. attribs.push("world2");
  41294. attribs.push("world3");
  41295. }
  41296. };
  41297. /**
  41298. * Binds the light shadow information to the effect for the given mesh.
  41299. * @param light The light containing the generator
  41300. * @param scene The scene the lights belongs to
  41301. * @param mesh The mesh we are binding the information to render
  41302. * @param lightIndex The light index in the effect used to render the mesh
  41303. * @param effect The effect we are binding the data to
  41304. */
  41305. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41306. if (light.shadowEnabled && mesh.receiveShadows) {
  41307. var shadowGenerator = light.getShadowGenerator();
  41308. if (shadowGenerator) {
  41309. shadowGenerator.bindShadowLight(lightIndex, effect);
  41310. }
  41311. }
  41312. };
  41313. /**
  41314. * Binds the light information to the effect.
  41315. * @param light The light containing the generator
  41316. * @param effect The effect we are binding the data to
  41317. * @param lightIndex The light index in the effect used to render
  41318. */
  41319. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41320. light.transferToEffect(effect, lightIndex + "");
  41321. };
  41322. /**
  41323. * Binds the lights information from the scene to the effect for the given mesh.
  41324. * @param scene The scene the lights belongs to
  41325. * @param mesh The mesh we are binding the information to render
  41326. * @param effect The effect we are binding the data to
  41327. * @param defines The generated defines for the effect
  41328. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41329. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41330. */
  41331. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41332. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41333. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41334. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41335. for (var i = 0; i < len; i++) {
  41336. var light = mesh._lightSources[i];
  41337. var iAsString = i.toString();
  41338. var scaledIntensity = light.getScaledIntensity();
  41339. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41340. MaterialHelper.BindLightProperties(light, effect, i);
  41341. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41342. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41343. if (defines["SPECULARTERM"]) {
  41344. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41345. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41346. }
  41347. // Shadows
  41348. if (scene.shadowsEnabled) {
  41349. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41350. }
  41351. light._uniformBuffer.update();
  41352. }
  41353. };
  41354. /**
  41355. * Binds the fog information from the scene to the effect for the given mesh.
  41356. * @param scene The scene the lights belongs to
  41357. * @param mesh The mesh we are binding the information to render
  41358. * @param effect The effect we are binding the data to
  41359. */
  41360. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41361. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41362. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41363. effect.setColor3("vFogColor", scene.fogColor);
  41364. }
  41365. };
  41366. /**
  41367. * Binds the bones information from the mesh to the effect.
  41368. * @param mesh The mesh we are binding the information to render
  41369. * @param effect The effect we are binding the data to
  41370. */
  41371. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41372. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41373. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41374. if (matrices && effect) {
  41375. effect.setMatrices("mBones", matrices);
  41376. }
  41377. }
  41378. };
  41379. /**
  41380. * Binds the morph targets information from the mesh to the effect.
  41381. * @param abstractMesh The mesh we are binding the information to render
  41382. * @param effect The effect we are binding the data to
  41383. */
  41384. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41385. var manager = abstractMesh.morphTargetManager;
  41386. if (!abstractMesh || !manager) {
  41387. return;
  41388. }
  41389. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41390. };
  41391. /**
  41392. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41393. * @param defines The generated defines used in the effect
  41394. * @param effect The effect we are binding the data to
  41395. * @param scene The scene we are willing to render with logarithmic scale for
  41396. */
  41397. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41398. if (defines["LOGARITHMICDEPTH"]) {
  41399. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41400. }
  41401. };
  41402. /**
  41403. * Binds the clip plane information from the scene to the effect.
  41404. * @param scene The scene the clip plane information are extracted from
  41405. * @param effect The effect we are binding the data to
  41406. */
  41407. MaterialHelper.BindClipPlane = function (effect, scene) {
  41408. if (scene.clipPlane) {
  41409. var clipPlane = scene.clipPlane;
  41410. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41411. }
  41412. };
  41413. return MaterialHelper;
  41414. }());
  41415. BABYLON.MaterialHelper = MaterialHelper;
  41416. })(BABYLON || (BABYLON = {}));
  41417. //# sourceMappingURL=babylon.materialHelper.js.map
  41418. "use strict";
  41419. var BABYLON;
  41420. (function (BABYLON) {
  41421. var PushMaterial = /** @class */ (function (_super) {
  41422. __extends(PushMaterial, _super);
  41423. function PushMaterial(name, scene) {
  41424. var _this = _super.call(this, name, scene) || this;
  41425. _this._normalMatrix = new BABYLON.Matrix();
  41426. _this.storeEffectOnSubMeshes = true;
  41427. return _this;
  41428. }
  41429. PushMaterial.prototype.getEffect = function () {
  41430. return this._activeEffect;
  41431. };
  41432. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41433. if (!mesh) {
  41434. return false;
  41435. }
  41436. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41437. return true;
  41438. }
  41439. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41440. };
  41441. /**
  41442. * Binds the given world matrix to the active effect
  41443. *
  41444. * @param world the matrix to bind
  41445. */
  41446. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41447. this._activeEffect.setMatrix("world", world);
  41448. };
  41449. /**
  41450. * Binds the given normal matrix to the active effect
  41451. *
  41452. * @param normalMatrix the matrix to bind
  41453. */
  41454. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41455. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41456. };
  41457. PushMaterial.prototype.bind = function (world, mesh) {
  41458. if (!mesh) {
  41459. return;
  41460. }
  41461. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41462. };
  41463. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41464. if (effect === void 0) { effect = null; }
  41465. _super.prototype._afterBind.call(this, mesh);
  41466. this.getScene()._cachedEffect = effect;
  41467. };
  41468. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41469. if (visibility === void 0) { visibility = 1; }
  41470. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41471. };
  41472. return PushMaterial;
  41473. }(BABYLON.Material));
  41474. BABYLON.PushMaterial = PushMaterial;
  41475. })(BABYLON || (BABYLON = {}));
  41476. //# sourceMappingURL=babylon.pushMaterial.js.map
  41477. "use strict";
  41478. var BABYLON;
  41479. (function (BABYLON) {
  41480. /** @ignore */
  41481. var StandardMaterialDefines = /** @class */ (function (_super) {
  41482. __extends(StandardMaterialDefines, _super);
  41483. function StandardMaterialDefines() {
  41484. var _this = _super.call(this) || this;
  41485. _this.MAINUV1 = false;
  41486. _this.MAINUV2 = false;
  41487. _this.DIFFUSE = false;
  41488. _this.DIFFUSEDIRECTUV = 0;
  41489. _this.AMBIENT = false;
  41490. _this.AMBIENTDIRECTUV = 0;
  41491. _this.OPACITY = false;
  41492. _this.OPACITYDIRECTUV = 0;
  41493. _this.OPACITYRGB = false;
  41494. _this.REFLECTION = false;
  41495. _this.EMISSIVE = false;
  41496. _this.EMISSIVEDIRECTUV = 0;
  41497. _this.SPECULAR = false;
  41498. _this.SPECULARDIRECTUV = 0;
  41499. _this.BUMP = false;
  41500. _this.BUMPDIRECTUV = 0;
  41501. _this.PARALLAX = false;
  41502. _this.PARALLAXOCCLUSION = false;
  41503. _this.SPECULAROVERALPHA = false;
  41504. _this.CLIPPLANE = false;
  41505. _this.ALPHATEST = false;
  41506. _this.DEPTHPREPASS = false;
  41507. _this.ALPHAFROMDIFFUSE = false;
  41508. _this.POINTSIZE = false;
  41509. _this.FOG = false;
  41510. _this.SPECULARTERM = false;
  41511. _this.DIFFUSEFRESNEL = false;
  41512. _this.OPACITYFRESNEL = false;
  41513. _this.REFLECTIONFRESNEL = false;
  41514. _this.REFRACTIONFRESNEL = false;
  41515. _this.EMISSIVEFRESNEL = false;
  41516. _this.FRESNEL = false;
  41517. _this.NORMAL = false;
  41518. _this.UV1 = false;
  41519. _this.UV2 = false;
  41520. _this.VERTEXCOLOR = false;
  41521. _this.VERTEXALPHA = false;
  41522. _this.NUM_BONE_INFLUENCERS = 0;
  41523. _this.BonesPerMesh = 0;
  41524. _this.INSTANCES = false;
  41525. _this.GLOSSINESS = false;
  41526. _this.ROUGHNESS = false;
  41527. _this.EMISSIVEASILLUMINATION = false;
  41528. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41529. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41530. _this.LIGHTMAP = false;
  41531. _this.LIGHTMAPDIRECTUV = 0;
  41532. _this.OBJECTSPACE_NORMALMAP = false;
  41533. _this.USELIGHTMAPASSHADOWMAP = false;
  41534. _this.REFLECTIONMAP_3D = false;
  41535. _this.REFLECTIONMAP_SPHERICAL = false;
  41536. _this.REFLECTIONMAP_PLANAR = false;
  41537. _this.REFLECTIONMAP_CUBIC = false;
  41538. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41539. _this.REFLECTIONMAP_PROJECTION = false;
  41540. _this.REFLECTIONMAP_SKYBOX = false;
  41541. _this.REFLECTIONMAP_EXPLICIT = false;
  41542. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41543. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41544. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41545. _this.INVERTCUBICMAP = false;
  41546. _this.LOGARITHMICDEPTH = false;
  41547. _this.REFRACTION = false;
  41548. _this.REFRACTIONMAP_3D = false;
  41549. _this.REFLECTIONOVERALPHA = false;
  41550. _this.TWOSIDEDLIGHTING = false;
  41551. _this.SHADOWFLOAT = false;
  41552. _this.MORPHTARGETS = false;
  41553. _this.MORPHTARGETS_NORMAL = false;
  41554. _this.MORPHTARGETS_TANGENT = false;
  41555. _this.NUM_MORPH_INFLUENCERS = 0;
  41556. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41557. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41558. _this.IMAGEPROCESSING = false;
  41559. _this.VIGNETTE = false;
  41560. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41561. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41562. _this.TONEMAPPING = false;
  41563. _this.CONTRAST = false;
  41564. _this.COLORCURVES = false;
  41565. _this.COLORGRADING = false;
  41566. _this.COLORGRADING3D = false;
  41567. _this.SAMPLER3DGREENDEPTH = false;
  41568. _this.SAMPLER3DBGRMAP = false;
  41569. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41570. _this.EXPOSURE = false;
  41571. _this.rebuild();
  41572. return _this;
  41573. }
  41574. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41575. var modes = [
  41576. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41577. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41578. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41579. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41580. ];
  41581. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41582. var mode = modes_1[_i];
  41583. this[mode] = (mode === modeToEnable);
  41584. }
  41585. };
  41586. return StandardMaterialDefines;
  41587. }(BABYLON.MaterialDefines));
  41588. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41589. var StandardMaterial = /** @class */ (function (_super) {
  41590. __extends(StandardMaterial, _super);
  41591. function StandardMaterial(name, scene) {
  41592. var _this = _super.call(this, name, scene) || this;
  41593. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41594. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41595. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41596. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41597. _this.specularPower = 64;
  41598. _this._useAlphaFromDiffuseTexture = false;
  41599. _this._useEmissiveAsIllumination = false;
  41600. _this._linkEmissiveWithDiffuse = false;
  41601. _this._useSpecularOverAlpha = false;
  41602. _this._useReflectionOverAlpha = false;
  41603. _this._disableLighting = false;
  41604. _this._useObjectSpaceNormalMap = false;
  41605. _this._useParallax = false;
  41606. _this._useParallaxOcclusion = false;
  41607. _this.parallaxScaleBias = 0.05;
  41608. _this._roughness = 0;
  41609. _this.indexOfRefraction = 0.98;
  41610. _this.invertRefractionY = true;
  41611. _this._useLightmapAsShadowmap = false;
  41612. _this._useReflectionFresnelFromSpecular = false;
  41613. _this._useGlossinessFromSpecularMapAlpha = false;
  41614. _this._maxSimultaneousLights = 4;
  41615. /**
  41616. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41617. */
  41618. _this._invertNormalMapX = false;
  41619. /**
  41620. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41621. */
  41622. _this._invertNormalMapY = false;
  41623. /**
  41624. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41625. */
  41626. _this._twoSidedLighting = false;
  41627. _this._renderTargets = new BABYLON.SmartArray(16);
  41628. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41629. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41630. // Setup the default processing configuration to the scene.
  41631. _this._attachImageProcessingConfiguration(null);
  41632. _this.getRenderTargetTextures = function () {
  41633. _this._renderTargets.reset();
  41634. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41635. _this._renderTargets.push(_this._reflectionTexture);
  41636. }
  41637. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41638. _this._renderTargets.push(_this._refractionTexture);
  41639. }
  41640. return _this._renderTargets;
  41641. };
  41642. return _this;
  41643. }
  41644. ;
  41645. ;
  41646. ;
  41647. ;
  41648. ;
  41649. ;
  41650. ;
  41651. ;
  41652. ;
  41653. ;
  41654. ;
  41655. ;
  41656. ;
  41657. ;
  41658. ;
  41659. ;
  41660. ;
  41661. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41662. /**
  41663. * Gets the image processing configuration used either in this material.
  41664. */
  41665. get: function () {
  41666. return this._imageProcessingConfiguration;
  41667. },
  41668. /**
  41669. * Sets the Default image processing configuration used either in the this material.
  41670. *
  41671. * If sets to null, the scene one is in use.
  41672. */
  41673. set: function (value) {
  41674. this._attachImageProcessingConfiguration(value);
  41675. // Ensure the effect will be rebuilt.
  41676. this._markAllSubMeshesAsTexturesDirty();
  41677. },
  41678. enumerable: true,
  41679. configurable: true
  41680. });
  41681. /**
  41682. * Attaches a new image processing configuration to the Standard Material.
  41683. * @param configuration
  41684. */
  41685. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41686. var _this = this;
  41687. if (configuration === this._imageProcessingConfiguration) {
  41688. return;
  41689. }
  41690. // Detaches observer.
  41691. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41692. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41693. }
  41694. // Pick the scene configuration if needed.
  41695. if (!configuration) {
  41696. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41697. }
  41698. else {
  41699. this._imageProcessingConfiguration = configuration;
  41700. }
  41701. // Attaches observer.
  41702. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41703. _this._markAllSubMeshesAsImageProcessingDirty();
  41704. });
  41705. };
  41706. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41707. /**
  41708. * Gets wether the color curves effect is enabled.
  41709. */
  41710. get: function () {
  41711. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41712. },
  41713. /**
  41714. * Sets wether the color curves effect is enabled.
  41715. */
  41716. set: function (value) {
  41717. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41718. },
  41719. enumerable: true,
  41720. configurable: true
  41721. });
  41722. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41723. /**
  41724. * Gets wether the color grading effect is enabled.
  41725. */
  41726. get: function () {
  41727. return this.imageProcessingConfiguration.colorGradingEnabled;
  41728. },
  41729. /**
  41730. * Gets wether the color grading effect is enabled.
  41731. */
  41732. set: function (value) {
  41733. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41734. },
  41735. enumerable: true,
  41736. configurable: true
  41737. });
  41738. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41739. /**
  41740. * Gets wether tonemapping is enabled or not.
  41741. */
  41742. get: function () {
  41743. return this._imageProcessingConfiguration.toneMappingEnabled;
  41744. },
  41745. /**
  41746. * Sets wether tonemapping is enabled or not
  41747. */
  41748. set: function (value) {
  41749. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41750. },
  41751. enumerable: true,
  41752. configurable: true
  41753. });
  41754. ;
  41755. ;
  41756. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41757. /**
  41758. * The camera exposure used on this material.
  41759. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41760. * This corresponds to a photographic exposure.
  41761. */
  41762. get: function () {
  41763. return this._imageProcessingConfiguration.exposure;
  41764. },
  41765. /**
  41766. * The camera exposure used on this material.
  41767. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41768. * This corresponds to a photographic exposure.
  41769. */
  41770. set: function (value) {
  41771. this._imageProcessingConfiguration.exposure = value;
  41772. },
  41773. enumerable: true,
  41774. configurable: true
  41775. });
  41776. ;
  41777. ;
  41778. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41779. /**
  41780. * Gets The camera contrast used on this material.
  41781. */
  41782. get: function () {
  41783. return this._imageProcessingConfiguration.contrast;
  41784. },
  41785. /**
  41786. * Sets The camera contrast used on this material.
  41787. */
  41788. set: function (value) {
  41789. this._imageProcessingConfiguration.contrast = value;
  41790. },
  41791. enumerable: true,
  41792. configurable: true
  41793. });
  41794. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41795. /**
  41796. * Gets the Color Grading 2D Lookup Texture.
  41797. */
  41798. get: function () {
  41799. return this._imageProcessingConfiguration.colorGradingTexture;
  41800. },
  41801. /**
  41802. * Sets the Color Grading 2D Lookup Texture.
  41803. */
  41804. set: function (value) {
  41805. this._imageProcessingConfiguration.colorGradingTexture = value;
  41806. },
  41807. enumerable: true,
  41808. configurable: true
  41809. });
  41810. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41811. /**
  41812. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41813. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41814. * 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;
  41815. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41816. */
  41817. get: function () {
  41818. return this._imageProcessingConfiguration.colorCurves;
  41819. },
  41820. /**
  41821. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41822. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41823. * 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;
  41824. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41825. */
  41826. set: function (value) {
  41827. this._imageProcessingConfiguration.colorCurves = value;
  41828. },
  41829. enumerable: true,
  41830. configurable: true
  41831. });
  41832. StandardMaterial.prototype.getClassName = function () {
  41833. return "StandardMaterial";
  41834. };
  41835. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41836. get: function () {
  41837. return this._useLogarithmicDepth;
  41838. },
  41839. set: function (value) {
  41840. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41841. this._markAllSubMeshesAsMiscDirty();
  41842. },
  41843. enumerable: true,
  41844. configurable: true
  41845. });
  41846. StandardMaterial.prototype.needAlphaBlending = function () {
  41847. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41848. };
  41849. StandardMaterial.prototype.needAlphaTesting = function () {
  41850. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41851. };
  41852. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41853. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41854. };
  41855. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41856. return this._diffuseTexture;
  41857. };
  41858. /**
  41859. * Child classes can use it to update shaders
  41860. */
  41861. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41862. if (useInstances === void 0) { useInstances = false; }
  41863. if (subMesh.effect && this.isFrozen) {
  41864. if (this._wasPreviouslyReady && subMesh.effect) {
  41865. return true;
  41866. }
  41867. }
  41868. if (!subMesh._materialDefines) {
  41869. subMesh._materialDefines = new StandardMaterialDefines();
  41870. }
  41871. var scene = this.getScene();
  41872. var defines = subMesh._materialDefines;
  41873. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41874. if (defines._renderId === scene.getRenderId()) {
  41875. return true;
  41876. }
  41877. }
  41878. var engine = scene.getEngine();
  41879. // Lights
  41880. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41881. // Textures
  41882. if (defines._areTexturesDirty) {
  41883. defines._needUVs = false;
  41884. defines.MAINUV1 = false;
  41885. defines.MAINUV2 = false;
  41886. if (scene.texturesEnabled) {
  41887. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41888. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41889. return false;
  41890. }
  41891. else {
  41892. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41893. }
  41894. }
  41895. else {
  41896. defines.DIFFUSE = false;
  41897. }
  41898. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41899. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41900. return false;
  41901. }
  41902. else {
  41903. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41904. }
  41905. }
  41906. else {
  41907. defines.AMBIENT = false;
  41908. }
  41909. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41910. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41911. return false;
  41912. }
  41913. else {
  41914. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41915. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41916. }
  41917. }
  41918. else {
  41919. defines.OPACITY = false;
  41920. }
  41921. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41922. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41923. return false;
  41924. }
  41925. else {
  41926. defines._needNormals = true;
  41927. defines.REFLECTION = true;
  41928. defines.ROUGHNESS = (this._roughness > 0);
  41929. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41930. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41931. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41932. switch (this._reflectionTexture.coordinatesMode) {
  41933. case BABYLON.Texture.CUBIC_MODE:
  41934. case BABYLON.Texture.INVCUBIC_MODE:
  41935. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41936. break;
  41937. case BABYLON.Texture.EXPLICIT_MODE:
  41938. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41939. break;
  41940. case BABYLON.Texture.PLANAR_MODE:
  41941. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41942. break;
  41943. case BABYLON.Texture.PROJECTION_MODE:
  41944. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41945. break;
  41946. case BABYLON.Texture.SKYBOX_MODE:
  41947. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41948. break;
  41949. case BABYLON.Texture.SPHERICAL_MODE:
  41950. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41951. break;
  41952. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41953. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41954. break;
  41955. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41956. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41957. break;
  41958. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41959. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41960. break;
  41961. }
  41962. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41963. }
  41964. }
  41965. else {
  41966. defines.REFLECTION = false;
  41967. }
  41968. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41969. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41970. return false;
  41971. }
  41972. else {
  41973. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41974. }
  41975. }
  41976. else {
  41977. defines.EMISSIVE = false;
  41978. }
  41979. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41980. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41981. return false;
  41982. }
  41983. else {
  41984. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41985. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41986. }
  41987. }
  41988. else {
  41989. defines.LIGHTMAP = false;
  41990. }
  41991. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41992. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41993. return false;
  41994. }
  41995. else {
  41996. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41997. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41998. }
  41999. }
  42000. else {
  42001. defines.SPECULAR = false;
  42002. }
  42003. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42004. // Bump texure can not be not blocking.
  42005. if (!this._bumpTexture.isReady()) {
  42006. return false;
  42007. }
  42008. else {
  42009. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42010. defines.PARALLAX = this._useParallax;
  42011. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42012. }
  42013. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42014. }
  42015. else {
  42016. defines.BUMP = false;
  42017. }
  42018. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42019. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42020. return false;
  42021. }
  42022. else {
  42023. defines._needUVs = true;
  42024. defines.REFRACTION = true;
  42025. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42026. }
  42027. }
  42028. else {
  42029. defines.REFRACTION = false;
  42030. }
  42031. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42032. }
  42033. else {
  42034. defines.DIFFUSE = false;
  42035. defines.AMBIENT = false;
  42036. defines.OPACITY = false;
  42037. defines.REFLECTION = false;
  42038. defines.EMISSIVE = false;
  42039. defines.LIGHTMAP = false;
  42040. defines.BUMP = false;
  42041. defines.REFRACTION = false;
  42042. }
  42043. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42044. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42045. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42046. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42047. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42048. }
  42049. if (defines._areImageProcessingDirty) {
  42050. if (!this._imageProcessingConfiguration.isReady()) {
  42051. return false;
  42052. }
  42053. this._imageProcessingConfiguration.prepareDefines(defines);
  42054. }
  42055. if (defines._areFresnelDirty) {
  42056. if (StandardMaterial.FresnelEnabled) {
  42057. // Fresnel
  42058. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42059. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42060. this._reflectionFresnelParameters) {
  42061. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42062. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42063. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42064. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42065. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42066. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42067. defines._needNormals = true;
  42068. defines.FRESNEL = true;
  42069. }
  42070. }
  42071. else {
  42072. defines.FRESNEL = false;
  42073. }
  42074. }
  42075. // Misc.
  42076. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42077. // Attribs
  42078. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42079. // Values that need to be evaluated on every frame
  42080. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42081. // Get correct effect
  42082. if (defines.isDirty) {
  42083. defines.markAsProcessed();
  42084. scene.resetCachedMaterial();
  42085. // Fallbacks
  42086. var fallbacks = new BABYLON.EffectFallbacks();
  42087. if (defines.REFLECTION) {
  42088. fallbacks.addFallback(0, "REFLECTION");
  42089. }
  42090. if (defines.SPECULAR) {
  42091. fallbacks.addFallback(0, "SPECULAR");
  42092. }
  42093. if (defines.BUMP) {
  42094. fallbacks.addFallback(0, "BUMP");
  42095. }
  42096. if (defines.PARALLAX) {
  42097. fallbacks.addFallback(1, "PARALLAX");
  42098. }
  42099. if (defines.PARALLAXOCCLUSION) {
  42100. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42101. }
  42102. if (defines.SPECULAROVERALPHA) {
  42103. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42104. }
  42105. if (defines.FOG) {
  42106. fallbacks.addFallback(1, "FOG");
  42107. }
  42108. if (defines.POINTSIZE) {
  42109. fallbacks.addFallback(0, "POINTSIZE");
  42110. }
  42111. if (defines.LOGARITHMICDEPTH) {
  42112. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42113. }
  42114. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42115. if (defines.SPECULARTERM) {
  42116. fallbacks.addFallback(0, "SPECULARTERM");
  42117. }
  42118. if (defines.DIFFUSEFRESNEL) {
  42119. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42120. }
  42121. if (defines.OPACITYFRESNEL) {
  42122. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42123. }
  42124. if (defines.REFLECTIONFRESNEL) {
  42125. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42126. }
  42127. if (defines.EMISSIVEFRESNEL) {
  42128. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42129. }
  42130. if (defines.FRESNEL) {
  42131. fallbacks.addFallback(4, "FRESNEL");
  42132. }
  42133. //Attributes
  42134. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42135. if (defines.NORMAL) {
  42136. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42137. }
  42138. if (defines.UV1) {
  42139. attribs.push(BABYLON.VertexBuffer.UVKind);
  42140. }
  42141. if (defines.UV2) {
  42142. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42143. }
  42144. if (defines.VERTEXCOLOR) {
  42145. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42146. }
  42147. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42148. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42149. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42150. var shaderName = "default";
  42151. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42152. "vFogInfos", "vFogColor", "pointSize",
  42153. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42154. "mBones",
  42155. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42156. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42157. "vReflectionPosition", "vReflectionSize",
  42158. "logarithmicDepthConstant", "vTangentSpaceParams"
  42159. ];
  42160. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42161. var uniformBuffers = ["Material", "Scene"];
  42162. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42163. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42164. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42165. uniformsNames: uniforms,
  42166. uniformBuffersNames: uniformBuffers,
  42167. samplers: samplers,
  42168. defines: defines,
  42169. maxSimultaneousLights: this._maxSimultaneousLights
  42170. });
  42171. if (this.customShaderNameResolve) {
  42172. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42173. }
  42174. var join = defines.toString();
  42175. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42176. attributes: attribs,
  42177. uniformsNames: uniforms,
  42178. uniformBuffersNames: uniformBuffers,
  42179. samplers: samplers,
  42180. defines: join,
  42181. fallbacks: fallbacks,
  42182. onCompiled: this.onCompiled,
  42183. onError: this.onError,
  42184. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42185. }, engine), defines);
  42186. this.buildUniformLayout();
  42187. }
  42188. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42189. return false;
  42190. }
  42191. defines._renderId = scene.getRenderId();
  42192. this._wasPreviouslyReady = true;
  42193. return true;
  42194. };
  42195. StandardMaterial.prototype.buildUniformLayout = function () {
  42196. // Order is important !
  42197. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42198. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42199. this._uniformBuffer.addUniform("opacityParts", 4);
  42200. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42201. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42202. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42203. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42204. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42205. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42206. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42207. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42208. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42209. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42210. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42211. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42212. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42213. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42214. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42215. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42216. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42217. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42218. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42219. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42220. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42221. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42222. this._uniformBuffer.addUniform("specularMatrix", 16);
  42223. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42224. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42225. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42226. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42227. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42228. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42229. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42230. this._uniformBuffer.addUniform("pointSize", 1);
  42231. this._uniformBuffer.create();
  42232. };
  42233. StandardMaterial.prototype.unbind = function () {
  42234. if (this._activeEffect) {
  42235. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42236. this._activeEffect.setTexture("reflection2DSampler", null);
  42237. }
  42238. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42239. this._activeEffect.setTexture("refraction2DSampler", null);
  42240. }
  42241. }
  42242. _super.prototype.unbind.call(this);
  42243. };
  42244. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42245. var scene = this.getScene();
  42246. var defines = subMesh._materialDefines;
  42247. if (!defines) {
  42248. return;
  42249. }
  42250. var effect = subMesh.effect;
  42251. if (!effect) {
  42252. return;
  42253. }
  42254. this._activeEffect = effect;
  42255. // Matrices
  42256. this.bindOnlyWorldMatrix(world);
  42257. // Normal Matrix
  42258. if (defines.OBJECTSPACE_NORMALMAP) {
  42259. world.toNormalMatrix(this._normalMatrix);
  42260. this.bindOnlyNormalMatrix(this._normalMatrix);
  42261. }
  42262. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42263. // Bones
  42264. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42265. if (mustRebind) {
  42266. this._uniformBuffer.bindToEffect(effect, "Material");
  42267. this.bindViewProjection(effect);
  42268. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42269. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42270. // Fresnel
  42271. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42272. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42273. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42274. }
  42275. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42276. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42277. }
  42278. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42279. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42280. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42281. }
  42282. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42283. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42284. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42285. }
  42286. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42287. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42288. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42289. }
  42290. }
  42291. // Textures
  42292. if (scene.texturesEnabled) {
  42293. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42294. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42295. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42296. }
  42297. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42298. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42299. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42300. }
  42301. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42302. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42303. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42304. }
  42305. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42306. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42307. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42308. if (this._reflectionTexture.boundingBoxSize) {
  42309. var cubeTexture = this._reflectionTexture;
  42310. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42311. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42312. }
  42313. }
  42314. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42315. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42316. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42317. }
  42318. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42319. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42320. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42321. }
  42322. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42323. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42324. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42325. }
  42326. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42327. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42328. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42329. if (scene._mirroredCameraPosition) {
  42330. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42331. }
  42332. else {
  42333. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42334. }
  42335. }
  42336. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42337. var depth = 1.0;
  42338. if (!this._refractionTexture.isCube) {
  42339. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42340. if (this._refractionTexture.depth) {
  42341. depth = this._refractionTexture.depth;
  42342. }
  42343. }
  42344. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42345. }
  42346. }
  42347. // Point size
  42348. if (this.pointsCloud) {
  42349. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42350. }
  42351. if (defines.SPECULARTERM) {
  42352. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42353. }
  42354. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42355. // Diffuse
  42356. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42357. }
  42358. // Textures
  42359. if (scene.texturesEnabled) {
  42360. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42361. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42362. }
  42363. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42364. effect.setTexture("ambientSampler", this._ambientTexture);
  42365. }
  42366. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42367. effect.setTexture("opacitySampler", this._opacityTexture);
  42368. }
  42369. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42370. if (this._reflectionTexture.isCube) {
  42371. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42372. }
  42373. else {
  42374. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42375. }
  42376. }
  42377. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42378. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42379. }
  42380. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42381. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42382. }
  42383. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42384. effect.setTexture("specularSampler", this._specularTexture);
  42385. }
  42386. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42387. effect.setTexture("bumpSampler", this._bumpTexture);
  42388. }
  42389. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42390. var depth = 1.0;
  42391. if (this._refractionTexture.isCube) {
  42392. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42393. }
  42394. else {
  42395. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42396. }
  42397. }
  42398. }
  42399. // Clip plane
  42400. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42401. // Colors
  42402. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42403. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42404. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42405. }
  42406. if (mustRebind || !this.isFrozen) {
  42407. // Lights
  42408. if (scene.lightsEnabled && !this._disableLighting) {
  42409. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42410. }
  42411. // View
  42412. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42413. this.bindView(effect);
  42414. }
  42415. // Fog
  42416. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42417. // Morph targets
  42418. if (defines.NUM_MORPH_INFLUENCERS) {
  42419. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42420. }
  42421. // Log. depth
  42422. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42423. // image processing
  42424. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  42425. this._imageProcessingConfiguration.bind(this._activeEffect);
  42426. }
  42427. }
  42428. this._uniformBuffer.update();
  42429. this._afterBind(mesh, this._activeEffect);
  42430. };
  42431. StandardMaterial.prototype.getAnimatables = function () {
  42432. var results = [];
  42433. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42434. results.push(this._diffuseTexture);
  42435. }
  42436. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42437. results.push(this._ambientTexture);
  42438. }
  42439. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42440. results.push(this._opacityTexture);
  42441. }
  42442. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42443. results.push(this._reflectionTexture);
  42444. }
  42445. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42446. results.push(this._emissiveTexture);
  42447. }
  42448. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42449. results.push(this._specularTexture);
  42450. }
  42451. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42452. results.push(this._bumpTexture);
  42453. }
  42454. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42455. results.push(this._lightmapTexture);
  42456. }
  42457. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42458. results.push(this._refractionTexture);
  42459. }
  42460. return results;
  42461. };
  42462. StandardMaterial.prototype.getActiveTextures = function () {
  42463. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42464. if (this._diffuseTexture) {
  42465. activeTextures.push(this._diffuseTexture);
  42466. }
  42467. if (this._ambientTexture) {
  42468. activeTextures.push(this._ambientTexture);
  42469. }
  42470. if (this._opacityTexture) {
  42471. activeTextures.push(this._opacityTexture);
  42472. }
  42473. if (this._reflectionTexture) {
  42474. activeTextures.push(this._reflectionTexture);
  42475. }
  42476. if (this._emissiveTexture) {
  42477. activeTextures.push(this._emissiveTexture);
  42478. }
  42479. if (this._specularTexture) {
  42480. activeTextures.push(this._specularTexture);
  42481. }
  42482. if (this._bumpTexture) {
  42483. activeTextures.push(this._bumpTexture);
  42484. }
  42485. if (this._lightmapTexture) {
  42486. activeTextures.push(this._lightmapTexture);
  42487. }
  42488. if (this._refractionTexture) {
  42489. activeTextures.push(this._refractionTexture);
  42490. }
  42491. return activeTextures;
  42492. };
  42493. StandardMaterial.prototype.hasTexture = function (texture) {
  42494. if (_super.prototype.hasTexture.call(this, texture)) {
  42495. return true;
  42496. }
  42497. if (this._diffuseTexture === texture) {
  42498. return true;
  42499. }
  42500. if (this._ambientTexture === texture) {
  42501. return true;
  42502. }
  42503. if (this._opacityTexture === texture) {
  42504. return true;
  42505. }
  42506. if (this._reflectionTexture === texture) {
  42507. return true;
  42508. }
  42509. if (this._emissiveTexture === texture) {
  42510. return true;
  42511. }
  42512. if (this._specularTexture === texture) {
  42513. return true;
  42514. }
  42515. if (this._bumpTexture === texture) {
  42516. return true;
  42517. }
  42518. if (this._lightmapTexture === texture) {
  42519. return true;
  42520. }
  42521. if (this._refractionTexture === texture) {
  42522. return true;
  42523. }
  42524. return false;
  42525. };
  42526. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42527. if (forceDisposeTextures) {
  42528. if (this._diffuseTexture) {
  42529. this._diffuseTexture.dispose();
  42530. }
  42531. if (this._ambientTexture) {
  42532. this._ambientTexture.dispose();
  42533. }
  42534. if (this._opacityTexture) {
  42535. this._opacityTexture.dispose();
  42536. }
  42537. if (this._reflectionTexture) {
  42538. this._reflectionTexture.dispose();
  42539. }
  42540. if (this._emissiveTexture) {
  42541. this._emissiveTexture.dispose();
  42542. }
  42543. if (this._specularTexture) {
  42544. this._specularTexture.dispose();
  42545. }
  42546. if (this._bumpTexture) {
  42547. this._bumpTexture.dispose();
  42548. }
  42549. if (this._lightmapTexture) {
  42550. this._lightmapTexture.dispose();
  42551. }
  42552. if (this._refractionTexture) {
  42553. this._refractionTexture.dispose();
  42554. }
  42555. }
  42556. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42557. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42558. }
  42559. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42560. };
  42561. StandardMaterial.prototype.clone = function (name) {
  42562. var _this = this;
  42563. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42564. result.name = name;
  42565. result.id = name;
  42566. return result;
  42567. };
  42568. StandardMaterial.prototype.serialize = function () {
  42569. return BABYLON.SerializationHelper.Serialize(this);
  42570. };
  42571. // Statics
  42572. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42573. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42574. };
  42575. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42576. get: function () {
  42577. return StandardMaterial._DiffuseTextureEnabled;
  42578. },
  42579. set: function (value) {
  42580. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42581. return;
  42582. }
  42583. StandardMaterial._DiffuseTextureEnabled = value;
  42584. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42585. },
  42586. enumerable: true,
  42587. configurable: true
  42588. });
  42589. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42590. get: function () {
  42591. return StandardMaterial._AmbientTextureEnabled;
  42592. },
  42593. set: function (value) {
  42594. if (StandardMaterial._AmbientTextureEnabled === value) {
  42595. return;
  42596. }
  42597. StandardMaterial._AmbientTextureEnabled = value;
  42598. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42599. },
  42600. enumerable: true,
  42601. configurable: true
  42602. });
  42603. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42604. get: function () {
  42605. return StandardMaterial._OpacityTextureEnabled;
  42606. },
  42607. set: function (value) {
  42608. if (StandardMaterial._OpacityTextureEnabled === value) {
  42609. return;
  42610. }
  42611. StandardMaterial._OpacityTextureEnabled = value;
  42612. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42613. },
  42614. enumerable: true,
  42615. configurable: true
  42616. });
  42617. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42618. get: function () {
  42619. return StandardMaterial._ReflectionTextureEnabled;
  42620. },
  42621. set: function (value) {
  42622. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42623. return;
  42624. }
  42625. StandardMaterial._ReflectionTextureEnabled = value;
  42626. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42627. },
  42628. enumerable: true,
  42629. configurable: true
  42630. });
  42631. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42632. get: function () {
  42633. return StandardMaterial._EmissiveTextureEnabled;
  42634. },
  42635. set: function (value) {
  42636. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42637. return;
  42638. }
  42639. StandardMaterial._EmissiveTextureEnabled = value;
  42640. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42641. },
  42642. enumerable: true,
  42643. configurable: true
  42644. });
  42645. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42646. get: function () {
  42647. return StandardMaterial._SpecularTextureEnabled;
  42648. },
  42649. set: function (value) {
  42650. if (StandardMaterial._SpecularTextureEnabled === value) {
  42651. return;
  42652. }
  42653. StandardMaterial._SpecularTextureEnabled = value;
  42654. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42655. },
  42656. enumerable: true,
  42657. configurable: true
  42658. });
  42659. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42660. get: function () {
  42661. return StandardMaterial._BumpTextureEnabled;
  42662. },
  42663. set: function (value) {
  42664. if (StandardMaterial._BumpTextureEnabled === value) {
  42665. return;
  42666. }
  42667. StandardMaterial._BumpTextureEnabled = value;
  42668. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42669. },
  42670. enumerable: true,
  42671. configurable: true
  42672. });
  42673. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42674. get: function () {
  42675. return StandardMaterial._LightmapTextureEnabled;
  42676. },
  42677. set: function (value) {
  42678. if (StandardMaterial._LightmapTextureEnabled === value) {
  42679. return;
  42680. }
  42681. StandardMaterial._LightmapTextureEnabled = value;
  42682. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42683. },
  42684. enumerable: true,
  42685. configurable: true
  42686. });
  42687. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42688. get: function () {
  42689. return StandardMaterial._RefractionTextureEnabled;
  42690. },
  42691. set: function (value) {
  42692. if (StandardMaterial._RefractionTextureEnabled === value) {
  42693. return;
  42694. }
  42695. StandardMaterial._RefractionTextureEnabled = value;
  42696. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42697. },
  42698. enumerable: true,
  42699. configurable: true
  42700. });
  42701. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42702. get: function () {
  42703. return StandardMaterial._ColorGradingTextureEnabled;
  42704. },
  42705. set: function (value) {
  42706. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42707. return;
  42708. }
  42709. StandardMaterial._ColorGradingTextureEnabled = value;
  42710. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42711. },
  42712. enumerable: true,
  42713. configurable: true
  42714. });
  42715. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42716. get: function () {
  42717. return StandardMaterial._FresnelEnabled;
  42718. },
  42719. set: function (value) {
  42720. if (StandardMaterial._FresnelEnabled === value) {
  42721. return;
  42722. }
  42723. StandardMaterial._FresnelEnabled = value;
  42724. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42725. },
  42726. enumerable: true,
  42727. configurable: true
  42728. });
  42729. // Flags used to enable or disable a type of texture for all Standard Materials
  42730. StandardMaterial._DiffuseTextureEnabled = true;
  42731. StandardMaterial._AmbientTextureEnabled = true;
  42732. StandardMaterial._OpacityTextureEnabled = true;
  42733. StandardMaterial._ReflectionTextureEnabled = true;
  42734. StandardMaterial._EmissiveTextureEnabled = true;
  42735. StandardMaterial._SpecularTextureEnabled = true;
  42736. StandardMaterial._BumpTextureEnabled = true;
  42737. StandardMaterial._LightmapTextureEnabled = true;
  42738. StandardMaterial._RefractionTextureEnabled = true;
  42739. StandardMaterial._ColorGradingTextureEnabled = true;
  42740. StandardMaterial._FresnelEnabled = true;
  42741. __decorate([
  42742. BABYLON.serializeAsTexture("diffuseTexture")
  42743. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42744. __decorate([
  42745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42746. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42747. __decorate([
  42748. BABYLON.serializeAsTexture("ambientTexture")
  42749. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42750. __decorate([
  42751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42752. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42753. __decorate([
  42754. BABYLON.serializeAsTexture("opacityTexture")
  42755. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42756. __decorate([
  42757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42758. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42759. __decorate([
  42760. BABYLON.serializeAsTexture("reflectionTexture")
  42761. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42762. __decorate([
  42763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42764. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42765. __decorate([
  42766. BABYLON.serializeAsTexture("emissiveTexture")
  42767. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42768. __decorate([
  42769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42770. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42771. __decorate([
  42772. BABYLON.serializeAsTexture("specularTexture")
  42773. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42774. __decorate([
  42775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42776. ], StandardMaterial.prototype, "specularTexture", void 0);
  42777. __decorate([
  42778. BABYLON.serializeAsTexture("bumpTexture")
  42779. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42780. __decorate([
  42781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42782. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42783. __decorate([
  42784. BABYLON.serializeAsTexture("lightmapTexture")
  42785. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42786. __decorate([
  42787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42788. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42789. __decorate([
  42790. BABYLON.serializeAsTexture("refractionTexture")
  42791. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42792. __decorate([
  42793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42794. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42795. __decorate([
  42796. BABYLON.serializeAsColor3("ambient")
  42797. ], StandardMaterial.prototype, "ambientColor", void 0);
  42798. __decorate([
  42799. BABYLON.serializeAsColor3("diffuse")
  42800. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42801. __decorate([
  42802. BABYLON.serializeAsColor3("specular")
  42803. ], StandardMaterial.prototype, "specularColor", void 0);
  42804. __decorate([
  42805. BABYLON.serializeAsColor3("emissive")
  42806. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42807. __decorate([
  42808. BABYLON.serialize()
  42809. ], StandardMaterial.prototype, "specularPower", void 0);
  42810. __decorate([
  42811. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42812. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42813. __decorate([
  42814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42815. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42816. __decorate([
  42817. BABYLON.serialize("useEmissiveAsIllumination")
  42818. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42819. __decorate([
  42820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42821. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42822. __decorate([
  42823. BABYLON.serialize("linkEmissiveWithDiffuse")
  42824. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42825. __decorate([
  42826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42827. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42828. __decorate([
  42829. BABYLON.serialize("useSpecularOverAlpha")
  42830. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42831. __decorate([
  42832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42833. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42834. __decorate([
  42835. BABYLON.serialize("useReflectionOverAlpha")
  42836. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42837. __decorate([
  42838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42839. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42840. __decorate([
  42841. BABYLON.serialize("disableLighting")
  42842. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42843. __decorate([
  42844. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42845. ], StandardMaterial.prototype, "disableLighting", void 0);
  42846. __decorate([
  42847. BABYLON.serialize("useObjectSpaceNormalMap")
  42848. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42849. __decorate([
  42850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42851. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42852. __decorate([
  42853. BABYLON.serialize("useParallax")
  42854. ], StandardMaterial.prototype, "_useParallax", void 0);
  42855. __decorate([
  42856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42857. ], StandardMaterial.prototype, "useParallax", void 0);
  42858. __decorate([
  42859. BABYLON.serialize("useParallaxOcclusion")
  42860. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42861. __decorate([
  42862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42863. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42864. __decorate([
  42865. BABYLON.serialize()
  42866. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42867. __decorate([
  42868. BABYLON.serialize("roughness")
  42869. ], StandardMaterial.prototype, "_roughness", void 0);
  42870. __decorate([
  42871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42872. ], StandardMaterial.prototype, "roughness", void 0);
  42873. __decorate([
  42874. BABYLON.serialize()
  42875. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42876. __decorate([
  42877. BABYLON.serialize()
  42878. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42879. __decorate([
  42880. BABYLON.serialize("useLightmapAsShadowmap")
  42881. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42882. __decorate([
  42883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42884. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42885. __decorate([
  42886. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42887. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42888. __decorate([
  42889. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42890. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42891. __decorate([
  42892. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42893. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42894. __decorate([
  42895. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42896. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42897. __decorate([
  42898. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42899. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42900. __decorate([
  42901. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42902. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42903. __decorate([
  42904. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42905. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42906. __decorate([
  42907. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42908. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42909. __decorate([
  42910. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42911. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42912. __decorate([
  42913. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42914. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42915. __decorate([
  42916. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42917. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42918. __decorate([
  42919. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42920. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42921. __decorate([
  42922. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42923. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42924. __decorate([
  42925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42926. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42927. __decorate([
  42928. BABYLON.serialize("maxSimultaneousLights")
  42929. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42930. __decorate([
  42931. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42932. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42933. __decorate([
  42934. BABYLON.serialize("invertNormalMapX")
  42935. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42936. __decorate([
  42937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42938. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42939. __decorate([
  42940. BABYLON.serialize("invertNormalMapY")
  42941. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42942. __decorate([
  42943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42944. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42945. __decorate([
  42946. BABYLON.serialize("twoSidedLighting")
  42947. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42948. __decorate([
  42949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42950. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42951. __decorate([
  42952. BABYLON.serialize()
  42953. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42954. return StandardMaterial;
  42955. }(BABYLON.PushMaterial));
  42956. BABYLON.StandardMaterial = StandardMaterial;
  42957. })(BABYLON || (BABYLON = {}));
  42958. //# sourceMappingURL=babylon.standardMaterial.js.map
  42959. "use strict";
  42960. var BABYLON;
  42961. (function (BABYLON) {
  42962. /**
  42963. * Manages the defines for the PBR Material.
  42964. * @ignoreChildren
  42965. */
  42966. var PBRMaterialDefines = /** @class */ (function (_super) {
  42967. __extends(PBRMaterialDefines, _super);
  42968. /**
  42969. * Initializes the PBR Material defines.
  42970. */
  42971. function PBRMaterialDefines() {
  42972. var _this = _super.call(this) || this;
  42973. _this.PBR = true;
  42974. _this.MAINUV1 = false;
  42975. _this.MAINUV2 = false;
  42976. _this.UV1 = false;
  42977. _this.UV2 = false;
  42978. _this.ALBEDO = false;
  42979. _this.ALBEDODIRECTUV = 0;
  42980. _this.VERTEXCOLOR = false;
  42981. _this.AMBIENT = false;
  42982. _this.AMBIENTDIRECTUV = 0;
  42983. _this.AMBIENTINGRAYSCALE = false;
  42984. _this.OPACITY = false;
  42985. _this.VERTEXALPHA = false;
  42986. _this.OPACITYDIRECTUV = 0;
  42987. _this.OPACITYRGB = false;
  42988. _this.ALPHATEST = false;
  42989. _this.DEPTHPREPASS = false;
  42990. _this.ALPHABLEND = false;
  42991. _this.ALPHAFROMALBEDO = false;
  42992. _this.ALPHATESTVALUE = "0.5";
  42993. _this.SPECULAROVERALPHA = false;
  42994. _this.RADIANCEOVERALPHA = false;
  42995. _this.ALPHAFRESNEL = false;
  42996. _this.LINEARALPHAFRESNEL = false;
  42997. _this.PREMULTIPLYALPHA = false;
  42998. _this.EMISSIVE = false;
  42999. _this.EMISSIVEDIRECTUV = 0;
  43000. _this.REFLECTIVITY = false;
  43001. _this.REFLECTIVITYDIRECTUV = 0;
  43002. _this.SPECULARTERM = false;
  43003. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43004. _this.MICROSURFACEAUTOMATIC = false;
  43005. _this.LODBASEDMICROSFURACE = false;
  43006. _this.MICROSURFACEMAP = false;
  43007. _this.MICROSURFACEMAPDIRECTUV = 0;
  43008. _this.METALLICWORKFLOW = false;
  43009. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43010. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43011. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43012. _this.AOSTOREINMETALMAPRED = false;
  43013. _this.ENVIRONMENTBRDF = false;
  43014. _this.NORMAL = false;
  43015. _this.TANGENT = false;
  43016. _this.BUMP = false;
  43017. _this.BUMPDIRECTUV = 0;
  43018. _this.OBJECTSPACE_NORMALMAP = false;
  43019. _this.PARALLAX = false;
  43020. _this.PARALLAXOCCLUSION = false;
  43021. _this.NORMALXYSCALE = true;
  43022. _this.LIGHTMAP = false;
  43023. _this.LIGHTMAPDIRECTUV = 0;
  43024. _this.USELIGHTMAPASSHADOWMAP = false;
  43025. _this.GAMMALIGHTMAP = false;
  43026. _this.REFLECTION = false;
  43027. _this.REFLECTIONMAP_3D = false;
  43028. _this.REFLECTIONMAP_SPHERICAL = false;
  43029. _this.REFLECTIONMAP_PLANAR = false;
  43030. _this.REFLECTIONMAP_CUBIC = false;
  43031. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43032. _this.REFLECTIONMAP_PROJECTION = false;
  43033. _this.REFLECTIONMAP_SKYBOX = false;
  43034. _this.REFLECTIONMAP_EXPLICIT = false;
  43035. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43036. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43037. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43038. _this.INVERTCUBICMAP = false;
  43039. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43040. _this.USESPHERICALINVERTEX = false;
  43041. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43042. _this.LODINREFLECTIONALPHA = false;
  43043. _this.GAMMAREFLECTION = false;
  43044. _this.RADIANCEOCCLUSION = false;
  43045. _this.HORIZONOCCLUSION = false;
  43046. _this.REFRACTION = false;
  43047. _this.REFRACTIONMAP_3D = false;
  43048. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43049. _this.LODINREFRACTIONALPHA = false;
  43050. _this.GAMMAREFRACTION = false;
  43051. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43052. _this.INSTANCES = false;
  43053. _this.NUM_BONE_INFLUENCERS = 0;
  43054. _this.BonesPerMesh = 0;
  43055. _this.NONUNIFORMSCALING = false;
  43056. _this.MORPHTARGETS = false;
  43057. _this.MORPHTARGETS_NORMAL = false;
  43058. _this.MORPHTARGETS_TANGENT = false;
  43059. _this.NUM_MORPH_INFLUENCERS = 0;
  43060. _this.IMAGEPROCESSING = false;
  43061. _this.VIGNETTE = false;
  43062. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43063. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43064. _this.TONEMAPPING = false;
  43065. _this.CONTRAST = false;
  43066. _this.COLORCURVES = false;
  43067. _this.COLORGRADING = false;
  43068. _this.COLORGRADING3D = false;
  43069. _this.SAMPLER3DGREENDEPTH = false;
  43070. _this.SAMPLER3DBGRMAP = false;
  43071. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43072. _this.EXPOSURE = false;
  43073. _this.USEPHYSICALLIGHTFALLOFF = false;
  43074. _this.TWOSIDEDLIGHTING = false;
  43075. _this.SHADOWFLOAT = false;
  43076. _this.CLIPPLANE = false;
  43077. _this.POINTSIZE = false;
  43078. _this.FOG = false;
  43079. _this.LOGARITHMICDEPTH = false;
  43080. _this.FORCENORMALFORWARD = false;
  43081. _this.GEOMETRYAA = false;
  43082. _this.UNLIT = false;
  43083. _this.rebuild();
  43084. return _this;
  43085. }
  43086. /**
  43087. * Resets the PBR Material defines.
  43088. */
  43089. PBRMaterialDefines.prototype.reset = function () {
  43090. _super.prototype.reset.call(this);
  43091. this.ALPHATESTVALUE = "0.5";
  43092. this.PBR = true;
  43093. };
  43094. return PBRMaterialDefines;
  43095. }(BABYLON.MaterialDefines));
  43096. /**
  43097. * The Physically based material base class of BJS.
  43098. *
  43099. * This offers the main features of a standard PBR material.
  43100. * For more information, please refer to the documentation :
  43101. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43102. */
  43103. var PBRBaseMaterial = /** @class */ (function (_super) {
  43104. __extends(PBRBaseMaterial, _super);
  43105. /**
  43106. * Instantiates a new PBRMaterial instance.
  43107. *
  43108. * @param name The material name
  43109. * @param scene The scene the material will be use in.
  43110. */
  43111. function PBRBaseMaterial(name, scene) {
  43112. var _this = _super.call(this, name, scene) || this;
  43113. /**
  43114. * Intensity of the direct lights e.g. the four lights available in your scene.
  43115. * This impacts both the direct diffuse and specular highlights.
  43116. */
  43117. _this._directIntensity = 1.0;
  43118. /**
  43119. * Intensity of the emissive part of the material.
  43120. * This helps controlling the emissive effect without modifying the emissive color.
  43121. */
  43122. _this._emissiveIntensity = 1.0;
  43123. /**
  43124. * Intensity of the environment e.g. how much the environment will light the object
  43125. * either through harmonics for rough material or through the refelction for shiny ones.
  43126. */
  43127. _this._environmentIntensity = 1.0;
  43128. /**
  43129. * This is a special control allowing the reduction of the specular highlights coming from the
  43130. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43131. */
  43132. _this._specularIntensity = 1.0;
  43133. /**
  43134. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43135. */
  43136. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43137. /**
  43138. * Debug Control allowing disabling the bump map on this material.
  43139. */
  43140. _this._disableBumpMap = false;
  43141. /**
  43142. * AKA Occlusion Texture Intensity in other nomenclature.
  43143. */
  43144. _this._ambientTextureStrength = 1.0;
  43145. /**
  43146. * The color of a material in ambient lighting.
  43147. */
  43148. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43149. /**
  43150. * AKA Diffuse Color in other nomenclature.
  43151. */
  43152. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43153. /**
  43154. * AKA Specular Color in other nomenclature.
  43155. */
  43156. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43157. /**
  43158. * The color applied when light is reflected from a material.
  43159. */
  43160. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43161. /**
  43162. * The color applied when light is emitted from a material.
  43163. */
  43164. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43165. /**
  43166. * AKA Glossiness in other nomenclature.
  43167. */
  43168. _this._microSurface = 0.9;
  43169. /**
  43170. * source material index of refraction (IOR)' / 'destination material IOR.
  43171. */
  43172. _this._indexOfRefraction = 0.66;
  43173. /**
  43174. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43175. */
  43176. _this._invertRefractionY = false;
  43177. /**
  43178. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43179. * Materials half opaque for instance using refraction could benefit from this control.
  43180. */
  43181. _this._linkRefractionWithTransparency = false;
  43182. /**
  43183. * Specifies that the material will use the light map as a show map.
  43184. */
  43185. _this._useLightmapAsShadowmap = false;
  43186. /**
  43187. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43188. * makes the reflect vector face the model (under horizon).
  43189. */
  43190. _this._useHorizonOcclusion = true;
  43191. /**
  43192. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43193. * too much the area relying on ambient texture to define their ambient occlusion.
  43194. */
  43195. _this._useRadianceOcclusion = true;
  43196. /**
  43197. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43198. */
  43199. _this._useAlphaFromAlbedoTexture = false;
  43200. /**
  43201. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43202. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43203. */
  43204. _this._useSpecularOverAlpha = true;
  43205. /**
  43206. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43207. */
  43208. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43209. /**
  43210. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43211. */
  43212. _this._useRoughnessFromMetallicTextureAlpha = true;
  43213. /**
  43214. * Specifies if the metallic texture contains the roughness information in its green channel.
  43215. */
  43216. _this._useRoughnessFromMetallicTextureGreen = false;
  43217. /**
  43218. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43219. */
  43220. _this._useMetallnessFromMetallicTextureBlue = false;
  43221. /**
  43222. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43223. */
  43224. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43225. /**
  43226. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43227. */
  43228. _this._useAmbientInGrayScale = false;
  43229. /**
  43230. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43231. * The material will try to infer what glossiness each pixel should be.
  43232. */
  43233. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43234. /**
  43235. * BJS is using an harcoded light falloff based on a manually sets up range.
  43236. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43237. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43238. */
  43239. _this._usePhysicalLightFalloff = true;
  43240. /**
  43241. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43242. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43243. */
  43244. _this._useRadianceOverAlpha = true;
  43245. /**
  43246. * Allows using an object space normal map (instead of tangent space).
  43247. */
  43248. _this._useObjectSpaceNormalMap = false;
  43249. /**
  43250. * Allows using the bump map in parallax mode.
  43251. */
  43252. _this._useParallax = false;
  43253. /**
  43254. * Allows using the bump map in parallax occlusion mode.
  43255. */
  43256. _this._useParallaxOcclusion = false;
  43257. /**
  43258. * Controls the scale bias of the parallax mode.
  43259. */
  43260. _this._parallaxScaleBias = 0.05;
  43261. /**
  43262. * If sets to true, disables all the lights affecting the material.
  43263. */
  43264. _this._disableLighting = false;
  43265. /**
  43266. * Number of Simultaneous lights allowed on the material.
  43267. */
  43268. _this._maxSimultaneousLights = 4;
  43269. /**
  43270. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43271. */
  43272. _this._invertNormalMapX = false;
  43273. /**
  43274. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43275. */
  43276. _this._invertNormalMapY = false;
  43277. /**
  43278. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43279. */
  43280. _this._twoSidedLighting = false;
  43281. /**
  43282. * Defines the alpha limits in alpha test mode.
  43283. */
  43284. _this._alphaCutOff = 0.4;
  43285. /**
  43286. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43287. */
  43288. _this._forceAlphaTest = false;
  43289. /**
  43290. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43291. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43292. */
  43293. _this._useAlphaFresnel = false;
  43294. /**
  43295. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43296. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43297. */
  43298. _this._useLinearAlphaFresnel = false;
  43299. /**
  43300. * The transparency mode of the material.
  43301. */
  43302. _this._transparencyMode = null;
  43303. /**
  43304. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43305. * from cos thetav and roughness:
  43306. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43307. */
  43308. _this._environmentBRDFTexture = null;
  43309. /**
  43310. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43311. */
  43312. _this._forceIrradianceInFragment = false;
  43313. /**
  43314. * Force normal to face away from face.
  43315. */
  43316. _this._forceNormalForward = false;
  43317. /**
  43318. * Enables specular anti aliasing in the PBR shader.
  43319. * It will both interacts on the Geometry for analytical and IBL lighting.
  43320. * It also prefilter the roughness map based on the bump values.
  43321. */
  43322. _this._enableSpecularAntiAliasing = false;
  43323. /**
  43324. * Stores the available render targets.
  43325. */
  43326. _this._renderTargets = new BABYLON.SmartArray(16);
  43327. /**
  43328. * Sets the global ambient color for the material used in lighting calculations.
  43329. */
  43330. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43331. /**
  43332. * If set to true, no lighting calculations will be applied.
  43333. */
  43334. _this._unlit = false;
  43335. // Setup the default processing configuration to the scene.
  43336. _this._attachImageProcessingConfiguration(null);
  43337. _this.getRenderTargetTextures = function () {
  43338. _this._renderTargets.reset();
  43339. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43340. _this._renderTargets.push(_this._reflectionTexture);
  43341. }
  43342. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43343. _this._renderTargets.push(_this._refractionTexture);
  43344. }
  43345. return _this._renderTargets;
  43346. };
  43347. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43348. return _this;
  43349. }
  43350. /**
  43351. * Attaches a new image processing configuration to the PBR Material.
  43352. * @param configuration
  43353. */
  43354. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43355. var _this = this;
  43356. if (configuration === this._imageProcessingConfiguration) {
  43357. return;
  43358. }
  43359. // Detaches observer.
  43360. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43361. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43362. }
  43363. // Pick the scene configuration if needed.
  43364. if (!configuration) {
  43365. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43366. }
  43367. else {
  43368. this._imageProcessingConfiguration = configuration;
  43369. }
  43370. // Attaches observer.
  43371. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43372. _this._markAllSubMeshesAsImageProcessingDirty();
  43373. });
  43374. };
  43375. /**
  43376. * Gets the name of the material class.
  43377. */
  43378. PBRBaseMaterial.prototype.getClassName = function () {
  43379. return "PBRBaseMaterial";
  43380. };
  43381. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43382. /**
  43383. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43384. */
  43385. get: function () {
  43386. return this._useLogarithmicDepth;
  43387. },
  43388. /**
  43389. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43390. */
  43391. set: function (value) {
  43392. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43393. },
  43394. enumerable: true,
  43395. configurable: true
  43396. });
  43397. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43398. /**
  43399. * Gets the current transparency mode.
  43400. */
  43401. get: function () {
  43402. return this._transparencyMode;
  43403. },
  43404. /**
  43405. * Sets the transparency mode of the material.
  43406. */
  43407. set: function (value) {
  43408. if (this._transparencyMode === value) {
  43409. return;
  43410. }
  43411. this._transparencyMode = value;
  43412. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43413. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43414. },
  43415. enumerable: true,
  43416. configurable: true
  43417. });
  43418. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43419. /**
  43420. * Returns true if alpha blending should be disabled.
  43421. */
  43422. get: function () {
  43423. return (this._linkRefractionWithTransparency ||
  43424. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43425. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43426. },
  43427. enumerable: true,
  43428. configurable: true
  43429. });
  43430. /**
  43431. * Specifies whether or not this material should be rendered in alpha blend mode.
  43432. */
  43433. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43434. if (this._disableAlphaBlending) {
  43435. return false;
  43436. }
  43437. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43438. };
  43439. /**
  43440. * Specifies if the mesh will require alpha blending.
  43441. * @param mesh - BJS mesh.
  43442. */
  43443. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43444. if (this._disableAlphaBlending) {
  43445. return false;
  43446. }
  43447. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43448. };
  43449. /**
  43450. * Specifies whether or not this material should be rendered in alpha test mode.
  43451. */
  43452. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43453. if (this._forceAlphaTest) {
  43454. return true;
  43455. }
  43456. if (this._linkRefractionWithTransparency) {
  43457. return false;
  43458. }
  43459. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43460. };
  43461. /**
  43462. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43463. */
  43464. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43465. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43466. };
  43467. /**
  43468. * Gets the texture used for the alpha test.
  43469. */
  43470. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43471. return this._albedoTexture;
  43472. };
  43473. /**
  43474. * Specifies that the submesh is ready to be used.
  43475. * @param mesh - BJS mesh.
  43476. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43477. * @param useInstances - Specifies that instances should be used.
  43478. * @returns - boolean indicating that the submesh is ready or not.
  43479. */
  43480. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43481. if (subMesh.effect && this.isFrozen) {
  43482. if (this._wasPreviouslyReady) {
  43483. return true;
  43484. }
  43485. }
  43486. if (!subMesh._materialDefines) {
  43487. subMesh._materialDefines = new PBRMaterialDefines();
  43488. }
  43489. var defines = subMesh._materialDefines;
  43490. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43491. if (defines._renderId === this.getScene().getRenderId()) {
  43492. return true;
  43493. }
  43494. }
  43495. var scene = this.getScene();
  43496. var engine = scene.getEngine();
  43497. if (defines._areTexturesDirty) {
  43498. if (scene.texturesEnabled) {
  43499. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43500. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43501. return false;
  43502. }
  43503. }
  43504. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43505. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43506. return false;
  43507. }
  43508. }
  43509. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43510. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43511. return false;
  43512. }
  43513. }
  43514. var reflectionTexture = this._getReflectionTexture();
  43515. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43516. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43517. return false;
  43518. }
  43519. }
  43520. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43521. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43522. return false;
  43523. }
  43524. }
  43525. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43526. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43527. return false;
  43528. }
  43529. }
  43530. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43531. if (this._metallicTexture) {
  43532. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43533. return false;
  43534. }
  43535. }
  43536. else if (this._reflectivityTexture) {
  43537. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43538. return false;
  43539. }
  43540. }
  43541. if (this._microSurfaceTexture) {
  43542. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43543. return false;
  43544. }
  43545. }
  43546. }
  43547. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43548. // Bump texture cannot be not blocking.
  43549. if (!this._bumpTexture.isReady()) {
  43550. return false;
  43551. }
  43552. }
  43553. var refractionTexture = this._getRefractionTexture();
  43554. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43555. if (!refractionTexture.isReadyOrNotBlocking()) {
  43556. return false;
  43557. }
  43558. }
  43559. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43560. // This is blocking.
  43561. if (!this._environmentBRDFTexture.isReady()) {
  43562. return false;
  43563. }
  43564. }
  43565. }
  43566. }
  43567. if (defines._areImageProcessingDirty) {
  43568. if (!this._imageProcessingConfiguration.isReady()) {
  43569. return false;
  43570. }
  43571. }
  43572. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43573. mesh.createNormals(true);
  43574. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43575. }
  43576. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43577. if (effect) {
  43578. scene.resetCachedMaterial();
  43579. subMesh.setEffect(effect, defines);
  43580. this.buildUniformLayout();
  43581. }
  43582. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43583. return false;
  43584. }
  43585. defines._renderId = scene.getRenderId();
  43586. this._wasPreviouslyReady = true;
  43587. return true;
  43588. };
  43589. /**
  43590. * Specifies if the material uses metallic roughness workflow.
  43591. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43592. */
  43593. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43594. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43595. return true;
  43596. }
  43597. return false;
  43598. };
  43599. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43600. if (onCompiled === void 0) { onCompiled = null; }
  43601. if (onError === void 0) { onError = null; }
  43602. if (useInstances === void 0) { useInstances = null; }
  43603. if (useClipPlane === void 0) { useClipPlane = null; }
  43604. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43605. if (!defines.isDirty) {
  43606. return null;
  43607. }
  43608. defines.markAsProcessed();
  43609. var scene = this.getScene();
  43610. var engine = scene.getEngine();
  43611. // Fallbacks
  43612. var fallbacks = new BABYLON.EffectFallbacks();
  43613. var fallbackRank = 0;
  43614. if (defines.USESPHERICALINVERTEX) {
  43615. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43616. }
  43617. if (defines.FOG) {
  43618. fallbacks.addFallback(fallbackRank, "FOG");
  43619. }
  43620. if (defines.POINTSIZE) {
  43621. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43622. }
  43623. if (defines.LOGARITHMICDEPTH) {
  43624. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43625. }
  43626. if (defines.PARALLAX) {
  43627. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43628. }
  43629. if (defines.PARALLAXOCCLUSION) {
  43630. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43631. }
  43632. if (defines.ENVIRONMENTBRDF) {
  43633. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43634. }
  43635. if (defines.TANGENT) {
  43636. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43637. }
  43638. if (defines.BUMP) {
  43639. fallbacks.addFallback(fallbackRank++, "BUMP");
  43640. }
  43641. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43642. if (defines.SPECULARTERM) {
  43643. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43644. }
  43645. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43646. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43647. }
  43648. if (defines.LIGHTMAP) {
  43649. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43650. }
  43651. if (defines.NORMAL) {
  43652. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43653. }
  43654. if (defines.AMBIENT) {
  43655. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43656. }
  43657. if (defines.EMISSIVE) {
  43658. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43659. }
  43660. if (defines.VERTEXCOLOR) {
  43661. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43662. }
  43663. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43664. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43665. }
  43666. if (defines.MORPHTARGETS) {
  43667. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43668. }
  43669. //Attributes
  43670. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43671. if (defines.NORMAL) {
  43672. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43673. }
  43674. if (defines.TANGENT) {
  43675. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43676. }
  43677. if (defines.UV1) {
  43678. attribs.push(BABYLON.VertexBuffer.UVKind);
  43679. }
  43680. if (defines.UV2) {
  43681. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43682. }
  43683. if (defines.VERTEXCOLOR) {
  43684. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43685. }
  43686. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43687. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43688. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43689. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43690. "vFogInfos", "vFogColor", "pointSize",
  43691. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43692. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43693. "mBones",
  43694. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43695. "vLightingIntensity",
  43696. "logarithmicDepthConstant",
  43697. "vSphericalX", "vSphericalY", "vSphericalZ",
  43698. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43699. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43700. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43701. "vTangentSpaceParams"
  43702. ];
  43703. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43704. "bumpSampler", "lightmapSampler", "opacitySampler",
  43705. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43706. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43707. "microSurfaceSampler", "environmentBrdfSampler"];
  43708. var uniformBuffers = ["Material", "Scene"];
  43709. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43710. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43711. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43712. uniformsNames: uniforms,
  43713. uniformBuffersNames: uniformBuffers,
  43714. samplers: samplers,
  43715. defines: defines,
  43716. maxSimultaneousLights: this._maxSimultaneousLights
  43717. });
  43718. var join = defines.toString();
  43719. return engine.createEffect("pbr", {
  43720. attributes: attribs,
  43721. uniformsNames: uniforms,
  43722. uniformBuffersNames: uniformBuffers,
  43723. samplers: samplers,
  43724. defines: join,
  43725. fallbacks: fallbacks,
  43726. onCompiled: onCompiled,
  43727. onError: onError,
  43728. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43729. }, engine);
  43730. };
  43731. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43732. if (useInstances === void 0) { useInstances = null; }
  43733. if (useClipPlane === void 0) { useClipPlane = null; }
  43734. var scene = this.getScene();
  43735. var engine = scene.getEngine();
  43736. // Lights
  43737. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43738. defines._needNormals = true;
  43739. // Textures
  43740. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43741. if (defines._areTexturesDirty) {
  43742. defines._needUVs = false;
  43743. if (scene.texturesEnabled) {
  43744. if (scene.getEngine().getCaps().textureLOD) {
  43745. defines.LODBASEDMICROSFURACE = true;
  43746. }
  43747. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43748. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43749. }
  43750. else {
  43751. defines.ALBEDO = false;
  43752. }
  43753. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43754. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43755. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43756. }
  43757. else {
  43758. defines.AMBIENT = false;
  43759. }
  43760. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43762. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43763. }
  43764. else {
  43765. defines.OPACITY = false;
  43766. }
  43767. var reflectionTexture = this._getReflectionTexture();
  43768. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43769. defines.REFLECTION = true;
  43770. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43771. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43772. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43773. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43774. defines.INVERTCUBICMAP = true;
  43775. }
  43776. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43777. switch (reflectionTexture.coordinatesMode) {
  43778. case BABYLON.Texture.CUBIC_MODE:
  43779. case BABYLON.Texture.INVCUBIC_MODE:
  43780. defines.REFLECTIONMAP_CUBIC = true;
  43781. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43782. break;
  43783. case BABYLON.Texture.EXPLICIT_MODE:
  43784. defines.REFLECTIONMAP_EXPLICIT = true;
  43785. break;
  43786. case BABYLON.Texture.PLANAR_MODE:
  43787. defines.REFLECTIONMAP_PLANAR = true;
  43788. break;
  43789. case BABYLON.Texture.PROJECTION_MODE:
  43790. defines.REFLECTIONMAP_PROJECTION = true;
  43791. break;
  43792. case BABYLON.Texture.SKYBOX_MODE:
  43793. defines.REFLECTIONMAP_SKYBOX = true;
  43794. break;
  43795. case BABYLON.Texture.SPHERICAL_MODE:
  43796. defines.REFLECTIONMAP_SPHERICAL = true;
  43797. break;
  43798. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43799. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43800. break;
  43801. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43802. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43803. break;
  43804. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43805. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43806. break;
  43807. }
  43808. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43809. if (reflectionTexture.sphericalPolynomial) {
  43810. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43811. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43812. defines.USESPHERICALINVERTEX = false;
  43813. }
  43814. else {
  43815. defines.USESPHERICALINVERTEX = true;
  43816. }
  43817. }
  43818. }
  43819. }
  43820. else {
  43821. defines.REFLECTION = false;
  43822. defines.REFLECTIONMAP_3D = false;
  43823. defines.REFLECTIONMAP_SPHERICAL = false;
  43824. defines.REFLECTIONMAP_PLANAR = false;
  43825. defines.REFLECTIONMAP_CUBIC = false;
  43826. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43827. defines.REFLECTIONMAP_PROJECTION = false;
  43828. defines.REFLECTIONMAP_SKYBOX = false;
  43829. defines.REFLECTIONMAP_EXPLICIT = false;
  43830. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43831. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43832. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43833. defines.INVERTCUBICMAP = false;
  43834. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43835. defines.USESPHERICALINVERTEX = false;
  43836. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43837. defines.LODINREFLECTIONALPHA = false;
  43838. defines.GAMMAREFLECTION = false;
  43839. }
  43840. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43841. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43842. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43843. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43844. }
  43845. else {
  43846. defines.LIGHTMAP = false;
  43847. }
  43848. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43849. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43850. }
  43851. else {
  43852. defines.EMISSIVE = false;
  43853. }
  43854. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43855. if (this._metallicTexture) {
  43856. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43857. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43858. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43859. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43860. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43861. }
  43862. else if (this._reflectivityTexture) {
  43863. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43864. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43865. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43866. }
  43867. else {
  43868. defines.REFLECTIVITY = false;
  43869. }
  43870. if (this._microSurfaceTexture) {
  43871. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43872. }
  43873. else {
  43874. defines.MICROSURFACEMAP = false;
  43875. }
  43876. }
  43877. else {
  43878. defines.REFLECTIVITY = false;
  43879. defines.MICROSURFACEMAP = false;
  43880. }
  43881. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43882. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43883. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43884. defines.PARALLAX = true;
  43885. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  43886. }
  43887. else {
  43888. defines.PARALLAX = false;
  43889. }
  43890. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43891. }
  43892. else {
  43893. defines.BUMP = false;
  43894. }
  43895. var refractionTexture = this._getRefractionTexture();
  43896. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43897. defines.REFRACTION = true;
  43898. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  43899. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  43900. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  43901. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  43902. if (this._linkRefractionWithTransparency) {
  43903. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  43904. }
  43905. }
  43906. else {
  43907. defines.REFRACTION = false;
  43908. }
  43909. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43910. defines.ENVIRONMENTBRDF = true;
  43911. }
  43912. else {
  43913. defines.ENVIRONMENTBRDF = false;
  43914. }
  43915. if (this._shouldUseAlphaFromAlbedoTexture()) {
  43916. defines.ALPHAFROMALBEDO = true;
  43917. }
  43918. else {
  43919. defines.ALPHAFROMALBEDO = false;
  43920. }
  43921. }
  43922. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43923. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  43924. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  43925. if (!this.backFaceCulling && this._twoSidedLighting) {
  43926. defines.TWOSIDEDLIGHTING = true;
  43927. }
  43928. else {
  43929. defines.TWOSIDEDLIGHTING = false;
  43930. }
  43931. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  43932. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43933. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  43934. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  43935. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  43936. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  43937. }
  43938. if (defines._areImageProcessingDirty) {
  43939. this._imageProcessingConfiguration.prepareDefines(defines);
  43940. }
  43941. defines.FORCENORMALFORWARD = this._forceNormalForward;
  43942. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  43943. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  43944. // Misc.
  43945. if (defines._areMiscDirty) {
  43946. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  43947. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  43948. }
  43949. // Values that need to be evaluated on every frame
  43950. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  43951. // Attribs
  43952. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  43953. };
  43954. /**
  43955. * Force shader compilation
  43956. */
  43957. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  43958. var _this = this;
  43959. var localOptions = __assign({ clipPlane: false }, options);
  43960. var defines = new PBRMaterialDefines();
  43961. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  43962. if (effect.isReady()) {
  43963. if (onCompiled) {
  43964. onCompiled(this);
  43965. }
  43966. }
  43967. else {
  43968. effect.onCompileObservable.add(function () {
  43969. if (onCompiled) {
  43970. onCompiled(_this);
  43971. }
  43972. });
  43973. }
  43974. };
  43975. /**
  43976. * Initializes the uniform buffer layout for the shader.
  43977. */
  43978. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  43979. // Order is important !
  43980. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  43981. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  43982. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43983. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43984. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43985. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  43986. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  43987. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43988. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43989. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43990. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43991. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43992. this._uniformBuffer.addUniform("albedoMatrix", 16);
  43993. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43994. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43995. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43996. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43997. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  43998. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  43999. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44000. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44001. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44002. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44003. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44004. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44005. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44006. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44007. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44008. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44009. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44010. this._uniformBuffer.addUniform("pointSize", 1);
  44011. this._uniformBuffer.create();
  44012. };
  44013. /**
  44014. * Unbinds the textures.
  44015. */
  44016. PBRBaseMaterial.prototype.unbind = function () {
  44017. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44018. this._uniformBuffer.setTexture("reflectionSampler", null);
  44019. }
  44020. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44021. this._uniformBuffer.setTexture("refractionSampler", null);
  44022. }
  44023. _super.prototype.unbind.call(this);
  44024. };
  44025. /**
  44026. * Binds the submesh data.
  44027. * @param world - The world matrix.
  44028. * @param mesh - The BJS mesh.
  44029. * @param subMesh - A submesh of the BJS mesh.
  44030. */
  44031. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44032. var scene = this.getScene();
  44033. var defines = subMesh._materialDefines;
  44034. if (!defines) {
  44035. return;
  44036. }
  44037. var effect = subMesh.effect;
  44038. if (!effect) {
  44039. return;
  44040. }
  44041. this._activeEffect = effect;
  44042. // Matrices
  44043. this.bindOnlyWorldMatrix(world);
  44044. // Normal Matrix
  44045. if (defines.OBJECTSPACE_NORMALMAP) {
  44046. world.toNormalMatrix(this._normalMatrix);
  44047. this.bindOnlyNormalMatrix(this._normalMatrix);
  44048. }
  44049. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44050. // Bones
  44051. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44052. var reflectionTexture = null;
  44053. if (mustRebind) {
  44054. this._uniformBuffer.bindToEffect(effect, "Material");
  44055. this.bindViewProjection(effect);
  44056. reflectionTexture = this._getReflectionTexture();
  44057. var refractionTexture = this._getRefractionTexture();
  44058. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44059. // Texture uniforms
  44060. if (scene.texturesEnabled) {
  44061. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44062. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44063. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44064. }
  44065. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44066. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44067. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44068. }
  44069. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44070. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44071. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44072. }
  44073. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44074. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44075. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44076. if (reflectionTexture.boundingBoxSize) {
  44077. var cubeTexture = reflectionTexture;
  44078. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44079. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44080. }
  44081. var polynomials = reflectionTexture.sphericalPolynomial;
  44082. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44083. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44084. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44085. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44086. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44087. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44088. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44089. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44090. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44091. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44092. }
  44093. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44094. }
  44095. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44096. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44097. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44098. }
  44099. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44100. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44101. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44102. }
  44103. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44104. if (this._metallicTexture) {
  44105. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44106. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44107. }
  44108. else if (this._reflectivityTexture) {
  44109. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44110. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44111. }
  44112. if (this._microSurfaceTexture) {
  44113. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44114. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44115. }
  44116. }
  44117. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44118. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44119. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44120. if (scene._mirroredCameraPosition) {
  44121. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44122. }
  44123. else {
  44124. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44125. }
  44126. }
  44127. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44128. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44129. var depth = 1.0;
  44130. if (!refractionTexture.isCube) {
  44131. if (refractionTexture.depth) {
  44132. depth = refractionTexture.depth;
  44133. }
  44134. }
  44135. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44136. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44137. }
  44138. }
  44139. // Point size
  44140. if (this.pointsCloud) {
  44141. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44142. }
  44143. // Colors
  44144. if (defines.METALLICWORKFLOW) {
  44145. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44146. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44147. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44148. }
  44149. else {
  44150. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44151. }
  44152. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44153. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44154. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44155. // Misc
  44156. this._lightingInfos.x = this._directIntensity;
  44157. this._lightingInfos.y = this._emissiveIntensity;
  44158. this._lightingInfos.z = this._environmentIntensity;
  44159. this._lightingInfos.w = this._specularIntensity;
  44160. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44161. }
  44162. // Textures
  44163. if (scene.texturesEnabled) {
  44164. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44165. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44166. }
  44167. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44168. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44169. }
  44170. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44171. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44172. }
  44173. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44174. if (defines.LODBASEDMICROSFURACE) {
  44175. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44176. }
  44177. else {
  44178. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44179. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44180. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44181. }
  44182. }
  44183. if (defines.ENVIRONMENTBRDF) {
  44184. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44185. }
  44186. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44187. if (defines.LODBASEDMICROSFURACE) {
  44188. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44189. }
  44190. else {
  44191. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44192. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44193. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44194. }
  44195. }
  44196. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44197. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44198. }
  44199. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44200. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44201. }
  44202. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44203. if (this._metallicTexture) {
  44204. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44205. }
  44206. else if (this._reflectivityTexture) {
  44207. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44208. }
  44209. if (this._microSurfaceTexture) {
  44210. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44211. }
  44212. }
  44213. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44214. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44215. }
  44216. }
  44217. // Clip plane
  44218. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44219. // Colors
  44220. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44221. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44222. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44223. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44224. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44225. }
  44226. if (mustRebind || !this.isFrozen) {
  44227. // Lights
  44228. if (scene.lightsEnabled && !this._disableLighting) {
  44229. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44230. }
  44231. // View
  44232. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44233. this.bindView(effect);
  44234. }
  44235. // Fog
  44236. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44237. // Morph targets
  44238. if (defines.NUM_MORPH_INFLUENCERS) {
  44239. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44240. }
  44241. // image processing
  44242. this._imageProcessingConfiguration.bind(this._activeEffect);
  44243. // Log. depth
  44244. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44245. }
  44246. this._uniformBuffer.update();
  44247. this._afterBind(mesh);
  44248. };
  44249. /**
  44250. * Returns the animatable textures.
  44251. * @returns - Array of animatable textures.
  44252. */
  44253. PBRBaseMaterial.prototype.getAnimatables = function () {
  44254. var results = [];
  44255. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44256. results.push(this._albedoTexture);
  44257. }
  44258. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44259. results.push(this._ambientTexture);
  44260. }
  44261. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44262. results.push(this._opacityTexture);
  44263. }
  44264. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44265. results.push(this._reflectionTexture);
  44266. }
  44267. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44268. results.push(this._emissiveTexture);
  44269. }
  44270. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44271. results.push(this._metallicTexture);
  44272. }
  44273. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44274. results.push(this._reflectivityTexture);
  44275. }
  44276. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44277. results.push(this._bumpTexture);
  44278. }
  44279. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44280. results.push(this._lightmapTexture);
  44281. }
  44282. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44283. results.push(this._refractionTexture);
  44284. }
  44285. return results;
  44286. };
  44287. /**
  44288. * Returns the texture used for reflections.
  44289. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44290. */
  44291. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44292. if (this._reflectionTexture) {
  44293. return this._reflectionTexture;
  44294. }
  44295. return this.getScene().environmentTexture;
  44296. };
  44297. /**
  44298. * Returns the texture used for refraction or null if none is used.
  44299. * @returns - Refection texture if present. If no refraction texture and refraction
  44300. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44301. */
  44302. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44303. if (this._refractionTexture) {
  44304. return this._refractionTexture;
  44305. }
  44306. if (this._linkRefractionWithTransparency) {
  44307. return this.getScene().environmentTexture;
  44308. }
  44309. return null;
  44310. };
  44311. /**
  44312. * Disposes the resources of the material.
  44313. * @param forceDisposeEffect - Forces the disposal of effects.
  44314. * @param forceDisposeTextures - Forces the disposal of all textures.
  44315. */
  44316. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44317. if (forceDisposeTextures) {
  44318. if (this._albedoTexture) {
  44319. this._albedoTexture.dispose();
  44320. }
  44321. if (this._ambientTexture) {
  44322. this._ambientTexture.dispose();
  44323. }
  44324. if (this._opacityTexture) {
  44325. this._opacityTexture.dispose();
  44326. }
  44327. if (this._reflectionTexture) {
  44328. this._reflectionTexture.dispose();
  44329. }
  44330. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44331. this._environmentBRDFTexture.dispose();
  44332. }
  44333. if (this._emissiveTexture) {
  44334. this._emissiveTexture.dispose();
  44335. }
  44336. if (this._metallicTexture) {
  44337. this._metallicTexture.dispose();
  44338. }
  44339. if (this._reflectivityTexture) {
  44340. this._reflectivityTexture.dispose();
  44341. }
  44342. if (this._bumpTexture) {
  44343. this._bumpTexture.dispose();
  44344. }
  44345. if (this._lightmapTexture) {
  44346. this._lightmapTexture.dispose();
  44347. }
  44348. if (this._refractionTexture) {
  44349. this._refractionTexture.dispose();
  44350. }
  44351. }
  44352. this._renderTargets.dispose();
  44353. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44354. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44355. }
  44356. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44357. };
  44358. /**
  44359. * Stores the reflectivity values based on metallic roughness workflow.
  44360. */
  44361. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44362. __decorate([
  44363. BABYLON.serializeAsImageProcessingConfiguration()
  44364. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44365. __decorate([
  44366. BABYLON.serialize()
  44367. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44368. __decorate([
  44369. BABYLON.serialize()
  44370. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44371. return PBRBaseMaterial;
  44372. }(BABYLON.PushMaterial));
  44373. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44374. })(BABYLON || (BABYLON = {}));
  44375. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44376. "use strict";
  44377. var BABYLON;
  44378. (function (BABYLON) {
  44379. /**
  44380. * The Physically based simple base material of BJS.
  44381. *
  44382. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44383. * It is used as the base class for both the specGloss and metalRough conventions.
  44384. */
  44385. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44386. __extends(PBRBaseSimpleMaterial, _super);
  44387. /**
  44388. * Instantiates a new PBRMaterial instance.
  44389. *
  44390. * @param name The material name
  44391. * @param scene The scene the material will be use in.
  44392. */
  44393. function PBRBaseSimpleMaterial(name, scene) {
  44394. var _this = _super.call(this, name, scene) || this;
  44395. /**
  44396. * Number of Simultaneous lights allowed on the material.
  44397. */
  44398. _this.maxSimultaneousLights = 4;
  44399. /**
  44400. * If sets to true, disables all the lights affecting the material.
  44401. */
  44402. _this.disableLighting = false;
  44403. /**
  44404. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44405. */
  44406. _this.invertNormalMapX = false;
  44407. /**
  44408. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44409. */
  44410. _this.invertNormalMapY = false;
  44411. /**
  44412. * Emissivie color used to self-illuminate the model.
  44413. */
  44414. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44415. /**
  44416. * Occlusion Channel Strenght.
  44417. */
  44418. _this.occlusionStrength = 1.0;
  44419. _this.useLightmapAsShadowmap = false;
  44420. _this._useAlphaFromAlbedoTexture = true;
  44421. _this._useAmbientInGrayScale = true;
  44422. return _this;
  44423. }
  44424. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44425. /**
  44426. * Gets the current double sided mode.
  44427. */
  44428. get: function () {
  44429. return this._twoSidedLighting;
  44430. },
  44431. /**
  44432. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44433. */
  44434. set: function (value) {
  44435. if (this._twoSidedLighting === value) {
  44436. return;
  44437. }
  44438. this._twoSidedLighting = value;
  44439. this.backFaceCulling = !value;
  44440. this._markAllSubMeshesAsTexturesDirty();
  44441. },
  44442. enumerable: true,
  44443. configurable: true
  44444. });
  44445. /**
  44446. * Return the active textures of the material.
  44447. */
  44448. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44449. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44450. if (this.environmentTexture) {
  44451. activeTextures.push(this.environmentTexture);
  44452. }
  44453. if (this.normalTexture) {
  44454. activeTextures.push(this.normalTexture);
  44455. }
  44456. if (this.emissiveTexture) {
  44457. activeTextures.push(this.emissiveTexture);
  44458. }
  44459. if (this.occlusionTexture) {
  44460. activeTextures.push(this.occlusionTexture);
  44461. }
  44462. if (this.lightmapTexture) {
  44463. activeTextures.push(this.lightmapTexture);
  44464. }
  44465. return activeTextures;
  44466. };
  44467. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44468. if (_super.prototype.hasTexture.call(this, texture)) {
  44469. return true;
  44470. }
  44471. if (this.lightmapTexture === texture) {
  44472. return true;
  44473. }
  44474. return false;
  44475. };
  44476. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44477. return "PBRBaseSimpleMaterial";
  44478. };
  44479. __decorate([
  44480. BABYLON.serialize(),
  44481. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44482. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44483. __decorate([
  44484. BABYLON.serialize(),
  44485. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44486. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44487. __decorate([
  44488. BABYLON.serializeAsTexture(),
  44489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44490. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44491. __decorate([
  44492. BABYLON.serialize(),
  44493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44494. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44495. __decorate([
  44496. BABYLON.serialize(),
  44497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44498. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44499. __decorate([
  44500. BABYLON.serializeAsTexture(),
  44501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44502. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44503. __decorate([
  44504. BABYLON.serializeAsColor3("emissive"),
  44505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44506. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44507. __decorate([
  44508. BABYLON.serializeAsTexture(),
  44509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44510. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44511. __decorate([
  44512. BABYLON.serialize(),
  44513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44514. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44515. __decorate([
  44516. BABYLON.serializeAsTexture(),
  44517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44518. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44519. __decorate([
  44520. BABYLON.serialize(),
  44521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44522. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44523. __decorate([
  44524. BABYLON.serialize()
  44525. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44526. __decorate([
  44527. BABYLON.serializeAsTexture(),
  44528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44529. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44530. __decorate([
  44531. BABYLON.serialize(),
  44532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44533. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44534. return PBRBaseSimpleMaterial;
  44535. }(BABYLON.PBRBaseMaterial));
  44536. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44537. })(BABYLON || (BABYLON = {}));
  44538. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44539. "use strict";
  44540. var BABYLON;
  44541. (function (BABYLON) {
  44542. /**
  44543. * The Physically based material of BJS.
  44544. *
  44545. * This offers the main features of a standard PBR material.
  44546. * For more information, please refer to the documentation :
  44547. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44548. */
  44549. var PBRMaterial = /** @class */ (function (_super) {
  44550. __extends(PBRMaterial, _super);
  44551. /**
  44552. * Instantiates a new PBRMaterial instance.
  44553. *
  44554. * @param name The material name
  44555. * @param scene The scene the material will be use in.
  44556. */
  44557. function PBRMaterial(name, scene) {
  44558. var _this = _super.call(this, name, scene) || this;
  44559. /**
  44560. * Intensity of the direct lights e.g. the four lights available in your scene.
  44561. * This impacts both the direct diffuse and specular highlights.
  44562. */
  44563. _this.directIntensity = 1.0;
  44564. /**
  44565. * Intensity of the emissive part of the material.
  44566. * This helps controlling the emissive effect without modifying the emissive color.
  44567. */
  44568. _this.emissiveIntensity = 1.0;
  44569. /**
  44570. * Intensity of the environment e.g. how much the environment will light the object
  44571. * either through harmonics for rough material or through the refelction for shiny ones.
  44572. */
  44573. _this.environmentIntensity = 1.0;
  44574. /**
  44575. * This is a special control allowing the reduction of the specular highlights coming from the
  44576. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44577. */
  44578. _this.specularIntensity = 1.0;
  44579. /**
  44580. * Debug Control allowing disabling the bump map on this material.
  44581. */
  44582. _this.disableBumpMap = false;
  44583. /**
  44584. * AKA Occlusion Texture Intensity in other nomenclature.
  44585. */
  44586. _this.ambientTextureStrength = 1.0;
  44587. /**
  44588. * The color of a material in ambient lighting.
  44589. */
  44590. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44591. /**
  44592. * AKA Diffuse Color in other nomenclature.
  44593. */
  44594. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44595. /**
  44596. * AKA Specular Color in other nomenclature.
  44597. */
  44598. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44599. /**
  44600. * The color reflected from the material.
  44601. */
  44602. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44603. /**
  44604. * The color emitted from the material.
  44605. */
  44606. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44607. /**
  44608. * AKA Glossiness in other nomenclature.
  44609. */
  44610. _this.microSurface = 1.0;
  44611. /**
  44612. * source material index of refraction (IOR)' / 'destination material IOR.
  44613. */
  44614. _this.indexOfRefraction = 0.66;
  44615. /**
  44616. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44617. */
  44618. _this.invertRefractionY = false;
  44619. /**
  44620. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44621. * Materials half opaque for instance using refraction could benefit from this control.
  44622. */
  44623. _this.linkRefractionWithTransparency = false;
  44624. _this.useLightmapAsShadowmap = false;
  44625. /**
  44626. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44627. */
  44628. _this.useAlphaFromAlbedoTexture = false;
  44629. /**
  44630. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44631. */
  44632. _this.forceAlphaTest = false;
  44633. /**
  44634. * Defines the alpha limits in alpha test mode.
  44635. */
  44636. _this.alphaCutOff = 0.4;
  44637. /**
  44638. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44639. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44640. */
  44641. _this.useSpecularOverAlpha = true;
  44642. /**
  44643. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44644. */
  44645. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44646. /**
  44647. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44648. */
  44649. _this.useRoughnessFromMetallicTextureAlpha = true;
  44650. /**
  44651. * Specifies if the metallic texture contains the roughness information in its green channel.
  44652. */
  44653. _this.useRoughnessFromMetallicTextureGreen = false;
  44654. /**
  44655. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44656. */
  44657. _this.useMetallnessFromMetallicTextureBlue = false;
  44658. /**
  44659. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44660. */
  44661. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44662. /**
  44663. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44664. */
  44665. _this.useAmbientInGrayScale = false;
  44666. /**
  44667. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44668. * The material will try to infer what glossiness each pixel should be.
  44669. */
  44670. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44671. /**
  44672. * BJS is using an harcoded light falloff based on a manually sets up range.
  44673. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44674. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44675. */
  44676. _this.usePhysicalLightFalloff = true;
  44677. /**
  44678. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44679. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44680. */
  44681. _this.useRadianceOverAlpha = true;
  44682. /**
  44683. * Allows using an object space normal map (instead of tangent space).
  44684. */
  44685. _this.useObjectSpaceNormalMap = false;
  44686. /**
  44687. * Allows using the bump map in parallax mode.
  44688. */
  44689. _this.useParallax = false;
  44690. /**
  44691. * Allows using the bump map in parallax occlusion mode.
  44692. */
  44693. _this.useParallaxOcclusion = false;
  44694. /**
  44695. * Controls the scale bias of the parallax mode.
  44696. */
  44697. _this.parallaxScaleBias = 0.05;
  44698. /**
  44699. * If sets to true, disables all the lights affecting the material.
  44700. */
  44701. _this.disableLighting = false;
  44702. /**
  44703. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44704. */
  44705. _this.forceIrradianceInFragment = false;
  44706. /**
  44707. * Number of Simultaneous lights allowed on the material.
  44708. */
  44709. _this.maxSimultaneousLights = 4;
  44710. /**
  44711. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44712. */
  44713. _this.invertNormalMapX = false;
  44714. /**
  44715. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44716. */
  44717. _this.invertNormalMapY = false;
  44718. /**
  44719. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44720. */
  44721. _this.twoSidedLighting = false;
  44722. /**
  44723. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44724. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44725. */
  44726. _this.useAlphaFresnel = false;
  44727. /**
  44728. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44729. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44730. */
  44731. _this.useLinearAlphaFresnel = false;
  44732. /**
  44733. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44734. * And/Or occlude the blended part.
  44735. */
  44736. _this.environmentBRDFTexture = null;
  44737. /**
  44738. * Force normal to face away from face.
  44739. */
  44740. _this.forceNormalForward = false;
  44741. /**
  44742. * Enables specular anti aliasing in the PBR shader.
  44743. * It will both interacts on the Geometry for analytical and IBL lighting.
  44744. * It also prefilter the roughness map based on the bump values.
  44745. */
  44746. _this.enableSpecularAntiAliasing = false;
  44747. /**
  44748. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44749. * makes the reflect vector face the model (under horizon).
  44750. */
  44751. _this.useHorizonOcclusion = true;
  44752. /**
  44753. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44754. * too much the area relying on ambient texture to define their ambient occlusion.
  44755. */
  44756. _this.useRadianceOcclusion = true;
  44757. /**
  44758. * If set to true, no lighting calculations will be applied.
  44759. */
  44760. _this.unlit = false;
  44761. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44762. return _this;
  44763. }
  44764. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44765. /**
  44766. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44767. */
  44768. get: function () {
  44769. return this._PBRMATERIAL_OPAQUE;
  44770. },
  44771. enumerable: true,
  44772. configurable: true
  44773. });
  44774. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44775. /**
  44776. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44777. */
  44778. get: function () {
  44779. return this._PBRMATERIAL_ALPHATEST;
  44780. },
  44781. enumerable: true,
  44782. configurable: true
  44783. });
  44784. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44785. /**
  44786. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44787. */
  44788. get: function () {
  44789. return this._PBRMATERIAL_ALPHABLEND;
  44790. },
  44791. enumerable: true,
  44792. configurable: true
  44793. });
  44794. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44795. /**
  44796. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44797. * They are also discarded below the alpha cutoff threshold to improve performances.
  44798. */
  44799. get: function () {
  44800. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44801. },
  44802. enumerable: true,
  44803. configurable: true
  44804. });
  44805. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44806. /**
  44807. * Gets the image processing configuration used either in this material.
  44808. */
  44809. get: function () {
  44810. return this._imageProcessingConfiguration;
  44811. },
  44812. /**
  44813. * Sets the Default image processing configuration used either in the this material.
  44814. *
  44815. * If sets to null, the scene one is in use.
  44816. */
  44817. set: function (value) {
  44818. this._attachImageProcessingConfiguration(value);
  44819. // Ensure the effect will be rebuilt.
  44820. this._markAllSubMeshesAsTexturesDirty();
  44821. },
  44822. enumerable: true,
  44823. configurable: true
  44824. });
  44825. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44826. /**
  44827. * Gets wether the color curves effect is enabled.
  44828. */
  44829. get: function () {
  44830. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44831. },
  44832. /**
  44833. * Sets wether the color curves effect is enabled.
  44834. */
  44835. set: function (value) {
  44836. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44837. },
  44838. enumerable: true,
  44839. configurable: true
  44840. });
  44841. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44842. /**
  44843. * Gets wether the color grading effect is enabled.
  44844. */
  44845. get: function () {
  44846. return this.imageProcessingConfiguration.colorGradingEnabled;
  44847. },
  44848. /**
  44849. * Gets wether the color grading effect is enabled.
  44850. */
  44851. set: function (value) {
  44852. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44853. },
  44854. enumerable: true,
  44855. configurable: true
  44856. });
  44857. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  44858. /**
  44859. * Gets wether tonemapping is enabled or not.
  44860. */
  44861. get: function () {
  44862. return this._imageProcessingConfiguration.toneMappingEnabled;
  44863. },
  44864. /**
  44865. * Sets wether tonemapping is enabled or not
  44866. */
  44867. set: function (value) {
  44868. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44869. },
  44870. enumerable: true,
  44871. configurable: true
  44872. });
  44873. ;
  44874. ;
  44875. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  44876. /**
  44877. * The camera exposure used on this material.
  44878. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44879. * This corresponds to a photographic exposure.
  44880. */
  44881. get: function () {
  44882. return this._imageProcessingConfiguration.exposure;
  44883. },
  44884. /**
  44885. * The camera exposure used on this material.
  44886. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44887. * This corresponds to a photographic exposure.
  44888. */
  44889. set: function (value) {
  44890. this._imageProcessingConfiguration.exposure = value;
  44891. },
  44892. enumerable: true,
  44893. configurable: true
  44894. });
  44895. ;
  44896. ;
  44897. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  44898. /**
  44899. * Gets The camera contrast used on this material.
  44900. */
  44901. get: function () {
  44902. return this._imageProcessingConfiguration.contrast;
  44903. },
  44904. /**
  44905. * Sets The camera contrast used on this material.
  44906. */
  44907. set: function (value) {
  44908. this._imageProcessingConfiguration.contrast = value;
  44909. },
  44910. enumerable: true,
  44911. configurable: true
  44912. });
  44913. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  44914. /**
  44915. * Gets the Color Grading 2D Lookup Texture.
  44916. */
  44917. get: function () {
  44918. return this._imageProcessingConfiguration.colorGradingTexture;
  44919. },
  44920. /**
  44921. * Sets the Color Grading 2D Lookup Texture.
  44922. */
  44923. set: function (value) {
  44924. this._imageProcessingConfiguration.colorGradingTexture = value;
  44925. },
  44926. enumerable: true,
  44927. configurable: true
  44928. });
  44929. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  44930. /**
  44931. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44932. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44933. * 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;
  44934. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44935. */
  44936. get: function () {
  44937. return this._imageProcessingConfiguration.colorCurves;
  44938. },
  44939. /**
  44940. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44941. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44942. * 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;
  44943. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44944. */
  44945. set: function (value) {
  44946. this._imageProcessingConfiguration.colorCurves = value;
  44947. },
  44948. enumerable: true,
  44949. configurable: true
  44950. });
  44951. /**
  44952. * Returns the name of this material class.
  44953. */
  44954. PBRMaterial.prototype.getClassName = function () {
  44955. return "PBRMaterial";
  44956. };
  44957. /**
  44958. * Returns an array of the actively used textures.
  44959. * @returns - Array of BaseTextures
  44960. */
  44961. PBRMaterial.prototype.getActiveTextures = function () {
  44962. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44963. if (this._albedoTexture) {
  44964. activeTextures.push(this._albedoTexture);
  44965. }
  44966. if (this._ambientTexture) {
  44967. activeTextures.push(this._ambientTexture);
  44968. }
  44969. if (this._opacityTexture) {
  44970. activeTextures.push(this._opacityTexture);
  44971. }
  44972. if (this._reflectionTexture) {
  44973. activeTextures.push(this._reflectionTexture);
  44974. }
  44975. if (this._emissiveTexture) {
  44976. activeTextures.push(this._emissiveTexture);
  44977. }
  44978. if (this._reflectivityTexture) {
  44979. activeTextures.push(this._reflectivityTexture);
  44980. }
  44981. if (this._metallicTexture) {
  44982. activeTextures.push(this._metallicTexture);
  44983. }
  44984. if (this._microSurfaceTexture) {
  44985. activeTextures.push(this._microSurfaceTexture);
  44986. }
  44987. if (this._bumpTexture) {
  44988. activeTextures.push(this._bumpTexture);
  44989. }
  44990. if (this._lightmapTexture) {
  44991. activeTextures.push(this._lightmapTexture);
  44992. }
  44993. if (this._refractionTexture) {
  44994. activeTextures.push(this._refractionTexture);
  44995. }
  44996. return activeTextures;
  44997. };
  44998. /**
  44999. * Checks to see if a texture is used in the material.
  45000. * @param texture - Base texture to use.
  45001. * @returns - Boolean specifying if a texture is used in the material.
  45002. */
  45003. PBRMaterial.prototype.hasTexture = function (texture) {
  45004. if (_super.prototype.hasTexture.call(this, texture)) {
  45005. return true;
  45006. }
  45007. if (this._albedoTexture === texture) {
  45008. return true;
  45009. }
  45010. if (this._ambientTexture === texture) {
  45011. return true;
  45012. }
  45013. if (this._opacityTexture === texture) {
  45014. return true;
  45015. }
  45016. if (this._reflectionTexture === texture) {
  45017. return true;
  45018. }
  45019. if (this._reflectivityTexture === texture) {
  45020. return true;
  45021. }
  45022. if (this._metallicTexture === texture) {
  45023. return true;
  45024. }
  45025. if (this._microSurfaceTexture === texture) {
  45026. return true;
  45027. }
  45028. if (this._bumpTexture === texture) {
  45029. return true;
  45030. }
  45031. if (this._lightmapTexture === texture) {
  45032. return true;
  45033. }
  45034. if (this._refractionTexture === texture) {
  45035. return true;
  45036. }
  45037. return false;
  45038. };
  45039. /**
  45040. * Makes a duplicate of the current material.
  45041. * @param name - name to use for the new material.
  45042. */
  45043. PBRMaterial.prototype.clone = function (name) {
  45044. var _this = this;
  45045. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45046. clone.id = name;
  45047. clone.name = name;
  45048. return clone;
  45049. };
  45050. /**
  45051. * Serializes this PBR Material.
  45052. * @returns - An object with the serialized material.
  45053. */
  45054. PBRMaterial.prototype.serialize = function () {
  45055. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45056. serializationObject.customType = "BABYLON.PBRMaterial";
  45057. return serializationObject;
  45058. };
  45059. // Statics
  45060. /**
  45061. * Parses a PBR Material from a serialized object.
  45062. * @param source - Serialized object.
  45063. * @param scene - BJS scene instance.
  45064. * @param rootUrl - url for the scene object
  45065. * @returns - PBRMaterial
  45066. */
  45067. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45068. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45069. };
  45070. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45071. /**
  45072. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45073. */
  45074. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45075. /**
  45076. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45077. */
  45078. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45079. /**
  45080. * 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.
  45081. * They are also discarded below the alpha cutoff threshold to improve performances.
  45082. */
  45083. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45084. __decorate([
  45085. BABYLON.serialize(),
  45086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45087. ], PBRMaterial.prototype, "directIntensity", void 0);
  45088. __decorate([
  45089. BABYLON.serialize(),
  45090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45091. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45092. __decorate([
  45093. BABYLON.serialize(),
  45094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45095. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45096. __decorate([
  45097. BABYLON.serialize(),
  45098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45099. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45100. __decorate([
  45101. BABYLON.serialize(),
  45102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45103. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45104. __decorate([
  45105. BABYLON.serializeAsTexture(),
  45106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45107. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45108. __decorate([
  45109. BABYLON.serializeAsTexture(),
  45110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45111. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45112. __decorate([
  45113. BABYLON.serialize(),
  45114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45115. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45116. __decorate([
  45117. BABYLON.serializeAsTexture(),
  45118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45119. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45120. __decorate([
  45121. BABYLON.serializeAsTexture(),
  45122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45123. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45124. __decorate([
  45125. BABYLON.serializeAsTexture(),
  45126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45127. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45128. __decorate([
  45129. BABYLON.serializeAsTexture(),
  45130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45131. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45132. __decorate([
  45133. BABYLON.serializeAsTexture(),
  45134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45135. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45136. __decorate([
  45137. BABYLON.serialize(),
  45138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45139. ], PBRMaterial.prototype, "metallic", void 0);
  45140. __decorate([
  45141. BABYLON.serialize(),
  45142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45143. ], PBRMaterial.prototype, "roughness", void 0);
  45144. __decorate([
  45145. BABYLON.serializeAsTexture(),
  45146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45147. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45148. __decorate([
  45149. BABYLON.serializeAsTexture(),
  45150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45151. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45152. __decorate([
  45153. BABYLON.serializeAsTexture(),
  45154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45155. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45156. __decorate([
  45157. BABYLON.serializeAsTexture(),
  45158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45159. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45160. __decorate([
  45161. BABYLON.serializeAsColor3("ambient"),
  45162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45163. ], PBRMaterial.prototype, "ambientColor", void 0);
  45164. __decorate([
  45165. BABYLON.serializeAsColor3("albedo"),
  45166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45167. ], PBRMaterial.prototype, "albedoColor", void 0);
  45168. __decorate([
  45169. BABYLON.serializeAsColor3("reflectivity"),
  45170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45171. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45172. __decorate([
  45173. BABYLON.serializeAsColor3("reflection"),
  45174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45175. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45176. __decorate([
  45177. BABYLON.serializeAsColor3("emissive"),
  45178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45179. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45180. __decorate([
  45181. BABYLON.serialize(),
  45182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45183. ], PBRMaterial.prototype, "microSurface", void 0);
  45184. __decorate([
  45185. BABYLON.serialize(),
  45186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45187. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45188. __decorate([
  45189. BABYLON.serialize(),
  45190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45191. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45192. __decorate([
  45193. BABYLON.serialize(),
  45194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45195. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45196. __decorate([
  45197. BABYLON.serialize(),
  45198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45199. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45200. __decorate([
  45201. BABYLON.serialize(),
  45202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45203. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45204. __decorate([
  45205. BABYLON.serialize(),
  45206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45207. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45208. __decorate([
  45209. BABYLON.serialize(),
  45210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45211. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45212. __decorate([
  45213. BABYLON.serialize(),
  45214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45215. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45216. __decorate([
  45217. BABYLON.serialize(),
  45218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45219. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45220. __decorate([
  45221. BABYLON.serialize(),
  45222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45223. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45224. __decorate([
  45225. BABYLON.serialize(),
  45226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45227. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45228. __decorate([
  45229. BABYLON.serialize(),
  45230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45231. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45232. __decorate([
  45233. BABYLON.serialize(),
  45234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45235. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45236. __decorate([
  45237. BABYLON.serialize(),
  45238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45239. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45240. __decorate([
  45241. BABYLON.serialize(),
  45242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45243. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45244. __decorate([
  45245. BABYLON.serialize(),
  45246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45247. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45248. __decorate([
  45249. BABYLON.serialize(),
  45250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45251. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45252. __decorate([
  45253. BABYLON.serialize(),
  45254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45255. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45256. __decorate([
  45257. BABYLON.serialize(),
  45258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45259. ], PBRMaterial.prototype, "useParallax", void 0);
  45260. __decorate([
  45261. BABYLON.serialize(),
  45262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45263. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45264. __decorate([
  45265. BABYLON.serialize(),
  45266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45267. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45268. __decorate([
  45269. BABYLON.serialize(),
  45270. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45271. ], PBRMaterial.prototype, "disableLighting", void 0);
  45272. __decorate([
  45273. BABYLON.serialize(),
  45274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45275. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45276. __decorate([
  45277. BABYLON.serialize(),
  45278. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45279. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45280. __decorate([
  45281. BABYLON.serialize(),
  45282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45283. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45284. __decorate([
  45285. BABYLON.serialize(),
  45286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45287. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45288. __decorate([
  45289. BABYLON.serialize(),
  45290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45291. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45292. __decorate([
  45293. BABYLON.serialize(),
  45294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45295. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45296. __decorate([
  45297. BABYLON.serialize(),
  45298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45299. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45300. __decorate([
  45301. BABYLON.serializeAsTexture(),
  45302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45303. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45304. __decorate([
  45305. BABYLON.serialize(),
  45306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45307. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45308. __decorate([
  45309. BABYLON.serialize(),
  45310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45311. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45312. __decorate([
  45313. BABYLON.serialize(),
  45314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45315. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45316. __decorate([
  45317. BABYLON.serialize(),
  45318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45319. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45320. __decorate([
  45321. BABYLON.serialize(),
  45322. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45323. ], PBRMaterial.prototype, "unlit", void 0);
  45324. return PBRMaterial;
  45325. }(BABYLON.PBRBaseMaterial));
  45326. BABYLON.PBRMaterial = PBRMaterial;
  45327. })(BABYLON || (BABYLON = {}));
  45328. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45329. "use strict";
  45330. var BABYLON;
  45331. (function (BABYLON) {
  45332. /**
  45333. * The PBR material of BJS following the metal roughness convention.
  45334. *
  45335. * This fits to the PBR convention in the GLTF definition:
  45336. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45337. */
  45338. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45339. __extends(PBRMetallicRoughnessMaterial, _super);
  45340. /**
  45341. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45342. *
  45343. * @param name The material name
  45344. * @param scene The scene the material will be use in.
  45345. */
  45346. function PBRMetallicRoughnessMaterial(name, scene) {
  45347. var _this = _super.call(this, name, scene) || this;
  45348. _this._useRoughnessFromMetallicTextureAlpha = false;
  45349. _this._useRoughnessFromMetallicTextureGreen = true;
  45350. _this._useMetallnessFromMetallicTextureBlue = true;
  45351. _this.metallic = 1.0;
  45352. _this.roughness = 1.0;
  45353. return _this;
  45354. }
  45355. /**
  45356. * Return the currrent class name of the material.
  45357. */
  45358. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45359. return "PBRMetallicRoughnessMaterial";
  45360. };
  45361. /**
  45362. * Return the active textures of the material.
  45363. */
  45364. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45365. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45366. if (this.baseTexture) {
  45367. activeTextures.push(this.baseTexture);
  45368. }
  45369. if (this.metallicRoughnessTexture) {
  45370. activeTextures.push(this.metallicRoughnessTexture);
  45371. }
  45372. return activeTextures;
  45373. };
  45374. /**
  45375. * Checks to see if a texture is used in the material.
  45376. * @param texture - Base texture to use.
  45377. * @returns - Boolean specifying if a texture is used in the material.
  45378. */
  45379. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45380. if (_super.prototype.hasTexture.call(this, texture)) {
  45381. return true;
  45382. }
  45383. if (this.baseTexture === texture) {
  45384. return true;
  45385. }
  45386. if (this.metallicRoughnessTexture === texture) {
  45387. return true;
  45388. }
  45389. return false;
  45390. };
  45391. /**
  45392. * Makes a duplicate of the current material.
  45393. * @param name - name to use for the new material.
  45394. */
  45395. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45396. var _this = this;
  45397. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45398. clone.id = name;
  45399. clone.name = name;
  45400. return clone;
  45401. };
  45402. /**
  45403. * Serialize the material to a parsable JSON object.
  45404. */
  45405. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45406. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45407. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45408. return serializationObject;
  45409. };
  45410. /**
  45411. * Parses a JSON object correponding to the serialize function.
  45412. */
  45413. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45414. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45415. };
  45416. __decorate([
  45417. BABYLON.serializeAsColor3(),
  45418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45419. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45420. __decorate([
  45421. BABYLON.serializeAsTexture(),
  45422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45423. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45424. __decorate([
  45425. BABYLON.serialize(),
  45426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45427. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45428. __decorate([
  45429. BABYLON.serialize(),
  45430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45431. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45432. __decorate([
  45433. BABYLON.serializeAsTexture(),
  45434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45435. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45436. return PBRMetallicRoughnessMaterial;
  45437. }(BABYLON.PBRBaseSimpleMaterial));
  45438. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45439. })(BABYLON || (BABYLON = {}));
  45440. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45441. "use strict";
  45442. var BABYLON;
  45443. (function (BABYLON) {
  45444. /**
  45445. * The PBR material of BJS following the specular glossiness convention.
  45446. *
  45447. * This fits to the PBR convention in the GLTF definition:
  45448. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45449. */
  45450. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45451. __extends(PBRSpecularGlossinessMaterial, _super);
  45452. /**
  45453. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45454. *
  45455. * @param name The material name
  45456. * @param scene The scene the material will be use in.
  45457. */
  45458. function PBRSpecularGlossinessMaterial(name, scene) {
  45459. var _this = _super.call(this, name, scene) || this;
  45460. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45461. return _this;
  45462. }
  45463. /**
  45464. * Return the currrent class name of the material.
  45465. */
  45466. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45467. return "PBRSpecularGlossinessMaterial";
  45468. };
  45469. /**
  45470. * Return the active textures of the material.
  45471. */
  45472. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45473. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45474. if (this.diffuseTexture) {
  45475. activeTextures.push(this.diffuseTexture);
  45476. }
  45477. if (this.specularGlossinessTexture) {
  45478. activeTextures.push(this.specularGlossinessTexture);
  45479. }
  45480. return activeTextures;
  45481. };
  45482. /**
  45483. * Checks to see if a texture is used in the material.
  45484. * @param texture - Base texture to use.
  45485. * @returns - Boolean specifying if a texture is used in the material.
  45486. */
  45487. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45488. if (_super.prototype.hasTexture.call(this, texture)) {
  45489. return true;
  45490. }
  45491. if (this.diffuseTexture === texture) {
  45492. return true;
  45493. }
  45494. if (this.specularGlossinessTexture === texture) {
  45495. return true;
  45496. }
  45497. return false;
  45498. };
  45499. /**
  45500. * Makes a duplicate of the current material.
  45501. * @param name - name to use for the new material.
  45502. */
  45503. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45504. var _this = this;
  45505. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45506. clone.id = name;
  45507. clone.name = name;
  45508. return clone;
  45509. };
  45510. /**
  45511. * Serialize the material to a parsable JSON object.
  45512. */
  45513. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45514. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45515. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45516. return serializationObject;
  45517. };
  45518. /**
  45519. * Parses a JSON object correponding to the serialize function.
  45520. */
  45521. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45522. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45523. };
  45524. __decorate([
  45525. BABYLON.serializeAsColor3("diffuse"),
  45526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45527. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45528. __decorate([
  45529. BABYLON.serializeAsTexture(),
  45530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45531. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45532. __decorate([
  45533. BABYLON.serializeAsColor3("specular"),
  45534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45535. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45536. __decorate([
  45537. BABYLON.serialize(),
  45538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45539. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45540. __decorate([
  45541. BABYLON.serializeAsTexture(),
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45543. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45544. return PBRSpecularGlossinessMaterial;
  45545. }(BABYLON.PBRBaseSimpleMaterial));
  45546. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45547. })(BABYLON || (BABYLON = {}));
  45548. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45549. "use strict";
  45550. var BABYLON;
  45551. (function (BABYLON) {
  45552. BABYLON.CameraInputTypes = {};
  45553. var CameraInputsManager = /** @class */ (function () {
  45554. function CameraInputsManager(camera) {
  45555. this.attached = {};
  45556. this.camera = camera;
  45557. this.checkInputs = function () { };
  45558. }
  45559. /**
  45560. * Add an input method to a camera.
  45561. * builtin inputs example: camera.inputs.addGamepad();
  45562. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45563. * @param input camera input method
  45564. */
  45565. CameraInputsManager.prototype.add = function (input) {
  45566. var type = input.getSimpleName();
  45567. if (this.attached[type]) {
  45568. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45569. return;
  45570. }
  45571. this.attached[type] = input;
  45572. input.camera = this.camera;
  45573. //for checkInputs, we are dynamically creating a function
  45574. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45575. if (input.checkInputs) {
  45576. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45577. }
  45578. if (this.attachedElement) {
  45579. input.attachControl(this.attachedElement);
  45580. }
  45581. };
  45582. /**
  45583. * Remove a specific input method from a camera
  45584. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45585. * @param inputToRemove camera input method
  45586. */
  45587. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45588. for (var cam in this.attached) {
  45589. var input = this.attached[cam];
  45590. if (input === inputToRemove) {
  45591. input.detachControl(this.attachedElement);
  45592. input.camera = null;
  45593. delete this.attached[cam];
  45594. this.rebuildInputCheck();
  45595. }
  45596. }
  45597. };
  45598. CameraInputsManager.prototype.removeByType = function (inputType) {
  45599. for (var cam in this.attached) {
  45600. var input = this.attached[cam];
  45601. if (input.getClassName() === inputType) {
  45602. input.detachControl(this.attachedElement);
  45603. input.camera = null;
  45604. delete this.attached[cam];
  45605. this.rebuildInputCheck();
  45606. }
  45607. }
  45608. };
  45609. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45610. var current = this.checkInputs;
  45611. return function () {
  45612. current();
  45613. fn();
  45614. };
  45615. };
  45616. CameraInputsManager.prototype.attachInput = function (input) {
  45617. if (this.attachedElement) {
  45618. input.attachControl(this.attachedElement, this.noPreventDefault);
  45619. }
  45620. };
  45621. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45622. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45623. if (this.attachedElement) {
  45624. return;
  45625. }
  45626. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45627. this.attachedElement = element;
  45628. this.noPreventDefault = noPreventDefault;
  45629. for (var cam in this.attached) {
  45630. this.attached[cam].attachControl(element, noPreventDefault);
  45631. }
  45632. };
  45633. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45634. if (disconnect === void 0) { disconnect = false; }
  45635. if (this.attachedElement !== element) {
  45636. return;
  45637. }
  45638. for (var cam in this.attached) {
  45639. this.attached[cam].detachControl(element);
  45640. if (disconnect) {
  45641. this.attached[cam].camera = null;
  45642. }
  45643. }
  45644. this.attachedElement = null;
  45645. };
  45646. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45647. this.checkInputs = function () { };
  45648. for (var cam in this.attached) {
  45649. var input = this.attached[cam];
  45650. if (input.checkInputs) {
  45651. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45652. }
  45653. }
  45654. };
  45655. /**
  45656. * Remove all attached input methods from a camera
  45657. */
  45658. CameraInputsManager.prototype.clear = function () {
  45659. if (this.attachedElement) {
  45660. this.detachElement(this.attachedElement, true);
  45661. }
  45662. this.attached = {};
  45663. this.attachedElement = null;
  45664. this.checkInputs = function () { };
  45665. };
  45666. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45667. var inputs = {};
  45668. for (var cam in this.attached) {
  45669. var input = this.attached[cam];
  45670. var res = BABYLON.SerializationHelper.Serialize(input);
  45671. inputs[input.getClassName()] = res;
  45672. }
  45673. serializedCamera.inputsmgr = inputs;
  45674. };
  45675. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45676. var parsedInputs = parsedCamera.inputsmgr;
  45677. if (parsedInputs) {
  45678. this.clear();
  45679. for (var n in parsedInputs) {
  45680. var construct = BABYLON.CameraInputTypes[n];
  45681. if (construct) {
  45682. var parsedinput = parsedInputs[n];
  45683. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45684. this.add(input);
  45685. }
  45686. }
  45687. }
  45688. else {
  45689. //2016-03-08 this part is for managing backward compatibility
  45690. for (var n in this.attached) {
  45691. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45692. if (construct) {
  45693. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45694. this.remove(this.attached[n]);
  45695. this.add(input);
  45696. }
  45697. }
  45698. }
  45699. };
  45700. return CameraInputsManager;
  45701. }());
  45702. BABYLON.CameraInputsManager = CameraInputsManager;
  45703. })(BABYLON || (BABYLON = {}));
  45704. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45705. "use strict";
  45706. var BABYLON;
  45707. (function (BABYLON) {
  45708. var TargetCamera = /** @class */ (function (_super) {
  45709. __extends(TargetCamera, _super);
  45710. function TargetCamera(name, position, scene) {
  45711. var _this = _super.call(this, name, position, scene) || this;
  45712. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45713. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45714. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45715. _this.speed = 2.0;
  45716. _this.noRotationConstraint = false;
  45717. _this.lockedTarget = null;
  45718. _this._currentTarget = BABYLON.Vector3.Zero();
  45719. _this._viewMatrix = BABYLON.Matrix.Zero();
  45720. _this._camMatrix = BABYLON.Matrix.Zero();
  45721. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45722. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45723. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45724. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45725. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45726. _this._lookAtTemp = BABYLON.Matrix.Zero();
  45727. _this._tempMatrix = BABYLON.Matrix.Zero();
  45728. return _this;
  45729. }
  45730. TargetCamera.prototype.getFrontPosition = function (distance) {
  45731. this.getWorldMatrix();
  45732. var direction = this.getTarget().subtract(this.position);
  45733. direction.normalize();
  45734. direction.scaleInPlace(distance);
  45735. return this.globalPosition.add(direction);
  45736. };
  45737. TargetCamera.prototype._getLockedTargetPosition = function () {
  45738. if (!this.lockedTarget) {
  45739. return null;
  45740. }
  45741. if (this.lockedTarget.absolutePosition) {
  45742. this.lockedTarget.computeWorldMatrix();
  45743. }
  45744. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45745. };
  45746. TargetCamera.prototype.storeState = function () {
  45747. this._storedPosition = this.position.clone();
  45748. this._storedRotation = this.rotation.clone();
  45749. if (this.rotationQuaternion) {
  45750. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45751. }
  45752. return _super.prototype.storeState.call(this);
  45753. };
  45754. /**
  45755. * Restored camera state. You must call storeState() first
  45756. */
  45757. TargetCamera.prototype._restoreStateValues = function () {
  45758. if (!_super.prototype._restoreStateValues.call(this)) {
  45759. return false;
  45760. }
  45761. this.position = this._storedPosition.clone();
  45762. this.rotation = this._storedRotation.clone();
  45763. if (this.rotationQuaternion) {
  45764. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45765. }
  45766. this.cameraDirection.copyFromFloats(0, 0, 0);
  45767. this.cameraRotation.copyFromFloats(0, 0);
  45768. return true;
  45769. };
  45770. // Cache
  45771. TargetCamera.prototype._initCache = function () {
  45772. _super.prototype._initCache.call(this);
  45773. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45774. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45775. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45776. };
  45777. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45778. if (!ignoreParentClass) {
  45779. _super.prototype._updateCache.call(this);
  45780. }
  45781. var lockedTargetPosition = this._getLockedTargetPosition();
  45782. if (!lockedTargetPosition) {
  45783. this._cache.lockedTarget = null;
  45784. }
  45785. else {
  45786. if (!this._cache.lockedTarget) {
  45787. this._cache.lockedTarget = lockedTargetPosition.clone();
  45788. }
  45789. else {
  45790. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45791. }
  45792. }
  45793. this._cache.rotation.copyFrom(this.rotation);
  45794. if (this.rotationQuaternion)
  45795. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45796. };
  45797. // Synchronized
  45798. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45799. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45800. return false;
  45801. }
  45802. var lockedTargetPosition = this._getLockedTargetPosition();
  45803. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45804. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45805. };
  45806. // Methods
  45807. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45808. var engine = this.getEngine();
  45809. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45810. };
  45811. // Target
  45812. TargetCamera.prototype.setTarget = function (target) {
  45813. this.upVector.normalize();
  45814. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45815. this._camMatrix.invert();
  45816. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45817. var vDir = target.subtract(this.position);
  45818. if (vDir.x >= 0.0) {
  45819. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45820. }
  45821. else {
  45822. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45823. }
  45824. this.rotation.z = 0;
  45825. if (isNaN(this.rotation.x)) {
  45826. this.rotation.x = 0;
  45827. }
  45828. if (isNaN(this.rotation.y)) {
  45829. this.rotation.y = 0;
  45830. }
  45831. if (isNaN(this.rotation.z)) {
  45832. this.rotation.z = 0;
  45833. }
  45834. if (this.rotationQuaternion) {
  45835. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45836. }
  45837. };
  45838. /**
  45839. * Return the current target position of the camera. This value is expressed in local space.
  45840. */
  45841. TargetCamera.prototype.getTarget = function () {
  45842. return this._currentTarget;
  45843. };
  45844. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45845. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45846. };
  45847. TargetCamera.prototype._updatePosition = function () {
  45848. if (this.parent) {
  45849. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45850. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45851. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45852. return;
  45853. }
  45854. this.position.addInPlace(this.cameraDirection);
  45855. };
  45856. TargetCamera.prototype._checkInputs = function () {
  45857. var needToMove = this._decideIfNeedsToMove();
  45858. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  45859. // Move
  45860. if (needToMove) {
  45861. this._updatePosition();
  45862. }
  45863. // Rotate
  45864. if (needToRotate) {
  45865. this.rotation.x += this.cameraRotation.x;
  45866. this.rotation.y += this.cameraRotation.y;
  45867. //rotate, if quaternion is set and rotation was used
  45868. if (this.rotationQuaternion) {
  45869. var len = this.rotation.lengthSquared();
  45870. if (len) {
  45871. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45872. }
  45873. }
  45874. if (!this.noRotationConstraint) {
  45875. var limit = (Math.PI / 2) * 0.95;
  45876. if (this.rotation.x > limit)
  45877. this.rotation.x = limit;
  45878. if (this.rotation.x < -limit)
  45879. this.rotation.x = -limit;
  45880. }
  45881. }
  45882. // Inertia
  45883. if (needToMove) {
  45884. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  45885. this.cameraDirection.x = 0;
  45886. }
  45887. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  45888. this.cameraDirection.y = 0;
  45889. }
  45890. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  45891. this.cameraDirection.z = 0;
  45892. }
  45893. this.cameraDirection.scaleInPlace(this.inertia);
  45894. }
  45895. if (needToRotate) {
  45896. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  45897. this.cameraRotation.x = 0;
  45898. }
  45899. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  45900. this.cameraRotation.y = 0;
  45901. }
  45902. this.cameraRotation.scaleInPlace(this.inertia);
  45903. }
  45904. _super.prototype._checkInputs.call(this);
  45905. };
  45906. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  45907. if (this.rotationQuaternion) {
  45908. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  45909. }
  45910. else {
  45911. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  45912. }
  45913. //update the up vector!
  45914. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  45915. };
  45916. TargetCamera.prototype._getViewMatrix = function () {
  45917. if (this.lockedTarget) {
  45918. this.setTarget(this._getLockedTargetPosition());
  45919. }
  45920. // Compute
  45921. this._updateCameraRotationMatrix();
  45922. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  45923. // Computing target and final matrix
  45924. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  45925. if (this.getScene().useRightHandedSystem) {
  45926. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  45927. }
  45928. else {
  45929. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  45930. }
  45931. return this._viewMatrix;
  45932. };
  45933. /**
  45934. * @override
  45935. * Override Camera.createRigCamera
  45936. */
  45937. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45938. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  45939. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  45940. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  45941. if (!this.rotationQuaternion) {
  45942. this.rotationQuaternion = new BABYLON.Quaternion();
  45943. }
  45944. rigCamera._cameraRigParams = {};
  45945. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  45946. }
  45947. return rigCamera;
  45948. }
  45949. return null;
  45950. };
  45951. /**
  45952. * @override
  45953. * Override Camera._updateRigCameras
  45954. */
  45955. TargetCamera.prototype._updateRigCameras = function () {
  45956. var camLeft = this._rigCameras[0];
  45957. var camRight = this._rigCameras[1];
  45958. switch (this.cameraRigMode) {
  45959. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45960. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45961. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45962. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45963. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  45964. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  45965. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  45966. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  45967. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  45968. camLeft.setTarget(this.getTarget());
  45969. camRight.setTarget(this.getTarget());
  45970. break;
  45971. case BABYLON.Camera.RIG_MODE_VR:
  45972. if (camLeft.rotationQuaternion) {
  45973. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45974. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45975. }
  45976. else {
  45977. camLeft.rotation.copyFrom(this.rotation);
  45978. camRight.rotation.copyFrom(this.rotation);
  45979. }
  45980. camLeft.position.copyFrom(this.position);
  45981. camRight.position.copyFrom(this.position);
  45982. break;
  45983. }
  45984. _super.prototype._updateRigCameras.call(this);
  45985. };
  45986. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  45987. if (!this._rigCamTransformMatrix) {
  45988. this._rigCamTransformMatrix = new BABYLON.Matrix();
  45989. }
  45990. var target = this.getTarget();
  45991. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  45992. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  45993. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  45994. };
  45995. TargetCamera.prototype.getClassName = function () {
  45996. return "TargetCamera";
  45997. };
  45998. __decorate([
  45999. BABYLON.serializeAsVector3()
  46000. ], TargetCamera.prototype, "rotation", void 0);
  46001. __decorate([
  46002. BABYLON.serialize()
  46003. ], TargetCamera.prototype, "speed", void 0);
  46004. __decorate([
  46005. BABYLON.serializeAsMeshReference("lockedTargetId")
  46006. ], TargetCamera.prototype, "lockedTarget", void 0);
  46007. return TargetCamera;
  46008. }(BABYLON.Camera));
  46009. BABYLON.TargetCamera = TargetCamera;
  46010. })(BABYLON || (BABYLON = {}));
  46011. //# sourceMappingURL=babylon.targetCamera.js.map
  46012. "use strict";
  46013. var BABYLON;
  46014. (function (BABYLON) {
  46015. var FreeCameraMouseInput = /** @class */ (function () {
  46016. function FreeCameraMouseInput(touchEnabled) {
  46017. if (touchEnabled === void 0) { touchEnabled = true; }
  46018. this.touchEnabled = touchEnabled;
  46019. this.buttons = [0, 1, 2];
  46020. this.angularSensibility = 2000.0;
  46021. this.previousPosition = null;
  46022. }
  46023. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46024. var _this = this;
  46025. var engine = this.camera.getEngine();
  46026. if (!this._pointerInput) {
  46027. this._pointerInput = function (p, s) {
  46028. var evt = p.event;
  46029. if (engine.isInVRExclusivePointerMode) {
  46030. return;
  46031. }
  46032. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46033. return;
  46034. }
  46035. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46036. return;
  46037. }
  46038. var srcElement = (evt.srcElement || evt.target);
  46039. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46040. try {
  46041. srcElement.setPointerCapture(evt.pointerId);
  46042. }
  46043. catch (e) {
  46044. //Nothing to do with the error. Execution will continue.
  46045. }
  46046. _this.previousPosition = {
  46047. x: evt.clientX,
  46048. y: evt.clientY
  46049. };
  46050. if (!noPreventDefault) {
  46051. evt.preventDefault();
  46052. element.focus();
  46053. }
  46054. }
  46055. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46056. try {
  46057. srcElement.releasePointerCapture(evt.pointerId);
  46058. }
  46059. catch (e) {
  46060. //Nothing to do with the error.
  46061. }
  46062. _this.previousPosition = null;
  46063. if (!noPreventDefault) {
  46064. evt.preventDefault();
  46065. }
  46066. }
  46067. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46068. if (!_this.previousPosition || engine.isPointerLock) {
  46069. return;
  46070. }
  46071. var offsetX = evt.clientX - _this.previousPosition.x;
  46072. var offsetY = evt.clientY - _this.previousPosition.y;
  46073. if (_this.camera.getScene().useRightHandedSystem) {
  46074. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46075. }
  46076. else {
  46077. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46078. }
  46079. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46080. _this.previousPosition = {
  46081. x: evt.clientX,
  46082. y: evt.clientY
  46083. };
  46084. if (!noPreventDefault) {
  46085. evt.preventDefault();
  46086. }
  46087. }
  46088. };
  46089. }
  46090. this._onMouseMove = function (evt) {
  46091. if (!engine.isPointerLock) {
  46092. return;
  46093. }
  46094. if (engine.isInVRExclusivePointerMode) {
  46095. return;
  46096. }
  46097. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46098. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46099. if (_this.camera.getScene().useRightHandedSystem) {
  46100. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46101. }
  46102. else {
  46103. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46104. }
  46105. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46106. _this.previousPosition = null;
  46107. if (!noPreventDefault) {
  46108. evt.preventDefault();
  46109. }
  46110. };
  46111. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46112. element.addEventListener("mousemove", this._onMouseMove, false);
  46113. };
  46114. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46115. if (this._observer && element) {
  46116. this.camera.getScene().onPointerObservable.remove(this._observer);
  46117. if (this._onMouseMove) {
  46118. element.removeEventListener("mousemove", this._onMouseMove);
  46119. }
  46120. this._observer = null;
  46121. this._onMouseMove = null;
  46122. this.previousPosition = null;
  46123. }
  46124. };
  46125. FreeCameraMouseInput.prototype.getClassName = function () {
  46126. return "FreeCameraMouseInput";
  46127. };
  46128. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46129. return "mouse";
  46130. };
  46131. __decorate([
  46132. BABYLON.serialize()
  46133. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46134. __decorate([
  46135. BABYLON.serialize()
  46136. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46137. return FreeCameraMouseInput;
  46138. }());
  46139. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46140. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46141. })(BABYLON || (BABYLON = {}));
  46142. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46143. "use strict";
  46144. var BABYLON;
  46145. (function (BABYLON) {
  46146. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46147. function FreeCameraKeyboardMoveInput() {
  46148. this._keys = new Array();
  46149. this.keysUp = [38];
  46150. this.keysDown = [40];
  46151. this.keysLeft = [37];
  46152. this.keysRight = [39];
  46153. }
  46154. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46155. var _this = this;
  46156. if (this._onCanvasBlurObserver) {
  46157. return;
  46158. }
  46159. this._scene = this.camera.getScene();
  46160. this._engine = this._scene.getEngine();
  46161. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46162. _this._keys = [];
  46163. });
  46164. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46165. var evt = info.event;
  46166. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46167. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46168. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46169. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46170. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46171. var index = _this._keys.indexOf(evt.keyCode);
  46172. if (index === -1) {
  46173. _this._keys.push(evt.keyCode);
  46174. }
  46175. if (!noPreventDefault) {
  46176. evt.preventDefault();
  46177. }
  46178. }
  46179. }
  46180. else {
  46181. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46182. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46183. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46184. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46185. var index = _this._keys.indexOf(evt.keyCode);
  46186. if (index >= 0) {
  46187. _this._keys.splice(index, 1);
  46188. }
  46189. if (!noPreventDefault) {
  46190. evt.preventDefault();
  46191. }
  46192. }
  46193. }
  46194. });
  46195. };
  46196. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46197. if (this._scene) {
  46198. if (this._onKeyboardObserver) {
  46199. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46200. }
  46201. if (this._onCanvasBlurObserver) {
  46202. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46203. }
  46204. this._onKeyboardObserver = null;
  46205. this._onCanvasBlurObserver = null;
  46206. }
  46207. this._keys = [];
  46208. };
  46209. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46210. if (this._onKeyboardObserver) {
  46211. var camera = this.camera;
  46212. // Keyboard
  46213. for (var index = 0; index < this._keys.length; index++) {
  46214. var keyCode = this._keys[index];
  46215. var speed = camera._computeLocalCameraSpeed();
  46216. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46217. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46218. }
  46219. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46220. camera._localDirection.copyFromFloats(0, 0, speed);
  46221. }
  46222. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46223. camera._localDirection.copyFromFloats(speed, 0, 0);
  46224. }
  46225. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46226. camera._localDirection.copyFromFloats(0, 0, -speed);
  46227. }
  46228. if (camera.getScene().useRightHandedSystem) {
  46229. camera._localDirection.z *= -1;
  46230. }
  46231. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46232. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46233. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46234. }
  46235. }
  46236. };
  46237. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46238. return "FreeCameraKeyboardMoveInput";
  46239. };
  46240. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46241. this._keys = [];
  46242. };
  46243. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46244. return "keyboard";
  46245. };
  46246. __decorate([
  46247. BABYLON.serialize()
  46248. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46249. __decorate([
  46250. BABYLON.serialize()
  46251. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46252. __decorate([
  46253. BABYLON.serialize()
  46254. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46255. __decorate([
  46256. BABYLON.serialize()
  46257. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46258. return FreeCameraKeyboardMoveInput;
  46259. }());
  46260. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46261. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46262. })(BABYLON || (BABYLON = {}));
  46263. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46264. "use strict";
  46265. var BABYLON;
  46266. (function (BABYLON) {
  46267. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46268. __extends(FreeCameraInputsManager, _super);
  46269. function FreeCameraInputsManager(camera) {
  46270. return _super.call(this, camera) || this;
  46271. }
  46272. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46273. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46274. return this;
  46275. };
  46276. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46277. if (touchEnabled === void 0) { touchEnabled = true; }
  46278. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46279. return this;
  46280. };
  46281. FreeCameraInputsManager.prototype.addGamepad = function () {
  46282. this.add(new BABYLON.FreeCameraGamepadInput());
  46283. return this;
  46284. };
  46285. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46286. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46287. return this;
  46288. };
  46289. FreeCameraInputsManager.prototype.addTouch = function () {
  46290. this.add(new BABYLON.FreeCameraTouchInput());
  46291. return this;
  46292. };
  46293. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46294. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46295. return this;
  46296. };
  46297. return FreeCameraInputsManager;
  46298. }(BABYLON.CameraInputsManager));
  46299. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46300. })(BABYLON || (BABYLON = {}));
  46301. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46302. "use strict";
  46303. var BABYLON;
  46304. (function (BABYLON) {
  46305. var FreeCamera = /** @class */ (function (_super) {
  46306. __extends(FreeCamera, _super);
  46307. function FreeCamera(name, position, scene) {
  46308. var _this = _super.call(this, name, position, scene) || this;
  46309. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46310. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46311. _this.checkCollisions = false;
  46312. _this.applyGravity = false;
  46313. _this._needMoveForGravity = false;
  46314. _this._oldPosition = BABYLON.Vector3.Zero();
  46315. _this._diffPosition = BABYLON.Vector3.Zero();
  46316. _this._newPosition = BABYLON.Vector3.Zero();
  46317. // Collisions
  46318. _this._collisionMask = -1;
  46319. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46320. if (collidedMesh === void 0) { collidedMesh = null; }
  46321. //TODO move this to the collision coordinator!
  46322. if (_this.getScene().workerCollisions)
  46323. newPosition.multiplyInPlace(_this._collider._radius);
  46324. var updatePosition = function (newPos) {
  46325. _this._newPosition.copyFrom(newPos);
  46326. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46327. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46328. _this.position.addInPlace(_this._diffPosition);
  46329. if (_this.onCollide && collidedMesh) {
  46330. _this.onCollide(collidedMesh);
  46331. }
  46332. }
  46333. };
  46334. updatePosition(newPosition);
  46335. };
  46336. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46337. _this.inputs.addKeyboard().addMouse();
  46338. return _this;
  46339. }
  46340. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46341. //-- begin properties for backward compatibility for inputs
  46342. /**
  46343. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46344. * Higher values reduce sensitivity.
  46345. */
  46346. get: function () {
  46347. var mouse = this.inputs.attached["mouse"];
  46348. if (mouse)
  46349. return mouse.angularSensibility;
  46350. return 0;
  46351. },
  46352. /**
  46353. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46354. * Higher values reduce sensitivity.
  46355. */
  46356. set: function (value) {
  46357. var mouse = this.inputs.attached["mouse"];
  46358. if (mouse)
  46359. mouse.angularSensibility = value;
  46360. },
  46361. enumerable: true,
  46362. configurable: true
  46363. });
  46364. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46365. get: function () {
  46366. var keyboard = this.inputs.attached["keyboard"];
  46367. if (keyboard)
  46368. return keyboard.keysUp;
  46369. return [];
  46370. },
  46371. set: function (value) {
  46372. var keyboard = this.inputs.attached["keyboard"];
  46373. if (keyboard)
  46374. keyboard.keysUp = value;
  46375. },
  46376. enumerable: true,
  46377. configurable: true
  46378. });
  46379. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46380. get: function () {
  46381. var keyboard = this.inputs.attached["keyboard"];
  46382. if (keyboard)
  46383. return keyboard.keysDown;
  46384. return [];
  46385. },
  46386. set: function (value) {
  46387. var keyboard = this.inputs.attached["keyboard"];
  46388. if (keyboard)
  46389. keyboard.keysDown = value;
  46390. },
  46391. enumerable: true,
  46392. configurable: true
  46393. });
  46394. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46395. get: function () {
  46396. var keyboard = this.inputs.attached["keyboard"];
  46397. if (keyboard)
  46398. return keyboard.keysLeft;
  46399. return [];
  46400. },
  46401. set: function (value) {
  46402. var keyboard = this.inputs.attached["keyboard"];
  46403. if (keyboard)
  46404. keyboard.keysLeft = value;
  46405. },
  46406. enumerable: true,
  46407. configurable: true
  46408. });
  46409. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46410. get: function () {
  46411. var keyboard = this.inputs.attached["keyboard"];
  46412. if (keyboard)
  46413. return keyboard.keysRight;
  46414. return [];
  46415. },
  46416. set: function (value) {
  46417. var keyboard = this.inputs.attached["keyboard"];
  46418. if (keyboard)
  46419. keyboard.keysRight = value;
  46420. },
  46421. enumerable: true,
  46422. configurable: true
  46423. });
  46424. // Controls
  46425. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46426. this.inputs.attachElement(element, noPreventDefault);
  46427. };
  46428. FreeCamera.prototype.detachControl = function (element) {
  46429. this.inputs.detachElement(element);
  46430. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46431. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46432. };
  46433. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46434. get: function () {
  46435. return this._collisionMask;
  46436. },
  46437. set: function (mask) {
  46438. this._collisionMask = !isNaN(mask) ? mask : -1;
  46439. },
  46440. enumerable: true,
  46441. configurable: true
  46442. });
  46443. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46444. var globalPosition;
  46445. if (this.parent) {
  46446. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46447. }
  46448. else {
  46449. globalPosition = this.position;
  46450. }
  46451. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46452. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46453. if (!this._collider) {
  46454. this._collider = new BABYLON.Collider();
  46455. }
  46456. this._collider._radius = this.ellipsoid;
  46457. this._collider.collisionMask = this._collisionMask;
  46458. //no need for clone, as long as gravity is not on.
  46459. var actualDisplacement = displacement;
  46460. //add gravity to the direction to prevent the dual-collision checking
  46461. if (this.applyGravity) {
  46462. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46463. actualDisplacement = displacement.add(this.getScene().gravity);
  46464. }
  46465. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46466. };
  46467. FreeCamera.prototype._checkInputs = function () {
  46468. if (!this._localDirection) {
  46469. this._localDirection = BABYLON.Vector3.Zero();
  46470. this._transformedDirection = BABYLON.Vector3.Zero();
  46471. }
  46472. this.inputs.checkInputs();
  46473. _super.prototype._checkInputs.call(this);
  46474. };
  46475. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46476. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46477. };
  46478. FreeCamera.prototype._updatePosition = function () {
  46479. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46480. this._collideWithWorld(this.cameraDirection);
  46481. }
  46482. else {
  46483. _super.prototype._updatePosition.call(this);
  46484. }
  46485. };
  46486. FreeCamera.prototype.dispose = function () {
  46487. this.inputs.clear();
  46488. _super.prototype.dispose.call(this);
  46489. };
  46490. FreeCamera.prototype.getClassName = function () {
  46491. return "FreeCamera";
  46492. };
  46493. __decorate([
  46494. BABYLON.serializeAsVector3()
  46495. ], FreeCamera.prototype, "ellipsoid", void 0);
  46496. __decorate([
  46497. BABYLON.serializeAsVector3()
  46498. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46499. __decorate([
  46500. BABYLON.serialize()
  46501. ], FreeCamera.prototype, "checkCollisions", void 0);
  46502. __decorate([
  46503. BABYLON.serialize()
  46504. ], FreeCamera.prototype, "applyGravity", void 0);
  46505. return FreeCamera;
  46506. }(BABYLON.TargetCamera));
  46507. BABYLON.FreeCamera = FreeCamera;
  46508. })(BABYLON || (BABYLON = {}));
  46509. //# sourceMappingURL=babylon.freeCamera.js.map
  46510. "use strict";
  46511. var BABYLON;
  46512. (function (BABYLON) {
  46513. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46514. function ArcRotateCameraKeyboardMoveInput() {
  46515. this._keys = new Array();
  46516. this.keysUp = [38];
  46517. this.keysDown = [40];
  46518. this.keysLeft = [37];
  46519. this.keysRight = [39];
  46520. this.keysReset = [220];
  46521. this.panningSensibility = 50.0;
  46522. this.zoomingSensibility = 25.0;
  46523. this.useAltToZoom = true;
  46524. }
  46525. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46526. var _this = this;
  46527. if (this._onCanvasBlurObserver) {
  46528. return;
  46529. }
  46530. this._scene = this.camera.getScene();
  46531. this._engine = this._scene.getEngine();
  46532. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46533. _this._keys = [];
  46534. });
  46535. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46536. var evt = info.event;
  46537. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46538. _this._ctrlPressed = evt.ctrlKey;
  46539. _this._altPressed = evt.altKey;
  46540. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46541. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46542. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46543. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46544. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46545. var index = _this._keys.indexOf(evt.keyCode);
  46546. if (index === -1) {
  46547. _this._keys.push(evt.keyCode);
  46548. }
  46549. if (evt.preventDefault) {
  46550. if (!noPreventDefault) {
  46551. evt.preventDefault();
  46552. }
  46553. }
  46554. }
  46555. }
  46556. else {
  46557. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46558. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46559. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46560. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46561. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46562. var index = _this._keys.indexOf(evt.keyCode);
  46563. if (index >= 0) {
  46564. _this._keys.splice(index, 1);
  46565. }
  46566. if (evt.preventDefault) {
  46567. if (!noPreventDefault) {
  46568. evt.preventDefault();
  46569. }
  46570. }
  46571. }
  46572. }
  46573. });
  46574. };
  46575. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46576. if (this._scene) {
  46577. if (this._onKeyboardObserver) {
  46578. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46579. }
  46580. if (this._onCanvasBlurObserver) {
  46581. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46582. }
  46583. this._onKeyboardObserver = null;
  46584. this._onCanvasBlurObserver = null;
  46585. }
  46586. this._keys = [];
  46587. };
  46588. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46589. if (this._onKeyboardObserver) {
  46590. var camera = this.camera;
  46591. for (var index = 0; index < this._keys.length; index++) {
  46592. var keyCode = this._keys[index];
  46593. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46594. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46595. camera.inertialPanningX -= 1 / this.panningSensibility;
  46596. }
  46597. else {
  46598. camera.inertialAlphaOffset -= 0.01;
  46599. }
  46600. }
  46601. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46602. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46603. camera.inertialPanningY += 1 / this.panningSensibility;
  46604. }
  46605. else if (this._altPressed && this.useAltToZoom) {
  46606. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46607. }
  46608. else {
  46609. camera.inertialBetaOffset -= 0.01;
  46610. }
  46611. }
  46612. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46613. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46614. camera.inertialPanningX += 1 / this.panningSensibility;
  46615. }
  46616. else {
  46617. camera.inertialAlphaOffset += 0.01;
  46618. }
  46619. }
  46620. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46621. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46622. camera.inertialPanningY -= 1 / this.panningSensibility;
  46623. }
  46624. else if (this._altPressed && this.useAltToZoom) {
  46625. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46626. }
  46627. else {
  46628. camera.inertialBetaOffset += 0.01;
  46629. }
  46630. }
  46631. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46632. camera.restoreState();
  46633. }
  46634. }
  46635. }
  46636. };
  46637. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46638. return "ArcRotateCameraKeyboardMoveInput";
  46639. };
  46640. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46641. return "keyboard";
  46642. };
  46643. __decorate([
  46644. BABYLON.serialize()
  46645. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46646. __decorate([
  46647. BABYLON.serialize()
  46648. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46649. __decorate([
  46650. BABYLON.serialize()
  46651. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46652. __decorate([
  46653. BABYLON.serialize()
  46654. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46655. __decorate([
  46656. BABYLON.serialize()
  46657. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46658. __decorate([
  46659. BABYLON.serialize()
  46660. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46661. __decorate([
  46662. BABYLON.serialize()
  46663. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46664. __decorate([
  46665. BABYLON.serialize()
  46666. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46667. return ArcRotateCameraKeyboardMoveInput;
  46668. }());
  46669. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46670. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46671. })(BABYLON || (BABYLON = {}));
  46672. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46673. "use strict";
  46674. var BABYLON;
  46675. (function (BABYLON) {
  46676. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46677. function ArcRotateCameraMouseWheelInput() {
  46678. this.wheelPrecision = 3.0;
  46679. /**
  46680. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46681. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46682. */
  46683. this.wheelDeltaPercentage = 0;
  46684. }
  46685. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46686. var _this = this;
  46687. this._wheel = function (p, s) {
  46688. //sanity check - this should be a PointerWheel event.
  46689. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46690. return;
  46691. var event = p.event;
  46692. var delta = 0;
  46693. if (event.wheelDelta) {
  46694. if (_this.wheelDeltaPercentage) {
  46695. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46696. if (event.wheelDelta > 0) {
  46697. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46698. }
  46699. else {
  46700. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46701. }
  46702. }
  46703. else {
  46704. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46705. }
  46706. }
  46707. else if (event.detail) {
  46708. delta = -event.detail / _this.wheelPrecision;
  46709. }
  46710. if (delta)
  46711. _this.camera.inertialRadiusOffset += delta;
  46712. if (event.preventDefault) {
  46713. if (!noPreventDefault) {
  46714. event.preventDefault();
  46715. }
  46716. }
  46717. };
  46718. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46719. };
  46720. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46721. if (this._observer && element) {
  46722. this.camera.getScene().onPointerObservable.remove(this._observer);
  46723. this._observer = null;
  46724. this._wheel = null;
  46725. }
  46726. };
  46727. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46728. return "ArcRotateCameraMouseWheelInput";
  46729. };
  46730. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46731. return "mousewheel";
  46732. };
  46733. __decorate([
  46734. BABYLON.serialize()
  46735. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46736. __decorate([
  46737. BABYLON.serialize()
  46738. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46739. return ArcRotateCameraMouseWheelInput;
  46740. }());
  46741. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46742. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46743. })(BABYLON || (BABYLON = {}));
  46744. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46745. "use strict";
  46746. var BABYLON;
  46747. (function (BABYLON) {
  46748. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46749. function ArcRotateCameraPointersInput() {
  46750. this.buttons = [0, 1, 2];
  46751. this.angularSensibilityX = 1000.0;
  46752. this.angularSensibilityY = 1000.0;
  46753. this.pinchPrecision = 12.0;
  46754. /**
  46755. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46756. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46757. */
  46758. this.pinchDeltaPercentage = 0;
  46759. this.panningSensibility = 1000.0;
  46760. this.multiTouchPanning = true;
  46761. this.multiTouchPanAndZoom = true;
  46762. this._isPanClick = false;
  46763. this.pinchInwards = true;
  46764. }
  46765. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46766. var _this = this;
  46767. var engine = this.camera.getEngine();
  46768. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46769. var pointA = null;
  46770. var pointB = null;
  46771. var previousPinchSquaredDistance = 0;
  46772. var initialDistance = 0;
  46773. var twoFingerActivityCount = 0;
  46774. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46775. this._pointerInput = function (p, s) {
  46776. var evt = p.event;
  46777. var isTouch = p.event.pointerType === "touch";
  46778. if (engine.isInVRExclusivePointerMode) {
  46779. return;
  46780. }
  46781. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46782. return;
  46783. }
  46784. var srcElement = (evt.srcElement || evt.target);
  46785. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46786. try {
  46787. srcElement.setPointerCapture(evt.pointerId);
  46788. }
  46789. catch (e) {
  46790. //Nothing to do with the error. Execution will continue.
  46791. }
  46792. // Manage panning with pan button click
  46793. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46794. // manage pointers
  46795. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46796. if (pointA === null) {
  46797. pointA = cacheSoloPointer;
  46798. }
  46799. else if (pointB === null) {
  46800. pointB = cacheSoloPointer;
  46801. }
  46802. if (!noPreventDefault) {
  46803. evt.preventDefault();
  46804. element.focus();
  46805. }
  46806. }
  46807. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46808. _this.camera.restoreState();
  46809. }
  46810. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46811. try {
  46812. srcElement.releasePointerCapture(evt.pointerId);
  46813. }
  46814. catch (e) {
  46815. //Nothing to do with the error.
  46816. }
  46817. cacheSoloPointer = null;
  46818. previousPinchSquaredDistance = 0;
  46819. previousMultiTouchPanPosition.isPaning = false;
  46820. previousMultiTouchPanPosition.isPinching = false;
  46821. twoFingerActivityCount = 0;
  46822. initialDistance = 0;
  46823. if (!isTouch) {
  46824. pointB = null; // Mouse and pen are mono pointer
  46825. }
  46826. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46827. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46828. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46829. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46830. if (engine._badOS) {
  46831. pointA = pointB = null;
  46832. }
  46833. else {
  46834. //only remove the impacted pointer in case of multitouch allowing on most
  46835. //platforms switching from rotate to zoom and pan seamlessly.
  46836. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46837. pointA = pointB;
  46838. pointB = null;
  46839. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46840. }
  46841. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46842. pointB = null;
  46843. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46844. }
  46845. else {
  46846. pointA = pointB = null;
  46847. }
  46848. }
  46849. if (!noPreventDefault) {
  46850. evt.preventDefault();
  46851. }
  46852. }
  46853. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46854. if (!noPreventDefault) {
  46855. evt.preventDefault();
  46856. }
  46857. // One button down
  46858. if (pointA && pointB === null && cacheSoloPointer) {
  46859. if (_this.panningSensibility !== 0 &&
  46860. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  46861. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  46862. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  46863. }
  46864. else {
  46865. var offsetX = evt.clientX - cacheSoloPointer.x;
  46866. var offsetY = evt.clientY - cacheSoloPointer.y;
  46867. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46868. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46869. }
  46870. cacheSoloPointer.x = evt.clientX;
  46871. cacheSoloPointer.y = evt.clientY;
  46872. }
  46873. else if (pointA && pointB) {
  46874. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  46875. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  46876. ed.x = evt.clientX;
  46877. ed.y = evt.clientY;
  46878. var direction = _this.pinchInwards ? 1 : -1;
  46879. var distX = pointA.x - pointB.x;
  46880. var distY = pointA.y - pointB.y;
  46881. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  46882. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  46883. if (previousPinchSquaredDistance === 0) {
  46884. initialDistance = pinchDistance;
  46885. previousPinchSquaredDistance = pinchSquaredDistance;
  46886. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  46887. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  46888. return;
  46889. }
  46890. if (_this.multiTouchPanAndZoom) {
  46891. if (_this.pinchDeltaPercentage) {
  46892. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46893. }
  46894. else {
  46895. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46896. (_this.pinchPrecision *
  46897. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46898. direction);
  46899. }
  46900. if (_this.panningSensibility !== 0) {
  46901. var pointersCenterX = (pointA.x + pointB.x) / 2;
  46902. var pointersCenterY = (pointA.y + pointB.y) / 2;
  46903. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  46904. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  46905. previousMultiTouchPanPosition.x = pointersCenterX;
  46906. previousMultiTouchPanPosition.y = pointersCenterY;
  46907. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  46908. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  46909. }
  46910. }
  46911. else {
  46912. twoFingerActivityCount++;
  46913. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  46914. if (_this.pinchDeltaPercentage) {
  46915. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46916. }
  46917. else {
  46918. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46919. (_this.pinchPrecision *
  46920. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46921. direction);
  46922. }
  46923. previousMultiTouchPanPosition.isPaning = false;
  46924. previousMultiTouchPanPosition.isPinching = true;
  46925. }
  46926. else {
  46927. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  46928. if (!previousMultiTouchPanPosition.isPaning) {
  46929. previousMultiTouchPanPosition.isPaning = true;
  46930. previousMultiTouchPanPosition.isPinching = false;
  46931. previousMultiTouchPanPosition.x = ed.x;
  46932. previousMultiTouchPanPosition.y = ed.y;
  46933. return;
  46934. }
  46935. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  46936. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  46937. }
  46938. }
  46939. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  46940. previousMultiTouchPanPosition.x = ed.x;
  46941. previousMultiTouchPanPosition.y = ed.y;
  46942. }
  46943. }
  46944. previousPinchSquaredDistance = pinchSquaredDistance;
  46945. }
  46946. }
  46947. };
  46948. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  46949. this._onContextMenu = function (evt) {
  46950. evt.preventDefault();
  46951. };
  46952. if (!this.camera._useCtrlForPanning) {
  46953. element.addEventListener("contextmenu", this._onContextMenu, false);
  46954. }
  46955. this._onLostFocus = function () {
  46956. //this._keys = [];
  46957. pointA = pointB = null;
  46958. previousPinchSquaredDistance = 0;
  46959. previousMultiTouchPanPosition.isPaning = false;
  46960. previousMultiTouchPanPosition.isPinching = false;
  46961. twoFingerActivityCount = 0;
  46962. cacheSoloPointer = null;
  46963. initialDistance = 0;
  46964. };
  46965. this._onMouseMove = function (evt) {
  46966. if (!engine.isPointerLock) {
  46967. return;
  46968. }
  46969. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46970. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46971. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46972. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46973. if (!noPreventDefault) {
  46974. evt.preventDefault();
  46975. }
  46976. };
  46977. this._onGestureStart = function (e) {
  46978. if (window.MSGesture === undefined) {
  46979. return;
  46980. }
  46981. if (!_this._MSGestureHandler) {
  46982. _this._MSGestureHandler = new MSGesture();
  46983. _this._MSGestureHandler.target = element;
  46984. }
  46985. _this._MSGestureHandler.addPointer(e.pointerId);
  46986. };
  46987. this._onGesture = function (e) {
  46988. _this.camera.radius *= e.scale;
  46989. if (e.preventDefault) {
  46990. if (!noPreventDefault) {
  46991. e.stopPropagation();
  46992. e.preventDefault();
  46993. }
  46994. }
  46995. };
  46996. element.addEventListener("mousemove", this._onMouseMove, false);
  46997. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  46998. element.addEventListener("MSGestureChange", this._onGesture, false);
  46999. BABYLON.Tools.RegisterTopRootEvents([
  47000. { name: "blur", handler: this._onLostFocus }
  47001. ]);
  47002. };
  47003. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47004. if (this._onLostFocus) {
  47005. BABYLON.Tools.UnregisterTopRootEvents([
  47006. { name: "blur", handler: this._onLostFocus }
  47007. ]);
  47008. }
  47009. if (element && this._observer) {
  47010. this.camera.getScene().onPointerObservable.remove(this._observer);
  47011. this._observer = null;
  47012. if (this._onContextMenu) {
  47013. element.removeEventListener("contextmenu", this._onContextMenu);
  47014. }
  47015. if (this._onMouseMove) {
  47016. element.removeEventListener("mousemove", this._onMouseMove);
  47017. }
  47018. if (this._onGestureStart) {
  47019. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47020. }
  47021. if (this._onGesture) {
  47022. element.removeEventListener("MSGestureChange", this._onGesture);
  47023. }
  47024. this._isPanClick = false;
  47025. this.pinchInwards = true;
  47026. this._onMouseMove = null;
  47027. this._onGestureStart = null;
  47028. this._onGesture = null;
  47029. this._MSGestureHandler = null;
  47030. this._onLostFocus = null;
  47031. this._onContextMenu = null;
  47032. }
  47033. };
  47034. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47035. return "ArcRotateCameraPointersInput";
  47036. };
  47037. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47038. return "pointers";
  47039. };
  47040. __decorate([
  47041. BABYLON.serialize()
  47042. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47043. __decorate([
  47044. BABYLON.serialize()
  47045. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47046. __decorate([
  47047. BABYLON.serialize()
  47048. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47049. __decorate([
  47050. BABYLON.serialize()
  47051. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47052. __decorate([
  47053. BABYLON.serialize()
  47054. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47055. __decorate([
  47056. BABYLON.serialize()
  47057. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47058. __decorate([
  47059. BABYLON.serialize()
  47060. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47061. __decorate([
  47062. BABYLON.serialize()
  47063. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47064. return ArcRotateCameraPointersInput;
  47065. }());
  47066. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47067. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47068. })(BABYLON || (BABYLON = {}));
  47069. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47070. "use strict";
  47071. var BABYLON;
  47072. (function (BABYLON) {
  47073. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47074. __extends(ArcRotateCameraInputsManager, _super);
  47075. function ArcRotateCameraInputsManager(camera) {
  47076. return _super.call(this, camera) || this;
  47077. }
  47078. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47079. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47080. return this;
  47081. };
  47082. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47083. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47084. return this;
  47085. };
  47086. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47087. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47088. return this;
  47089. };
  47090. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47091. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47092. return this;
  47093. };
  47094. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47095. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47096. return this;
  47097. };
  47098. return ArcRotateCameraInputsManager;
  47099. }(BABYLON.CameraInputsManager));
  47100. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47101. })(BABYLON || (BABYLON = {}));
  47102. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47103. "use strict";
  47104. var BABYLON;
  47105. (function (BABYLON) {
  47106. var ArcRotateCamera = /** @class */ (function (_super) {
  47107. __extends(ArcRotateCamera, _super);
  47108. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47109. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47110. _this.inertialAlphaOffset = 0;
  47111. _this.inertialBetaOffset = 0;
  47112. _this.inertialRadiusOffset = 0;
  47113. _this.lowerAlphaLimit = null;
  47114. _this.upperAlphaLimit = null;
  47115. _this.lowerBetaLimit = 0.01;
  47116. _this.upperBetaLimit = Math.PI;
  47117. _this.lowerRadiusLimit = null;
  47118. _this.upperRadiusLimit = null;
  47119. _this.inertialPanningX = 0;
  47120. _this.inertialPanningY = 0;
  47121. _this.pinchToPanMaxDistance = 20;
  47122. _this.panningDistanceLimit = null;
  47123. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47124. _this.panningInertia = 0.9;
  47125. //-- end properties for backward compatibility for inputs
  47126. _this.zoomOnFactor = 1;
  47127. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47128. _this.allowUpsideDown = true;
  47129. _this._viewMatrix = new BABYLON.Matrix();
  47130. // Panning
  47131. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47132. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47133. _this.checkCollisions = false;
  47134. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47135. _this._previousPosition = BABYLON.Vector3.Zero();
  47136. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47137. _this._newPosition = BABYLON.Vector3.Zero();
  47138. _this._computationVector = BABYLON.Vector3.Zero();
  47139. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47140. if (collidedMesh === void 0) { collidedMesh = null; }
  47141. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47142. newPosition.multiplyInPlace(_this._collider._radius);
  47143. }
  47144. if (!collidedMesh) {
  47145. _this._previousPosition.copyFrom(_this.position);
  47146. }
  47147. else {
  47148. _this.setPosition(newPosition);
  47149. if (_this.onCollide) {
  47150. _this.onCollide(collidedMesh);
  47151. }
  47152. }
  47153. // Recompute because of constraints
  47154. var cosa = Math.cos(_this.alpha);
  47155. var sina = Math.sin(_this.alpha);
  47156. var cosb = Math.cos(_this.beta);
  47157. var sinb = Math.sin(_this.beta);
  47158. if (sinb === 0) {
  47159. sinb = 0.0001;
  47160. }
  47161. var target = _this._getTargetPosition();
  47162. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47163. target.addToRef(_this._computationVector, _this._newPosition);
  47164. _this.position.copyFrom(_this._newPosition);
  47165. var up = _this.upVector;
  47166. if (_this.allowUpsideDown && _this.beta < 0) {
  47167. up = up.clone();
  47168. up = up.negate();
  47169. }
  47170. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47171. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47172. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47173. _this._collisionTriggered = false;
  47174. };
  47175. _this._target = BABYLON.Vector3.Zero();
  47176. if (target) {
  47177. _this.setTarget(target);
  47178. }
  47179. _this.alpha = alpha;
  47180. _this.beta = beta;
  47181. _this.radius = radius;
  47182. _this.getViewMatrix();
  47183. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47184. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47185. return _this;
  47186. }
  47187. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47188. get: function () {
  47189. return this._target;
  47190. },
  47191. set: function (value) {
  47192. this.setTarget(value);
  47193. },
  47194. enumerable: true,
  47195. configurable: true
  47196. });
  47197. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47198. //-- begin properties for backward compatibility for inputs
  47199. get: function () {
  47200. var pointers = this.inputs.attached["pointers"];
  47201. if (pointers)
  47202. return pointers.angularSensibilityX;
  47203. return 0;
  47204. },
  47205. set: function (value) {
  47206. var pointers = this.inputs.attached["pointers"];
  47207. if (pointers) {
  47208. pointers.angularSensibilityX = value;
  47209. }
  47210. },
  47211. enumerable: true,
  47212. configurable: true
  47213. });
  47214. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47215. get: function () {
  47216. var pointers = this.inputs.attached["pointers"];
  47217. if (pointers)
  47218. return pointers.angularSensibilityY;
  47219. return 0;
  47220. },
  47221. set: function (value) {
  47222. var pointers = this.inputs.attached["pointers"];
  47223. if (pointers) {
  47224. pointers.angularSensibilityY = value;
  47225. }
  47226. },
  47227. enumerable: true,
  47228. configurable: true
  47229. });
  47230. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47231. get: function () {
  47232. var pointers = this.inputs.attached["pointers"];
  47233. if (pointers)
  47234. return pointers.pinchPrecision;
  47235. return 0;
  47236. },
  47237. set: function (value) {
  47238. var pointers = this.inputs.attached["pointers"];
  47239. if (pointers) {
  47240. pointers.pinchPrecision = value;
  47241. }
  47242. },
  47243. enumerable: true,
  47244. configurable: true
  47245. });
  47246. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47247. get: function () {
  47248. var pointers = this.inputs.attached["pointers"];
  47249. if (pointers)
  47250. return pointers.pinchDeltaPercentage;
  47251. return 0;
  47252. },
  47253. set: function (value) {
  47254. var pointers = this.inputs.attached["pointers"];
  47255. if (pointers) {
  47256. pointers.pinchDeltaPercentage = value;
  47257. }
  47258. },
  47259. enumerable: true,
  47260. configurable: true
  47261. });
  47262. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47263. get: function () {
  47264. var pointers = this.inputs.attached["pointers"];
  47265. if (pointers)
  47266. return pointers.panningSensibility;
  47267. return 0;
  47268. },
  47269. set: function (value) {
  47270. var pointers = this.inputs.attached["pointers"];
  47271. if (pointers) {
  47272. pointers.panningSensibility = value;
  47273. }
  47274. },
  47275. enumerable: true,
  47276. configurable: true
  47277. });
  47278. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47279. get: function () {
  47280. var keyboard = this.inputs.attached["keyboard"];
  47281. if (keyboard)
  47282. return keyboard.keysUp;
  47283. return [];
  47284. },
  47285. set: function (value) {
  47286. var keyboard = this.inputs.attached["keyboard"];
  47287. if (keyboard)
  47288. keyboard.keysUp = value;
  47289. },
  47290. enumerable: true,
  47291. configurable: true
  47292. });
  47293. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47294. get: function () {
  47295. var keyboard = this.inputs.attached["keyboard"];
  47296. if (keyboard)
  47297. return keyboard.keysDown;
  47298. return [];
  47299. },
  47300. set: function (value) {
  47301. var keyboard = this.inputs.attached["keyboard"];
  47302. if (keyboard)
  47303. keyboard.keysDown = value;
  47304. },
  47305. enumerable: true,
  47306. configurable: true
  47307. });
  47308. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47309. get: function () {
  47310. var keyboard = this.inputs.attached["keyboard"];
  47311. if (keyboard)
  47312. return keyboard.keysLeft;
  47313. return [];
  47314. },
  47315. set: function (value) {
  47316. var keyboard = this.inputs.attached["keyboard"];
  47317. if (keyboard)
  47318. keyboard.keysLeft = value;
  47319. },
  47320. enumerable: true,
  47321. configurable: true
  47322. });
  47323. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47324. get: function () {
  47325. var keyboard = this.inputs.attached["keyboard"];
  47326. if (keyboard)
  47327. return keyboard.keysRight;
  47328. return [];
  47329. },
  47330. set: function (value) {
  47331. var keyboard = this.inputs.attached["keyboard"];
  47332. if (keyboard)
  47333. keyboard.keysRight = value;
  47334. },
  47335. enumerable: true,
  47336. configurable: true
  47337. });
  47338. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47339. get: function () {
  47340. var mousewheel = this.inputs.attached["mousewheel"];
  47341. if (mousewheel)
  47342. return mousewheel.wheelPrecision;
  47343. return 0;
  47344. },
  47345. set: function (value) {
  47346. var mousewheel = this.inputs.attached["mousewheel"];
  47347. if (mousewheel)
  47348. mousewheel.wheelPrecision = value;
  47349. },
  47350. enumerable: true,
  47351. configurable: true
  47352. });
  47353. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47354. get: function () {
  47355. var mousewheel = this.inputs.attached["mousewheel"];
  47356. if (mousewheel)
  47357. return mousewheel.wheelDeltaPercentage;
  47358. return 0;
  47359. },
  47360. set: function (value) {
  47361. var mousewheel = this.inputs.attached["mousewheel"];
  47362. if (mousewheel)
  47363. mousewheel.wheelDeltaPercentage = value;
  47364. },
  47365. enumerable: true,
  47366. configurable: true
  47367. });
  47368. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47369. get: function () {
  47370. return this._bouncingBehavior;
  47371. },
  47372. enumerable: true,
  47373. configurable: true
  47374. });
  47375. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47376. get: function () {
  47377. return this._bouncingBehavior != null;
  47378. },
  47379. set: function (value) {
  47380. if (value === this.useBouncingBehavior) {
  47381. return;
  47382. }
  47383. if (value) {
  47384. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47385. this.addBehavior(this._bouncingBehavior);
  47386. }
  47387. else if (this._bouncingBehavior) {
  47388. this.removeBehavior(this._bouncingBehavior);
  47389. this._bouncingBehavior = null;
  47390. }
  47391. },
  47392. enumerable: true,
  47393. configurable: true
  47394. });
  47395. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47396. get: function () {
  47397. return this._framingBehavior;
  47398. },
  47399. enumerable: true,
  47400. configurable: true
  47401. });
  47402. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47403. get: function () {
  47404. return this._framingBehavior != null;
  47405. },
  47406. set: function (value) {
  47407. if (value === this.useFramingBehavior) {
  47408. return;
  47409. }
  47410. if (value) {
  47411. this._framingBehavior = new BABYLON.FramingBehavior();
  47412. this.addBehavior(this._framingBehavior);
  47413. }
  47414. else if (this._framingBehavior) {
  47415. this.removeBehavior(this._framingBehavior);
  47416. this._framingBehavior = null;
  47417. }
  47418. },
  47419. enumerable: true,
  47420. configurable: true
  47421. });
  47422. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47423. get: function () {
  47424. return this._autoRotationBehavior;
  47425. },
  47426. enumerable: true,
  47427. configurable: true
  47428. });
  47429. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47430. get: function () {
  47431. return this._autoRotationBehavior != null;
  47432. },
  47433. set: function (value) {
  47434. if (value === this.useAutoRotationBehavior) {
  47435. return;
  47436. }
  47437. if (value) {
  47438. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47439. this.addBehavior(this._autoRotationBehavior);
  47440. }
  47441. else if (this._autoRotationBehavior) {
  47442. this.removeBehavior(this._autoRotationBehavior);
  47443. this._autoRotationBehavior = null;
  47444. }
  47445. },
  47446. enumerable: true,
  47447. configurable: true
  47448. });
  47449. // Cache
  47450. ArcRotateCamera.prototype._initCache = function () {
  47451. _super.prototype._initCache.call(this);
  47452. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47453. this._cache.alpha = undefined;
  47454. this._cache.beta = undefined;
  47455. this._cache.radius = undefined;
  47456. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47457. };
  47458. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47459. if (!ignoreParentClass) {
  47460. _super.prototype._updateCache.call(this);
  47461. }
  47462. this._cache._target.copyFrom(this._getTargetPosition());
  47463. this._cache.alpha = this.alpha;
  47464. this._cache.beta = this.beta;
  47465. this._cache.radius = this.radius;
  47466. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47467. };
  47468. ArcRotateCamera.prototype._getTargetPosition = function () {
  47469. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47470. var pos = this._targetHost.getAbsolutePosition();
  47471. if (this._targetBoundingCenter) {
  47472. pos.addToRef(this._targetBoundingCenter, this._target);
  47473. }
  47474. else {
  47475. this._target.copyFrom(pos);
  47476. }
  47477. }
  47478. var lockedTargetPosition = this._getLockedTargetPosition();
  47479. if (lockedTargetPosition) {
  47480. return lockedTargetPosition;
  47481. }
  47482. return this._target;
  47483. };
  47484. ArcRotateCamera.prototype.storeState = function () {
  47485. this._storedAlpha = this.alpha;
  47486. this._storedBeta = this.beta;
  47487. this._storedRadius = this.radius;
  47488. this._storedTarget = this._getTargetPosition().clone();
  47489. return _super.prototype.storeState.call(this);
  47490. };
  47491. /**
  47492. * Restored camera state. You must call storeState() first
  47493. */
  47494. ArcRotateCamera.prototype._restoreStateValues = function () {
  47495. if (!_super.prototype._restoreStateValues.call(this)) {
  47496. return false;
  47497. }
  47498. this.alpha = this._storedAlpha;
  47499. this.beta = this._storedBeta;
  47500. this.radius = this._storedRadius;
  47501. this.setTarget(this._storedTarget.clone());
  47502. this.inertialAlphaOffset = 0;
  47503. this.inertialBetaOffset = 0;
  47504. this.inertialRadiusOffset = 0;
  47505. this.inertialPanningX = 0;
  47506. this.inertialPanningY = 0;
  47507. return true;
  47508. };
  47509. // Synchronized
  47510. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47511. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47512. return false;
  47513. return this._cache._target.equals(this._getTargetPosition())
  47514. && this._cache.alpha === this.alpha
  47515. && this._cache.beta === this.beta
  47516. && this._cache.radius === this.radius
  47517. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47518. };
  47519. // Methods
  47520. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47521. var _this = this;
  47522. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47523. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47524. this._useCtrlForPanning = useCtrlForPanning;
  47525. this._panningMouseButton = panningMouseButton;
  47526. this.inputs.attachElement(element, noPreventDefault);
  47527. this._reset = function () {
  47528. _this.inertialAlphaOffset = 0;
  47529. _this.inertialBetaOffset = 0;
  47530. _this.inertialRadiusOffset = 0;
  47531. _this.inertialPanningX = 0;
  47532. _this.inertialPanningY = 0;
  47533. };
  47534. };
  47535. ArcRotateCamera.prototype.detachControl = function (element) {
  47536. this.inputs.detachElement(element);
  47537. if (this._reset) {
  47538. this._reset();
  47539. }
  47540. };
  47541. ArcRotateCamera.prototype._checkInputs = function () {
  47542. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47543. if (this._collisionTriggered) {
  47544. return;
  47545. }
  47546. this.inputs.checkInputs();
  47547. // Inertia
  47548. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47549. if (this.getScene().useRightHandedSystem) {
  47550. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47551. }
  47552. else {
  47553. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47554. }
  47555. this.beta += this.inertialBetaOffset;
  47556. this.radius -= this.inertialRadiusOffset;
  47557. this.inertialAlphaOffset *= this.inertia;
  47558. this.inertialBetaOffset *= this.inertia;
  47559. this.inertialRadiusOffset *= this.inertia;
  47560. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47561. this.inertialAlphaOffset = 0;
  47562. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47563. this.inertialBetaOffset = 0;
  47564. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47565. this.inertialRadiusOffset = 0;
  47566. }
  47567. // Panning inertia
  47568. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47569. if (!this._localDirection) {
  47570. this._localDirection = BABYLON.Vector3.Zero();
  47571. this._transformedDirection = BABYLON.Vector3.Zero();
  47572. }
  47573. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47574. this._localDirection.multiplyInPlace(this.panningAxis);
  47575. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47576. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47577. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47578. if (!this.panningAxis.y) {
  47579. this._transformedDirection.y = 0;
  47580. }
  47581. if (!this._targetHost) {
  47582. if (this.panningDistanceLimit) {
  47583. this._transformedDirection.addInPlace(this._target);
  47584. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47585. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47586. this._target.copyFrom(this._transformedDirection);
  47587. }
  47588. }
  47589. else {
  47590. this._target.addInPlace(this._transformedDirection);
  47591. }
  47592. }
  47593. this.inertialPanningX *= this.panningInertia;
  47594. this.inertialPanningY *= this.panningInertia;
  47595. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47596. this.inertialPanningX = 0;
  47597. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47598. this.inertialPanningY = 0;
  47599. }
  47600. // Limits
  47601. this._checkLimits();
  47602. _super.prototype._checkInputs.call(this);
  47603. };
  47604. ArcRotateCamera.prototype._checkLimits = function () {
  47605. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47606. if (this.allowUpsideDown && this.beta > Math.PI) {
  47607. this.beta = this.beta - (2 * Math.PI);
  47608. }
  47609. }
  47610. else {
  47611. if (this.beta < this.lowerBetaLimit) {
  47612. this.beta = this.lowerBetaLimit;
  47613. }
  47614. }
  47615. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47616. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47617. this.beta = this.beta + (2 * Math.PI);
  47618. }
  47619. }
  47620. else {
  47621. if (this.beta > this.upperBetaLimit) {
  47622. this.beta = this.upperBetaLimit;
  47623. }
  47624. }
  47625. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47626. this.alpha = this.lowerAlphaLimit;
  47627. }
  47628. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47629. this.alpha = this.upperAlphaLimit;
  47630. }
  47631. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47632. this.radius = this.lowerRadiusLimit;
  47633. }
  47634. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47635. this.radius = this.upperRadiusLimit;
  47636. }
  47637. };
  47638. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47639. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47640. this.radius = this._computationVector.length();
  47641. if (this.radius === 0) {
  47642. this.radius = 0.0001; // Just to avoid division by zero
  47643. }
  47644. // Alpha
  47645. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47646. if (this._computationVector.z < 0) {
  47647. this.alpha = 2 * Math.PI - this.alpha;
  47648. }
  47649. // Beta
  47650. this.beta = Math.acos(this._computationVector.y / this.radius);
  47651. this._checkLimits();
  47652. };
  47653. ArcRotateCamera.prototype.setPosition = function (position) {
  47654. if (this.position.equals(position)) {
  47655. return;
  47656. }
  47657. this.position.copyFrom(position);
  47658. this.rebuildAnglesAndRadius();
  47659. };
  47660. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47661. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47662. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47663. if (target.getBoundingInfo) {
  47664. if (toBoundingCenter) {
  47665. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47666. }
  47667. else {
  47668. this._targetBoundingCenter = null;
  47669. }
  47670. this._targetHost = target;
  47671. this._target = this._getTargetPosition();
  47672. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47673. }
  47674. else {
  47675. var newTarget = target;
  47676. var currentTarget = this._getTargetPosition();
  47677. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47678. return;
  47679. }
  47680. this._targetHost = null;
  47681. this._target = newTarget;
  47682. this._targetBoundingCenter = null;
  47683. this.onMeshTargetChangedObservable.notifyObservers(null);
  47684. }
  47685. this.rebuildAnglesAndRadius();
  47686. };
  47687. ArcRotateCamera.prototype._getViewMatrix = function () {
  47688. // Compute
  47689. var cosa = Math.cos(this.alpha);
  47690. var sina = Math.sin(this.alpha);
  47691. var cosb = Math.cos(this.beta);
  47692. var sinb = Math.sin(this.beta);
  47693. if (sinb === 0) {
  47694. sinb = 0.0001;
  47695. }
  47696. var target = this._getTargetPosition();
  47697. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47698. target.addToRef(this._computationVector, this._newPosition);
  47699. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47700. if (!this._collider) {
  47701. this._collider = new BABYLON.Collider();
  47702. }
  47703. this._collider._radius = this.collisionRadius;
  47704. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47705. this._collisionTriggered = true;
  47706. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47707. }
  47708. else {
  47709. this.position.copyFrom(this._newPosition);
  47710. var up = this.upVector;
  47711. if (this.allowUpsideDown && sinb < 0) {
  47712. up = up.clone();
  47713. up = up.negate();
  47714. }
  47715. if (this.getScene().useRightHandedSystem) {
  47716. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  47717. }
  47718. else {
  47719. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  47720. }
  47721. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47722. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47723. }
  47724. this._currentTarget = target;
  47725. return this._viewMatrix;
  47726. };
  47727. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47728. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47729. meshes = meshes || this.getScene().meshes;
  47730. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47731. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47732. this.radius = distance * this.zoomOnFactor;
  47733. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47734. };
  47735. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47736. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47737. var meshesOrMinMaxVector;
  47738. var distance;
  47739. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  47740. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47741. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47742. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47743. }
  47744. else {
  47745. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47746. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47747. distance = minMaxVectorAndDistance.distance;
  47748. }
  47749. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47750. if (!doNotUpdateMaxZ) {
  47751. this.maxZ = distance * 2;
  47752. }
  47753. };
  47754. /**
  47755. * @override
  47756. * Override Camera.createRigCamera
  47757. */
  47758. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47759. var alphaShift = 0;
  47760. switch (this.cameraRigMode) {
  47761. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47762. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47763. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47764. case BABYLON.Camera.RIG_MODE_VR:
  47765. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47766. break;
  47767. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47768. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47769. break;
  47770. }
  47771. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47772. rigCam._cameraRigParams = {};
  47773. return rigCam;
  47774. };
  47775. /**
  47776. * @override
  47777. * Override Camera._updateRigCameras
  47778. */
  47779. ArcRotateCamera.prototype._updateRigCameras = function () {
  47780. var camLeft = this._rigCameras[0];
  47781. var camRight = this._rigCameras[1];
  47782. camLeft.beta = camRight.beta = this.beta;
  47783. camLeft.radius = camRight.radius = this.radius;
  47784. switch (this.cameraRigMode) {
  47785. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47786. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47787. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47788. case BABYLON.Camera.RIG_MODE_VR:
  47789. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47790. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47791. break;
  47792. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47793. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47794. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47795. break;
  47796. }
  47797. _super.prototype._updateRigCameras.call(this);
  47798. };
  47799. ArcRotateCamera.prototype.dispose = function () {
  47800. this.inputs.clear();
  47801. _super.prototype.dispose.call(this);
  47802. };
  47803. ArcRotateCamera.prototype.getClassName = function () {
  47804. return "ArcRotateCamera";
  47805. };
  47806. __decorate([
  47807. BABYLON.serialize()
  47808. ], ArcRotateCamera.prototype, "alpha", void 0);
  47809. __decorate([
  47810. BABYLON.serialize()
  47811. ], ArcRotateCamera.prototype, "beta", void 0);
  47812. __decorate([
  47813. BABYLON.serialize()
  47814. ], ArcRotateCamera.prototype, "radius", void 0);
  47815. __decorate([
  47816. BABYLON.serializeAsVector3("target")
  47817. ], ArcRotateCamera.prototype, "_target", void 0);
  47818. __decorate([
  47819. BABYLON.serialize()
  47820. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47821. __decorate([
  47822. BABYLON.serialize()
  47823. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47824. __decorate([
  47825. BABYLON.serialize()
  47826. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47827. __decorate([
  47828. BABYLON.serialize()
  47829. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47830. __decorate([
  47831. BABYLON.serialize()
  47832. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47833. __decorate([
  47834. BABYLON.serialize()
  47835. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47836. __decorate([
  47837. BABYLON.serialize()
  47838. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47839. __decorate([
  47840. BABYLON.serialize()
  47841. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47842. __decorate([
  47843. BABYLON.serialize()
  47844. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47845. __decorate([
  47846. BABYLON.serialize()
  47847. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47848. __decorate([
  47849. BABYLON.serialize()
  47850. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47851. __decorate([
  47852. BABYLON.serialize()
  47853. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  47854. __decorate([
  47855. BABYLON.serialize()
  47856. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  47857. __decorate([
  47858. BABYLON.serializeAsVector3()
  47859. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  47860. __decorate([
  47861. BABYLON.serialize()
  47862. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  47863. __decorate([
  47864. BABYLON.serialize()
  47865. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  47866. __decorate([
  47867. BABYLON.serialize()
  47868. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  47869. return ArcRotateCamera;
  47870. }(BABYLON.TargetCamera));
  47871. BABYLON.ArcRotateCamera = ArcRotateCamera;
  47872. })(BABYLON || (BABYLON = {}));
  47873. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  47874. "use strict";
  47875. var BABYLON;
  47876. (function (BABYLON) {
  47877. /**
  47878. * The HemisphericLight simulates the ambient environment light,
  47879. * so the passed direction is the light reflection direction, not the incoming direction.
  47880. */
  47881. var HemisphericLight = /** @class */ (function (_super) {
  47882. __extends(HemisphericLight, _super);
  47883. /**
  47884. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  47885. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  47886. * The HemisphericLight can't cast shadows.
  47887. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47888. * @param name The friendly name of the light
  47889. * @param direction The direction of the light reflection
  47890. * @param scene The scene the light belongs to
  47891. */
  47892. function HemisphericLight(name, direction, scene) {
  47893. var _this = _super.call(this, name, scene) || this;
  47894. /**
  47895. * The groundColor is the light in the opposite direction to the one specified during creation.
  47896. * 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.
  47897. */
  47898. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  47899. _this.direction = direction || BABYLON.Vector3.Up();
  47900. return _this;
  47901. }
  47902. HemisphericLight.prototype._buildUniformLayout = function () {
  47903. this._uniformBuffer.addUniform("vLightData", 4);
  47904. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47905. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47906. this._uniformBuffer.addUniform("vLightGround", 3);
  47907. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47908. this._uniformBuffer.addUniform("depthValues", 2);
  47909. this._uniformBuffer.create();
  47910. };
  47911. /**
  47912. * Returns the string "HemisphericLight".
  47913. * @return The class name
  47914. */
  47915. HemisphericLight.prototype.getClassName = function () {
  47916. return "HemisphericLight";
  47917. };
  47918. /**
  47919. * Sets the HemisphericLight direction towards the passed target (Vector3).
  47920. * Returns the updated direction.
  47921. * @param target The target the direction should point to
  47922. * @return The computed direction
  47923. */
  47924. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  47925. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  47926. return this.direction;
  47927. };
  47928. /**
  47929. * Returns the shadow generator associated to the light.
  47930. * @returns Always null for hemispheric lights because it does not support shadows.
  47931. */
  47932. HemisphericLight.prototype.getShadowGenerator = function () {
  47933. return null;
  47934. };
  47935. /**
  47936. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  47937. * @param effect The effect to update
  47938. * @param lightIndex The index of the light in the effect to update
  47939. * @returns The hemispheric light
  47940. */
  47941. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  47942. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  47943. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  47944. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  47945. return this;
  47946. };
  47947. /**
  47948. * @ignore internal use only.
  47949. */
  47950. HemisphericLight.prototype._getWorldMatrix = function () {
  47951. if (!this._worldMatrix) {
  47952. this._worldMatrix = BABYLON.Matrix.Identity();
  47953. }
  47954. return this._worldMatrix;
  47955. };
  47956. /**
  47957. * Returns the integer 3.
  47958. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47959. */
  47960. HemisphericLight.prototype.getTypeID = function () {
  47961. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  47962. };
  47963. __decorate([
  47964. BABYLON.serializeAsColor3()
  47965. ], HemisphericLight.prototype, "groundColor", void 0);
  47966. __decorate([
  47967. BABYLON.serializeAsVector3()
  47968. ], HemisphericLight.prototype, "direction", void 0);
  47969. return HemisphericLight;
  47970. }(BABYLON.Light));
  47971. BABYLON.HemisphericLight = HemisphericLight;
  47972. })(BABYLON || (BABYLON = {}));
  47973. //# sourceMappingURL=babylon.hemisphericLight.js.map
  47974. "use strict";
  47975. var BABYLON;
  47976. (function (BABYLON) {
  47977. /**
  47978. * Base implementation IShadowLight
  47979. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  47980. */
  47981. var ShadowLight = /** @class */ (function (_super) {
  47982. __extends(ShadowLight, _super);
  47983. function ShadowLight() {
  47984. var _this = _super !== null && _super.apply(this, arguments) || this;
  47985. _this._needProjectionMatrixCompute = true;
  47986. return _this;
  47987. }
  47988. ShadowLight.prototype._setPosition = function (value) {
  47989. this._position = value;
  47990. };
  47991. Object.defineProperty(ShadowLight.prototype, "position", {
  47992. /**
  47993. * Sets the position the shadow will be casted from. Also use as the light position for both
  47994. * point and spot lights.
  47995. */
  47996. get: function () {
  47997. return this._position;
  47998. },
  47999. /**
  48000. * Sets the position the shadow will be casted from. Also use as the light position for both
  48001. * point and spot lights.
  48002. */
  48003. set: function (value) {
  48004. this._setPosition(value);
  48005. },
  48006. enumerable: true,
  48007. configurable: true
  48008. });
  48009. ShadowLight.prototype._setDirection = function (value) {
  48010. this._direction = value;
  48011. };
  48012. Object.defineProperty(ShadowLight.prototype, "direction", {
  48013. /**
  48014. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48015. * Also use as the light direction on spot and directional lights.
  48016. */
  48017. get: function () {
  48018. return this._direction;
  48019. },
  48020. /**
  48021. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48022. * Also use as the light direction on spot and directional lights.
  48023. */
  48024. set: function (value) {
  48025. this._setDirection(value);
  48026. },
  48027. enumerable: true,
  48028. configurable: true
  48029. });
  48030. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48031. /**
  48032. * Gets the shadow projection clipping minimum z value.
  48033. */
  48034. get: function () {
  48035. return this._shadowMinZ;
  48036. },
  48037. /**
  48038. * Sets the shadow projection clipping minimum z value.
  48039. */
  48040. set: function (value) {
  48041. this._shadowMinZ = value;
  48042. this.forceProjectionMatrixCompute();
  48043. },
  48044. enumerable: true,
  48045. configurable: true
  48046. });
  48047. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48048. /**
  48049. * Sets the shadow projection clipping maximum z value.
  48050. */
  48051. get: function () {
  48052. return this._shadowMaxZ;
  48053. },
  48054. /**
  48055. * Gets the shadow projection clipping maximum z value.
  48056. */
  48057. set: function (value) {
  48058. this._shadowMaxZ = value;
  48059. this.forceProjectionMatrixCompute();
  48060. },
  48061. enumerable: true,
  48062. configurable: true
  48063. });
  48064. /**
  48065. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48066. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48067. */
  48068. ShadowLight.prototype.computeTransformedInformation = function () {
  48069. if (this.parent && this.parent.getWorldMatrix) {
  48070. if (!this.transformedPosition) {
  48071. this.transformedPosition = BABYLON.Vector3.Zero();
  48072. }
  48073. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48074. // In case the direction is present.
  48075. if (this.direction) {
  48076. if (!this.transformedDirection) {
  48077. this.transformedDirection = BABYLON.Vector3.Zero();
  48078. }
  48079. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48080. }
  48081. return true;
  48082. }
  48083. return false;
  48084. };
  48085. /**
  48086. * Return the depth scale used for the shadow map.
  48087. * @returns the depth scale.
  48088. */
  48089. ShadowLight.prototype.getDepthScale = function () {
  48090. return 50.0;
  48091. };
  48092. /**
  48093. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48094. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48095. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48096. */
  48097. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48098. return this.transformedDirection ? this.transformedDirection : this.direction;
  48099. };
  48100. /**
  48101. * Returns the ShadowLight absolute position in the World.
  48102. * @returns the position vector in world space
  48103. */
  48104. ShadowLight.prototype.getAbsolutePosition = function () {
  48105. return this.transformedPosition ? this.transformedPosition : this.position;
  48106. };
  48107. /**
  48108. * Sets the ShadowLight direction toward the passed target.
  48109. * @param target The point tot target in local space
  48110. * @returns the updated ShadowLight direction
  48111. */
  48112. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48113. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48114. return this.direction;
  48115. };
  48116. /**
  48117. * Returns the light rotation in euler definition.
  48118. * @returns the x y z rotation in local space.
  48119. */
  48120. ShadowLight.prototype.getRotation = function () {
  48121. this.direction.normalize();
  48122. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48123. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48124. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48125. };
  48126. /**
  48127. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48128. * @returns true if a cube texture needs to be use
  48129. */
  48130. ShadowLight.prototype.needCube = function () {
  48131. return false;
  48132. };
  48133. /**
  48134. * Detects if the projection matrix requires to be recomputed this frame.
  48135. * @returns true if it requires to be recomputed otherwise, false.
  48136. */
  48137. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48138. return this._needProjectionMatrixCompute;
  48139. };
  48140. /**
  48141. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48142. */
  48143. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48144. this._needProjectionMatrixCompute = true;
  48145. };
  48146. /**
  48147. * Get the world matrix of the sahdow lights.
  48148. * @ignore Internal Use Only
  48149. */
  48150. ShadowLight.prototype._getWorldMatrix = function () {
  48151. if (!this._worldMatrix) {
  48152. this._worldMatrix = BABYLON.Matrix.Identity();
  48153. }
  48154. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48155. return this._worldMatrix;
  48156. };
  48157. /**
  48158. * Gets the minZ used for shadow according to both the scene and the light.
  48159. * @param activeCamera The camera we are returning the min for
  48160. * @returns the depth min z
  48161. */
  48162. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48163. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48164. };
  48165. /**
  48166. * Gets the maxZ used for shadow according to both the scene and the light.
  48167. * @param activeCamera The camera we are returning the max for
  48168. * @returns the depth max z
  48169. */
  48170. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48171. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48172. };
  48173. /**
  48174. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48175. * @param matrix The materix to updated with the projection information
  48176. * @param viewMatrix The transform matrix of the light
  48177. * @param renderList The list of mesh to render in the map
  48178. * @returns The current light
  48179. */
  48180. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48181. if (this.customProjectionMatrixBuilder) {
  48182. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48183. }
  48184. else {
  48185. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48186. }
  48187. return this;
  48188. };
  48189. __decorate([
  48190. BABYLON.serializeAsVector3()
  48191. ], ShadowLight.prototype, "position", null);
  48192. __decorate([
  48193. BABYLON.serializeAsVector3()
  48194. ], ShadowLight.prototype, "direction", null);
  48195. __decorate([
  48196. BABYLON.serialize()
  48197. ], ShadowLight.prototype, "shadowMinZ", null);
  48198. __decorate([
  48199. BABYLON.serialize()
  48200. ], ShadowLight.prototype, "shadowMaxZ", null);
  48201. return ShadowLight;
  48202. }(BABYLON.Light));
  48203. BABYLON.ShadowLight = ShadowLight;
  48204. })(BABYLON || (BABYLON = {}));
  48205. //# sourceMappingURL=babylon.shadowLight.js.map
  48206. "use strict";
  48207. var BABYLON;
  48208. (function (BABYLON) {
  48209. /**
  48210. * A point light is a light defined by an unique point in world space.
  48211. * The light is emitted in every direction from this point.
  48212. * A good example of a point light is a standard light bulb.
  48213. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48214. */
  48215. var PointLight = /** @class */ (function (_super) {
  48216. __extends(PointLight, _super);
  48217. /**
  48218. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48219. * A PointLight emits the light in every direction.
  48220. * It can cast shadows.
  48221. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48222. * ```javascript
  48223. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48224. * ```
  48225. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48226. * @param name The light friendly name
  48227. * @param position The position of the point light in the scene
  48228. * @param scene The scene the lights belongs to
  48229. */
  48230. function PointLight(name, position, scene) {
  48231. var _this = _super.call(this, name, scene) || this;
  48232. _this._shadowAngle = Math.PI / 2;
  48233. _this.position = position;
  48234. return _this;
  48235. }
  48236. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48237. /**
  48238. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48239. * This specifies what angle the shadow will use to be created.
  48240. *
  48241. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48242. */
  48243. get: function () {
  48244. return this._shadowAngle;
  48245. },
  48246. /**
  48247. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48248. * This specifies what angle the shadow will use to be created.
  48249. *
  48250. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48251. */
  48252. set: function (value) {
  48253. this._shadowAngle = value;
  48254. this.forceProjectionMatrixCompute();
  48255. },
  48256. enumerable: true,
  48257. configurable: true
  48258. });
  48259. Object.defineProperty(PointLight.prototype, "direction", {
  48260. /**
  48261. * Gets the direction if it has been set.
  48262. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48263. */
  48264. get: function () {
  48265. return this._direction;
  48266. },
  48267. /**
  48268. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48269. */
  48270. set: function (value) {
  48271. var previousNeedCube = this.needCube();
  48272. this._direction = value;
  48273. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48274. this._shadowGenerator.recreateShadowMap();
  48275. }
  48276. },
  48277. enumerable: true,
  48278. configurable: true
  48279. });
  48280. /**
  48281. * Returns the string "PointLight"
  48282. * @returns the class name
  48283. */
  48284. PointLight.prototype.getClassName = function () {
  48285. return "PointLight";
  48286. };
  48287. /**
  48288. * Returns the integer 0.
  48289. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48290. */
  48291. PointLight.prototype.getTypeID = function () {
  48292. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48293. };
  48294. /**
  48295. * Specifies wether or not the shadowmap should be a cube texture.
  48296. * @returns true if the shadowmap needs to be a cube texture.
  48297. */
  48298. PointLight.prototype.needCube = function () {
  48299. return !this.direction;
  48300. };
  48301. /**
  48302. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48303. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48304. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48305. */
  48306. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48307. if (this.direction) {
  48308. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48309. }
  48310. else {
  48311. switch (faceIndex) {
  48312. case 0:
  48313. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48314. case 1:
  48315. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48316. case 2:
  48317. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48318. case 3:
  48319. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48320. case 4:
  48321. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48322. case 5:
  48323. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48324. }
  48325. }
  48326. return BABYLON.Vector3.Zero();
  48327. };
  48328. /**
  48329. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48330. * - fov = PI / 2
  48331. * - aspect ratio : 1.0
  48332. * - z-near and far equal to the active camera minZ and maxZ.
  48333. * Returns the PointLight.
  48334. */
  48335. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48336. var activeCamera = this.getScene().activeCamera;
  48337. if (!activeCamera) {
  48338. return;
  48339. }
  48340. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48341. };
  48342. PointLight.prototype._buildUniformLayout = function () {
  48343. this._uniformBuffer.addUniform("vLightData", 4);
  48344. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48345. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48346. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48347. this._uniformBuffer.addUniform("depthValues", 2);
  48348. this._uniformBuffer.create();
  48349. };
  48350. /**
  48351. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48352. * @param effect The effect to update
  48353. * @param lightIndex The index of the light in the effect to update
  48354. * @returns The point light
  48355. */
  48356. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48357. if (this.computeTransformedInformation()) {
  48358. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48359. return this;
  48360. }
  48361. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48362. return this;
  48363. };
  48364. __decorate([
  48365. BABYLON.serialize()
  48366. ], PointLight.prototype, "shadowAngle", null);
  48367. return PointLight;
  48368. }(BABYLON.ShadowLight));
  48369. BABYLON.PointLight = PointLight;
  48370. })(BABYLON || (BABYLON = {}));
  48371. //# sourceMappingURL=babylon.pointLight.js.map
  48372. "use strict";
  48373. var BABYLON;
  48374. (function (BABYLON) {
  48375. /**
  48376. * A directional light is defined by a direction (what a surprise!).
  48377. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48378. * 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.
  48379. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48380. */
  48381. var DirectionalLight = /** @class */ (function (_super) {
  48382. __extends(DirectionalLight, _super);
  48383. /**
  48384. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48385. * The directional light is emitted from everywhere in the given direction.
  48386. * It can cast shawdows.
  48387. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48388. * @param name The friendly name of the light
  48389. * @param direction The direction of the light
  48390. * @param scene The scene the light belongs to
  48391. */
  48392. function DirectionalLight(name, direction, scene) {
  48393. var _this = _super.call(this, name, scene) || this;
  48394. _this._shadowFrustumSize = 0;
  48395. _this._shadowOrthoScale = 0.1;
  48396. /**
  48397. * Automatically compute the projection matrix to best fit (including all the casters)
  48398. * on each frame.
  48399. */
  48400. _this.autoUpdateExtends = true;
  48401. // Cache
  48402. _this._orthoLeft = Number.MAX_VALUE;
  48403. _this._orthoRight = Number.MIN_VALUE;
  48404. _this._orthoTop = Number.MIN_VALUE;
  48405. _this._orthoBottom = Number.MAX_VALUE;
  48406. _this.position = direction.scale(-1.0);
  48407. _this.direction = direction;
  48408. return _this;
  48409. }
  48410. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48411. /**
  48412. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48413. */
  48414. get: function () {
  48415. return this._shadowFrustumSize;
  48416. },
  48417. /**
  48418. * Specifies a fix frustum size for the shadow generation.
  48419. */
  48420. set: function (value) {
  48421. this._shadowFrustumSize = value;
  48422. this.forceProjectionMatrixCompute();
  48423. },
  48424. enumerable: true,
  48425. configurable: true
  48426. });
  48427. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48428. /**
  48429. * Gets the shadow projection scale against the optimal computed one.
  48430. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48431. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48432. */
  48433. get: function () {
  48434. return this._shadowOrthoScale;
  48435. },
  48436. /**
  48437. * Sets the shadow projection scale against the optimal computed one.
  48438. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48439. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48440. */
  48441. set: function (value) {
  48442. this._shadowOrthoScale = value;
  48443. this.forceProjectionMatrixCompute();
  48444. },
  48445. enumerable: true,
  48446. configurable: true
  48447. });
  48448. /**
  48449. * Returns the string "DirectionalLight".
  48450. * @return The class name
  48451. */
  48452. DirectionalLight.prototype.getClassName = function () {
  48453. return "DirectionalLight";
  48454. };
  48455. /**
  48456. * Returns the integer 1.
  48457. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48458. */
  48459. DirectionalLight.prototype.getTypeID = function () {
  48460. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48461. };
  48462. /**
  48463. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48464. * Returns the DirectionalLight Shadow projection matrix.
  48465. */
  48466. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48467. if (this.shadowFrustumSize > 0) {
  48468. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48469. }
  48470. else {
  48471. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48472. }
  48473. };
  48474. /**
  48475. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48476. * Returns the DirectionalLight Shadow projection matrix.
  48477. */
  48478. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48479. var activeCamera = this.getScene().activeCamera;
  48480. if (!activeCamera) {
  48481. return;
  48482. }
  48483. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48484. };
  48485. /**
  48486. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48487. * Returns the DirectionalLight Shadow projection matrix.
  48488. */
  48489. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48490. var activeCamera = this.getScene().activeCamera;
  48491. if (!activeCamera) {
  48492. return;
  48493. }
  48494. // Check extends
  48495. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48496. var tempVector3 = BABYLON.Vector3.Zero();
  48497. this._orthoLeft = Number.MAX_VALUE;
  48498. this._orthoRight = Number.MIN_VALUE;
  48499. this._orthoTop = Number.MIN_VALUE;
  48500. this._orthoBottom = Number.MAX_VALUE;
  48501. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48502. var mesh = renderList[meshIndex];
  48503. if (!mesh) {
  48504. continue;
  48505. }
  48506. var boundingInfo = mesh.getBoundingInfo();
  48507. var boundingBox = boundingInfo.boundingBox;
  48508. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48509. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48510. if (tempVector3.x < this._orthoLeft)
  48511. this._orthoLeft = tempVector3.x;
  48512. if (tempVector3.y < this._orthoBottom)
  48513. this._orthoBottom = tempVector3.y;
  48514. if (tempVector3.x > this._orthoRight)
  48515. this._orthoRight = tempVector3.x;
  48516. if (tempVector3.y > this._orthoTop)
  48517. this._orthoTop = tempVector3.y;
  48518. }
  48519. }
  48520. }
  48521. var xOffset = this._orthoRight - this._orthoLeft;
  48522. var yOffset = this._orthoTop - this._orthoBottom;
  48523. 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);
  48524. };
  48525. DirectionalLight.prototype._buildUniformLayout = function () {
  48526. this._uniformBuffer.addUniform("vLightData", 4);
  48527. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48528. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48529. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48530. this._uniformBuffer.addUniform("depthValues", 2);
  48531. this._uniformBuffer.create();
  48532. };
  48533. /**
  48534. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48535. * @param effect The effect to update
  48536. * @param lightIndex The index of the light in the effect to update
  48537. * @returns The directional light
  48538. */
  48539. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48540. if (this.computeTransformedInformation()) {
  48541. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48542. return this;
  48543. }
  48544. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48545. return this;
  48546. };
  48547. /**
  48548. * Gets the minZ used for shadow according to both the scene and the light.
  48549. *
  48550. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48551. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48552. * @param activeCamera The camera we are returning the min for
  48553. * @returns the depth min z
  48554. */
  48555. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48556. return 1;
  48557. };
  48558. /**
  48559. * Gets the maxZ used for shadow according to both the scene and the light.
  48560. *
  48561. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48562. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48563. * @param activeCamera The camera we are returning the max for
  48564. * @returns the depth max z
  48565. */
  48566. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48567. return 1;
  48568. };
  48569. __decorate([
  48570. BABYLON.serialize()
  48571. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48572. __decorate([
  48573. BABYLON.serialize()
  48574. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48575. __decorate([
  48576. BABYLON.serialize()
  48577. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48578. return DirectionalLight;
  48579. }(BABYLON.ShadowLight));
  48580. BABYLON.DirectionalLight = DirectionalLight;
  48581. })(BABYLON || (BABYLON = {}));
  48582. //# sourceMappingURL=babylon.directionalLight.js.map
  48583. "use strict";
  48584. var BABYLON;
  48585. (function (BABYLON) {
  48586. /**
  48587. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48588. * These values define a cone of light starting from the position, emitting toward the direction.
  48589. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48590. * and the exponent defines the speed of the decay of the light with distance (reach).
  48591. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48592. */
  48593. var SpotLight = /** @class */ (function (_super) {
  48594. __extends(SpotLight, _super);
  48595. /**
  48596. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48597. * It can cast shadows.
  48598. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48599. * @param name The light friendly name
  48600. * @param position The position of the spot light in the scene
  48601. * @param direction The direction of the light in the scene
  48602. * @param angle The cone angle of the light in Radians
  48603. * @param exponent The light decay speed with the distance from the emission spot
  48604. * @param scene The scene the lights belongs to
  48605. */
  48606. function SpotLight(name, position, direction, angle, exponent, scene) {
  48607. var _this = _super.call(this, name, scene) || this;
  48608. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48609. _this._projectionTextureLightNear = 1e-6;
  48610. _this._projectionTextureLightFar = 1000.0;
  48611. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48612. _this._projectionTextureViewLightDirty = true;
  48613. _this._projectionTextureProjectionLightDirty = true;
  48614. _this._projectionTextureDirty = true;
  48615. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48616. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48617. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48618. _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);
  48619. _this.position = position;
  48620. _this.direction = direction;
  48621. _this.angle = angle;
  48622. _this.exponent = exponent;
  48623. return _this;
  48624. }
  48625. Object.defineProperty(SpotLight.prototype, "angle", {
  48626. /**
  48627. * Gets the cone angle of the spot light in Radians.
  48628. */
  48629. get: function () {
  48630. return this._angle;
  48631. },
  48632. /**
  48633. * Sets the cone angle of the spot light in Radians.
  48634. */
  48635. set: function (value) {
  48636. this._angle = value;
  48637. this._projectionTextureProjectionLightDirty = true;
  48638. this.forceProjectionMatrixCompute();
  48639. },
  48640. enumerable: true,
  48641. configurable: true
  48642. });
  48643. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48644. /**
  48645. * Allows scaling the angle of the light for shadow generation only.
  48646. */
  48647. get: function () {
  48648. return this._shadowAngleScale;
  48649. },
  48650. /**
  48651. * Allows scaling the angle of the light for shadow generation only.
  48652. */
  48653. set: function (value) {
  48654. this._shadowAngleScale = value;
  48655. this.forceProjectionMatrixCompute();
  48656. },
  48657. enumerable: true,
  48658. configurable: true
  48659. });
  48660. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48661. /**
  48662. * Allows reading the projecton texture
  48663. */
  48664. get: function () {
  48665. return this._projectionTextureMatrix;
  48666. },
  48667. enumerable: true,
  48668. configurable: true
  48669. });
  48670. ;
  48671. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48672. /**
  48673. * Gets the near clip of the Spotlight for texture projection.
  48674. */
  48675. get: function () {
  48676. return this._projectionTextureLightNear;
  48677. },
  48678. /**
  48679. * Sets the near clip of the Spotlight for texture projection.
  48680. */
  48681. set: function (value) {
  48682. this._projectionTextureLightNear = value;
  48683. this._projectionTextureProjectionLightDirty = true;
  48684. },
  48685. enumerable: true,
  48686. configurable: true
  48687. });
  48688. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48689. /**
  48690. * Gets the far clip of the Spotlight for texture projection.
  48691. */
  48692. get: function () {
  48693. return this._projectionTextureLightFar;
  48694. },
  48695. /**
  48696. * Sets the far clip of the Spotlight for texture projection.
  48697. */
  48698. set: function (value) {
  48699. this._projectionTextureLightFar = value;
  48700. this._projectionTextureProjectionLightDirty = true;
  48701. },
  48702. enumerable: true,
  48703. configurable: true
  48704. });
  48705. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48706. /**
  48707. * Gets the Up vector of the Spotlight for texture projection.
  48708. */
  48709. get: function () {
  48710. return this._projectionTextureUpDirection;
  48711. },
  48712. /**
  48713. * Sets the Up vector of the Spotlight for texture projection.
  48714. */
  48715. set: function (value) {
  48716. this._projectionTextureUpDirection = value;
  48717. this._projectionTextureProjectionLightDirty = true;
  48718. },
  48719. enumerable: true,
  48720. configurable: true
  48721. });
  48722. ;
  48723. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48724. /**
  48725. * Gets the projection texture of the light.
  48726. */
  48727. get: function () {
  48728. return this._projectionTexture;
  48729. },
  48730. /**
  48731. * Sets the projection texture of the light.
  48732. */
  48733. set: function (value) {
  48734. this._projectionTexture = value;
  48735. this._projectionTextureDirty = true;
  48736. },
  48737. enumerable: true,
  48738. configurable: true
  48739. });
  48740. /**
  48741. * Returns the string "SpotLight".
  48742. * @returns the class name
  48743. */
  48744. SpotLight.prototype.getClassName = function () {
  48745. return "SpotLight";
  48746. };
  48747. /**
  48748. * Returns the integer 2.
  48749. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48750. */
  48751. SpotLight.prototype.getTypeID = function () {
  48752. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48753. };
  48754. /**
  48755. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48756. */
  48757. SpotLight.prototype._setDirection = function (value) {
  48758. _super.prototype._setDirection.call(this, value);
  48759. this._projectionTextureViewLightDirty = true;
  48760. };
  48761. /**
  48762. * Overrides the position setter to recompute the projection texture view light Matrix.
  48763. */
  48764. SpotLight.prototype._setPosition = function (value) {
  48765. _super.prototype._setPosition.call(this, value);
  48766. this._projectionTextureViewLightDirty = true;
  48767. };
  48768. /**
  48769. * 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.
  48770. * Returns the SpotLight.
  48771. */
  48772. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48773. var activeCamera = this.getScene().activeCamera;
  48774. if (!activeCamera) {
  48775. return;
  48776. }
  48777. this._shadowAngleScale = this._shadowAngleScale || 1;
  48778. var angle = this._shadowAngleScale * this._angle;
  48779. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48780. };
  48781. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48782. this._projectionTextureViewLightDirty = false;
  48783. this._projectionTextureDirty = true;
  48784. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48785. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48786. };
  48787. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48788. this._projectionTextureProjectionLightDirty = false;
  48789. this._projectionTextureDirty = true;
  48790. var light_far = this.projectionTextureLightFar;
  48791. var light_near = this.projectionTextureLightNear;
  48792. var P = light_far / (light_far - light_near);
  48793. var Q = -P * light_near;
  48794. var S = 1.0 / Math.tan(this._angle / 2.0);
  48795. var A = 1.0;
  48796. 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);
  48797. };
  48798. /**
  48799. * Main function for light texture projection matrix computing.
  48800. */
  48801. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48802. this._projectionTextureDirty = false;
  48803. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48804. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48805. };
  48806. SpotLight.prototype._buildUniformLayout = function () {
  48807. this._uniformBuffer.addUniform("vLightData", 4);
  48808. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48809. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48810. this._uniformBuffer.addUniform("vLightDirection", 3);
  48811. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48812. this._uniformBuffer.addUniform("depthValues", 2);
  48813. this._uniformBuffer.create();
  48814. };
  48815. /**
  48816. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48817. * @param effect The effect to update
  48818. * @param lightIndex The index of the light in the effect to update
  48819. * @returns The spot light
  48820. */
  48821. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48822. var normalizeDirection;
  48823. if (this.computeTransformedInformation()) {
  48824. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  48825. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  48826. }
  48827. else {
  48828. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  48829. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48830. }
  48831. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  48832. if (this.projectionTexture && this.projectionTexture.isReady()) {
  48833. if (this._projectionTextureViewLightDirty) {
  48834. this._computeProjectionTextureViewLightMatrix();
  48835. }
  48836. if (this._projectionTextureProjectionLightDirty) {
  48837. this._computeProjectionTextureProjectionLightMatrix();
  48838. }
  48839. if (this._projectionTextureDirty) {
  48840. this._computeProjectionTextureMatrix();
  48841. }
  48842. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  48843. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  48844. }
  48845. return this;
  48846. };
  48847. /**
  48848. * Disposes the light and the associated resources.
  48849. */
  48850. SpotLight.prototype.dispose = function () {
  48851. _super.prototype.dispose.call(this);
  48852. if (this._projectionTexture) {
  48853. this._projectionTexture.dispose();
  48854. }
  48855. };
  48856. __decorate([
  48857. BABYLON.serialize()
  48858. ], SpotLight.prototype, "angle", null);
  48859. __decorate([
  48860. BABYLON.serialize()
  48861. ], SpotLight.prototype, "shadowAngleScale", null);
  48862. __decorate([
  48863. BABYLON.serialize()
  48864. ], SpotLight.prototype, "exponent", void 0);
  48865. __decorate([
  48866. BABYLON.serialize()
  48867. ], SpotLight.prototype, "projectionTextureLightNear", null);
  48868. __decorate([
  48869. BABYLON.serialize()
  48870. ], SpotLight.prototype, "projectionTextureLightFar", null);
  48871. __decorate([
  48872. BABYLON.serialize()
  48873. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  48874. __decorate([
  48875. BABYLON.serializeAsTexture("projectedLightTexture")
  48876. ], SpotLight.prototype, "_projectionTexture", void 0);
  48877. return SpotLight;
  48878. }(BABYLON.ShadowLight));
  48879. BABYLON.SpotLight = SpotLight;
  48880. })(BABYLON || (BABYLON = {}));
  48881. //# sourceMappingURL=babylon.spotLight.js.map
  48882. "use strict";
  48883. var BABYLON;
  48884. (function (BABYLON) {
  48885. /**
  48886. * Class used to override all child animations of a given target
  48887. */
  48888. var AnimationPropertiesOverride = /** @class */ (function () {
  48889. function AnimationPropertiesOverride() {
  48890. /**
  48891. * Gets or sets a value indicating if animation blending must be used
  48892. */
  48893. this.enableBlending = false;
  48894. /**
  48895. * Gets or sets the blending speed to use when enableBlending is true
  48896. */
  48897. this.blendingSpeed = 0.01;
  48898. /**
  48899. * Gets or sets the default loop mode to use
  48900. */
  48901. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  48902. }
  48903. return AnimationPropertiesOverride;
  48904. }());
  48905. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  48906. })(BABYLON || (BABYLON = {}));
  48907. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  48908. "use strict";
  48909. var BABYLON;
  48910. (function (BABYLON) {
  48911. var AnimationRange = /** @class */ (function () {
  48912. function AnimationRange(name, from, to) {
  48913. this.name = name;
  48914. this.from = from;
  48915. this.to = to;
  48916. }
  48917. AnimationRange.prototype.clone = function () {
  48918. return new AnimationRange(this.name, this.from, this.to);
  48919. };
  48920. return AnimationRange;
  48921. }());
  48922. BABYLON.AnimationRange = AnimationRange;
  48923. /**
  48924. * Composed of a frame, and an action function
  48925. */
  48926. var AnimationEvent = /** @class */ (function () {
  48927. function AnimationEvent(frame, action, onlyOnce) {
  48928. this.frame = frame;
  48929. this.action = action;
  48930. this.onlyOnce = onlyOnce;
  48931. this.isDone = false;
  48932. }
  48933. return AnimationEvent;
  48934. }());
  48935. BABYLON.AnimationEvent = AnimationEvent;
  48936. var PathCursor = /** @class */ (function () {
  48937. function PathCursor(path) {
  48938. this.path = path;
  48939. this._onchange = new Array();
  48940. this.value = 0;
  48941. this.animations = new Array();
  48942. }
  48943. PathCursor.prototype.getPoint = function () {
  48944. var point = this.path.getPointAtLengthPosition(this.value);
  48945. return new BABYLON.Vector3(point.x, 0, point.y);
  48946. };
  48947. PathCursor.prototype.moveAhead = function (step) {
  48948. if (step === void 0) { step = 0.002; }
  48949. this.move(step);
  48950. return this;
  48951. };
  48952. PathCursor.prototype.moveBack = function (step) {
  48953. if (step === void 0) { step = 0.002; }
  48954. this.move(-step);
  48955. return this;
  48956. };
  48957. PathCursor.prototype.move = function (step) {
  48958. if (Math.abs(step) > 1) {
  48959. throw "step size should be less than 1.";
  48960. }
  48961. this.value += step;
  48962. this.ensureLimits();
  48963. this.raiseOnChange();
  48964. return this;
  48965. };
  48966. PathCursor.prototype.ensureLimits = function () {
  48967. while (this.value > 1) {
  48968. this.value -= 1;
  48969. }
  48970. while (this.value < 0) {
  48971. this.value += 1;
  48972. }
  48973. return this;
  48974. };
  48975. // used by animation engine
  48976. PathCursor.prototype.raiseOnChange = function () {
  48977. var _this = this;
  48978. this._onchange.forEach(function (f) { return f(_this); });
  48979. return this;
  48980. };
  48981. PathCursor.prototype.onchange = function (f) {
  48982. this._onchange.push(f);
  48983. return this;
  48984. };
  48985. return PathCursor;
  48986. }());
  48987. BABYLON.PathCursor = PathCursor;
  48988. var AnimationKeyInterpolation;
  48989. (function (AnimationKeyInterpolation) {
  48990. /**
  48991. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  48992. */
  48993. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  48994. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  48995. var Animation = /** @class */ (function () {
  48996. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  48997. this.name = name;
  48998. this.targetProperty = targetProperty;
  48999. this.framePerSecond = framePerSecond;
  49000. this.dataType = dataType;
  49001. this.loopMode = loopMode;
  49002. this.enableBlending = enableBlending;
  49003. this._runtimeAnimations = new Array();
  49004. // The set of event that will be linked to this animation
  49005. this._events = new Array();
  49006. this.blendingSpeed = 0.01;
  49007. this._ranges = {};
  49008. this.targetPropertyPath = targetProperty.split(".");
  49009. this.dataType = dataType;
  49010. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49011. }
  49012. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49013. var dataType = undefined;
  49014. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49015. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49016. }
  49017. else if (from instanceof BABYLON.Quaternion) {
  49018. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49019. }
  49020. else if (from instanceof BABYLON.Vector3) {
  49021. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49022. }
  49023. else if (from instanceof BABYLON.Vector2) {
  49024. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49025. }
  49026. else if (from instanceof BABYLON.Color3) {
  49027. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49028. }
  49029. else if (from instanceof BABYLON.Size) {
  49030. dataType = Animation.ANIMATIONTYPE_SIZE;
  49031. }
  49032. if (dataType == undefined) {
  49033. return null;
  49034. }
  49035. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49036. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49037. animation.setKeys(keys);
  49038. if (easingFunction !== undefined) {
  49039. animation.setEasingFunction(easingFunction);
  49040. }
  49041. return animation;
  49042. };
  49043. /**
  49044. * Sets up an animation.
  49045. * @param property the property to animate
  49046. * @param animationType the animation type to apply
  49047. * @param easingFunction the easing function used in the animation
  49048. * @returns The created animation
  49049. */
  49050. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49051. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49052. animation.setEasingFunction(easingFunction);
  49053. return animation;
  49054. };
  49055. /**
  49056. * Create and start an animation on a node
  49057. * @param {string} name defines the name of the global animation that will be run on all nodes
  49058. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49059. * @param {string} targetProperty defines property to animate
  49060. * @param {number} framePerSecond defines the number of frame per second yo use
  49061. * @param {number} totalFrame defines the number of frames in total
  49062. * @param {any} from defines the initial value
  49063. * @param {any} to defines the final value
  49064. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49065. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49066. * @param onAnimationEnd defines the callback to call when animation end
  49067. * @returns the animatable created for this animation
  49068. */
  49069. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49070. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49071. if (!animation) {
  49072. return null;
  49073. }
  49074. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49075. };
  49076. /**
  49077. * Create and start an animation on a node and its descendants
  49078. * @param {string} name defines the name of the global animation that will be run on all nodes
  49079. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49080. * @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.
  49081. * @param {string} targetProperty defines property to animate
  49082. * @param {number} framePerSecond defines the number of frame per second yo use
  49083. * @param {number} totalFrame defines the number of frames in total
  49084. * @param {any} from defines the initial value
  49085. * @param {any} to defines the final value
  49086. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49087. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49088. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49089. * @returns the list of animatables created for all nodes
  49090. * @example https://www.babylonjs-playground.com/#MH0VLI
  49091. */
  49092. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49093. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49094. if (!animation) {
  49095. return null;
  49096. }
  49097. var scene = node.getScene();
  49098. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49099. };
  49100. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49101. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49102. if (!animation) {
  49103. return null;
  49104. }
  49105. node.animations.push(animation);
  49106. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49107. };
  49108. /**
  49109. * Transition property of the Camera to the target Value.
  49110. * @param property The property to transition
  49111. * @param targetValue The target Value of the property
  49112. * @param host The object where the property to animate belongs
  49113. * @param scene Scene used to run the animation
  49114. * @param frameRate Framerate (in frame/s) to use
  49115. * @param transition The transition type we want to use
  49116. * @param duration The duration of the animation, in milliseconds
  49117. * @param onAnimationEnd Call back trigger at the end of the animation.
  49118. */
  49119. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49120. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49121. if (duration <= 0) {
  49122. host[property] = targetValue;
  49123. if (onAnimationEnd) {
  49124. onAnimationEnd();
  49125. }
  49126. return null;
  49127. }
  49128. var endFrame = frameRate * (duration / 1000);
  49129. transition.setKeys([{
  49130. frame: 0,
  49131. value: host[property].clone ? host[property].clone() : host[property]
  49132. },
  49133. {
  49134. frame: endFrame,
  49135. value: targetValue
  49136. }]);
  49137. if (!host.animations) {
  49138. host.animations = [];
  49139. }
  49140. host.animations.push(transition);
  49141. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49142. animation.onAnimationEnd = onAnimationEnd;
  49143. return animation;
  49144. };
  49145. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49146. /**
  49147. * Return the array of runtime animations currently using this animation
  49148. */
  49149. get: function () {
  49150. return this._runtimeAnimations;
  49151. },
  49152. enumerable: true,
  49153. configurable: true
  49154. });
  49155. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49156. get: function () {
  49157. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49158. var runtimeAnimation = _a[_i];
  49159. if (!runtimeAnimation.isStopped) {
  49160. return true;
  49161. }
  49162. }
  49163. return false;
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. // Methods
  49169. /**
  49170. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49171. */
  49172. Animation.prototype.toString = function (fullDetails) {
  49173. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49174. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49175. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49176. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49177. if (fullDetails) {
  49178. ret += ", Ranges: {";
  49179. var first = true;
  49180. for (var name in this._ranges) {
  49181. if (first) {
  49182. ret += ", ";
  49183. first = false;
  49184. }
  49185. ret += name;
  49186. }
  49187. ret += "}";
  49188. }
  49189. return ret;
  49190. };
  49191. /**
  49192. * Add an event to this animation.
  49193. */
  49194. Animation.prototype.addEvent = function (event) {
  49195. this._events.push(event);
  49196. };
  49197. /**
  49198. * Remove all events found at the given frame
  49199. * @param frame
  49200. */
  49201. Animation.prototype.removeEvents = function (frame) {
  49202. for (var index = 0; index < this._events.length; index++) {
  49203. if (this._events[index].frame === frame) {
  49204. this._events.splice(index, 1);
  49205. index--;
  49206. }
  49207. }
  49208. };
  49209. Animation.prototype.getEvents = function () {
  49210. return this._events;
  49211. };
  49212. Animation.prototype.createRange = function (name, from, to) {
  49213. // check name not already in use; could happen for bones after serialized
  49214. if (!this._ranges[name]) {
  49215. this._ranges[name] = new AnimationRange(name, from, to);
  49216. }
  49217. };
  49218. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49219. if (deleteFrames === void 0) { deleteFrames = true; }
  49220. var range = this._ranges[name];
  49221. if (!range) {
  49222. return;
  49223. }
  49224. if (deleteFrames) {
  49225. var from = range.from;
  49226. var to = range.to;
  49227. // this loop MUST go high to low for multiple splices to work
  49228. for (var key = this._keys.length - 1; key >= 0; key--) {
  49229. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49230. this._keys.splice(key, 1);
  49231. }
  49232. }
  49233. }
  49234. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49235. };
  49236. Animation.prototype.getRange = function (name) {
  49237. return this._ranges[name];
  49238. };
  49239. Animation.prototype.getKeys = function () {
  49240. return this._keys;
  49241. };
  49242. Animation.prototype.getHighestFrame = function () {
  49243. var ret = 0;
  49244. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49245. if (ret < this._keys[key].frame) {
  49246. ret = this._keys[key].frame;
  49247. }
  49248. }
  49249. return ret;
  49250. };
  49251. Animation.prototype.getEasingFunction = function () {
  49252. return this._easingFunction;
  49253. };
  49254. Animation.prototype.setEasingFunction = function (easingFunction) {
  49255. this._easingFunction = easingFunction;
  49256. };
  49257. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49258. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49259. };
  49260. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49261. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49262. };
  49263. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49264. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49265. };
  49266. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49267. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49268. };
  49269. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49270. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49271. };
  49272. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49273. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49274. };
  49275. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49276. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49277. };
  49278. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49279. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49280. };
  49281. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49282. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49283. };
  49284. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49285. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49286. };
  49287. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  49288. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49289. };
  49290. Animation.prototype.clone = function () {
  49291. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49292. clone.enableBlending = this.enableBlending;
  49293. clone.blendingSpeed = this.blendingSpeed;
  49294. if (this._keys) {
  49295. clone.setKeys(this._keys);
  49296. }
  49297. if (this._ranges) {
  49298. clone._ranges = {};
  49299. for (var name in this._ranges) {
  49300. var range = this._ranges[name];
  49301. if (!range) {
  49302. continue;
  49303. }
  49304. clone._ranges[name] = range.clone();
  49305. }
  49306. }
  49307. return clone;
  49308. };
  49309. Animation.prototype.setKeys = function (values) {
  49310. this._keys = values.slice(0);
  49311. };
  49312. Animation.prototype.serialize = function () {
  49313. var serializationObject = {};
  49314. serializationObject.name = this.name;
  49315. serializationObject.property = this.targetProperty;
  49316. serializationObject.framePerSecond = this.framePerSecond;
  49317. serializationObject.dataType = this.dataType;
  49318. serializationObject.loopBehavior = this.loopMode;
  49319. serializationObject.enableBlending = this.enableBlending;
  49320. serializationObject.blendingSpeed = this.blendingSpeed;
  49321. var dataType = this.dataType;
  49322. serializationObject.keys = [];
  49323. var keys = this.getKeys();
  49324. for (var index = 0; index < keys.length; index++) {
  49325. var animationKey = keys[index];
  49326. var key = {};
  49327. key.frame = animationKey.frame;
  49328. switch (dataType) {
  49329. case Animation.ANIMATIONTYPE_FLOAT:
  49330. key.values = [animationKey.value];
  49331. break;
  49332. case Animation.ANIMATIONTYPE_QUATERNION:
  49333. case Animation.ANIMATIONTYPE_MATRIX:
  49334. case Animation.ANIMATIONTYPE_VECTOR3:
  49335. case Animation.ANIMATIONTYPE_COLOR3:
  49336. key.values = animationKey.value.asArray();
  49337. break;
  49338. }
  49339. serializationObject.keys.push(key);
  49340. }
  49341. serializationObject.ranges = [];
  49342. for (var name in this._ranges) {
  49343. var source = this._ranges[name];
  49344. if (!source) {
  49345. continue;
  49346. }
  49347. var range = {};
  49348. range.name = name;
  49349. range.from = source.from;
  49350. range.to = source.to;
  49351. serializationObject.ranges.push(range);
  49352. }
  49353. return serializationObject;
  49354. };
  49355. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49356. get: function () {
  49357. return Animation._ANIMATIONTYPE_FLOAT;
  49358. },
  49359. enumerable: true,
  49360. configurable: true
  49361. });
  49362. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49363. get: function () {
  49364. return Animation._ANIMATIONTYPE_VECTOR3;
  49365. },
  49366. enumerable: true,
  49367. configurable: true
  49368. });
  49369. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49370. get: function () {
  49371. return Animation._ANIMATIONTYPE_VECTOR2;
  49372. },
  49373. enumerable: true,
  49374. configurable: true
  49375. });
  49376. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49377. get: function () {
  49378. return Animation._ANIMATIONTYPE_SIZE;
  49379. },
  49380. enumerable: true,
  49381. configurable: true
  49382. });
  49383. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49384. get: function () {
  49385. return Animation._ANIMATIONTYPE_QUATERNION;
  49386. },
  49387. enumerable: true,
  49388. configurable: true
  49389. });
  49390. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49391. get: function () {
  49392. return Animation._ANIMATIONTYPE_MATRIX;
  49393. },
  49394. enumerable: true,
  49395. configurable: true
  49396. });
  49397. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49398. get: function () {
  49399. return Animation._ANIMATIONTYPE_COLOR3;
  49400. },
  49401. enumerable: true,
  49402. configurable: true
  49403. });
  49404. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49405. get: function () {
  49406. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49407. },
  49408. enumerable: true,
  49409. configurable: true
  49410. });
  49411. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49412. get: function () {
  49413. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49414. },
  49415. enumerable: true,
  49416. configurable: true
  49417. });
  49418. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49419. get: function () {
  49420. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49421. },
  49422. enumerable: true,
  49423. configurable: true
  49424. });
  49425. Animation.Parse = function (parsedAnimation) {
  49426. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49427. var dataType = parsedAnimation.dataType;
  49428. var keys = [];
  49429. var data;
  49430. var index;
  49431. if (parsedAnimation.enableBlending) {
  49432. animation.enableBlending = parsedAnimation.enableBlending;
  49433. }
  49434. if (parsedAnimation.blendingSpeed) {
  49435. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49436. }
  49437. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49438. var key = parsedAnimation.keys[index];
  49439. var inTangent;
  49440. var outTangent;
  49441. switch (dataType) {
  49442. case Animation.ANIMATIONTYPE_FLOAT:
  49443. data = key.values[0];
  49444. if (key.values.length >= 1) {
  49445. inTangent = key.values[1];
  49446. }
  49447. if (key.values.length >= 2) {
  49448. outTangent = key.values[2];
  49449. }
  49450. break;
  49451. case Animation.ANIMATIONTYPE_QUATERNION:
  49452. data = BABYLON.Quaternion.FromArray(key.values);
  49453. if (key.values.length >= 8) {
  49454. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49455. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49456. inTangent = _inTangent;
  49457. }
  49458. }
  49459. if (key.values.length >= 12) {
  49460. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49461. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49462. outTangent = _outTangent;
  49463. }
  49464. }
  49465. break;
  49466. case Animation.ANIMATIONTYPE_MATRIX:
  49467. data = BABYLON.Matrix.FromArray(key.values);
  49468. break;
  49469. case Animation.ANIMATIONTYPE_COLOR3:
  49470. data = BABYLON.Color3.FromArray(key.values);
  49471. break;
  49472. case Animation.ANIMATIONTYPE_VECTOR3:
  49473. default:
  49474. data = BABYLON.Vector3.FromArray(key.values);
  49475. break;
  49476. }
  49477. var keyData = {};
  49478. keyData.frame = key.frame;
  49479. keyData.value = data;
  49480. if (inTangent != undefined) {
  49481. keyData.inTangent = inTangent;
  49482. }
  49483. if (outTangent != undefined) {
  49484. keyData.outTangent = outTangent;
  49485. }
  49486. keys.push(keyData);
  49487. }
  49488. animation.setKeys(keys);
  49489. if (parsedAnimation.ranges) {
  49490. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49491. data = parsedAnimation.ranges[index];
  49492. animation.createRange(data.name, data.from, data.to);
  49493. }
  49494. }
  49495. return animation;
  49496. };
  49497. Animation.AppendSerializedAnimations = function (source, destination) {
  49498. if (source.animations) {
  49499. destination.animations = [];
  49500. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49501. var animation = source.animations[animationIndex];
  49502. destination.animations.push(animation.serialize());
  49503. }
  49504. }
  49505. };
  49506. Animation.AllowMatricesInterpolation = false;
  49507. // Statics
  49508. Animation._ANIMATIONTYPE_FLOAT = 0;
  49509. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49510. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49511. Animation._ANIMATIONTYPE_MATRIX = 3;
  49512. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49513. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49514. Animation._ANIMATIONTYPE_SIZE = 6;
  49515. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49516. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49517. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49518. return Animation;
  49519. }());
  49520. BABYLON.Animation = Animation;
  49521. })(BABYLON || (BABYLON = {}));
  49522. //# sourceMappingURL=babylon.animation.js.map
  49523. "use strict";
  49524. var BABYLON;
  49525. (function (BABYLON) {
  49526. /**
  49527. * This class defines the direct association between an animation and a target
  49528. */
  49529. var TargetedAnimation = /** @class */ (function () {
  49530. function TargetedAnimation() {
  49531. }
  49532. return TargetedAnimation;
  49533. }());
  49534. BABYLON.TargetedAnimation = TargetedAnimation;
  49535. /**
  49536. * Use this class to create coordinated animations on multiple targets
  49537. */
  49538. var AnimationGroup = /** @class */ (function () {
  49539. function AnimationGroup(name, scene) {
  49540. if (scene === void 0) { scene = null; }
  49541. this.name = name;
  49542. this._targetedAnimations = new Array();
  49543. this._animatables = new Array();
  49544. this._from = Number.MAX_VALUE;
  49545. this._to = -Number.MAX_VALUE;
  49546. this._speedRatio = 1;
  49547. this.onAnimationEndObservable = new BABYLON.Observable();
  49548. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49549. this._scene.animationGroups.push(this);
  49550. }
  49551. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  49552. /**
  49553. * Define if the animations are started
  49554. */
  49555. get: function () {
  49556. return this._isStarted;
  49557. },
  49558. enumerable: true,
  49559. configurable: true
  49560. });
  49561. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  49562. /**
  49563. * Gets or sets the speed ratio to use for all animations
  49564. */
  49565. get: function () {
  49566. return this._speedRatio;
  49567. },
  49568. /**
  49569. * Gets or sets the speed ratio to use for all animations
  49570. */
  49571. set: function (value) {
  49572. if (this._speedRatio === value) {
  49573. return;
  49574. }
  49575. this._speedRatio = value;
  49576. for (var index = 0; index < this._animatables.length; index++) {
  49577. var animatable = this._animatables[index];
  49578. animatable.speedRatio = this._speedRatio;
  49579. }
  49580. },
  49581. enumerable: true,
  49582. configurable: true
  49583. });
  49584. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  49585. /**
  49586. * Gets the targeted animations for this animation group
  49587. */
  49588. get: function () {
  49589. return this._targetedAnimations;
  49590. },
  49591. enumerable: true,
  49592. configurable: true
  49593. });
  49594. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  49595. /**
  49596. * returning the list of animatables controlled by this animation group.
  49597. */
  49598. get: function () {
  49599. return this._animatables;
  49600. },
  49601. enumerable: true,
  49602. configurable: true
  49603. });
  49604. /**
  49605. * Add an animation (with its target) in the group
  49606. * @param animation defines the animation we want to add
  49607. * @param target defines the target of the animation
  49608. * @returns the {BABYLON.TargetedAnimation} object
  49609. */
  49610. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  49611. var targetedAnimation = {
  49612. animation: animation,
  49613. target: target
  49614. };
  49615. var keys = animation.getKeys();
  49616. if (this._from > keys[0].frame) {
  49617. this._from = keys[0].frame;
  49618. }
  49619. if (this._to < keys[keys.length - 1].frame) {
  49620. this._to = keys[keys.length - 1].frame;
  49621. }
  49622. this._targetedAnimations.push(targetedAnimation);
  49623. return targetedAnimation;
  49624. };
  49625. /**
  49626. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  49627. * It can add constant keys at begin or end
  49628. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  49629. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  49630. */
  49631. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  49632. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  49633. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  49634. beginFrame = Math.max(beginFrame, this._from);
  49635. endFrame = Math.min(endFrame, this._to);
  49636. for (var index = 0; index < this._targetedAnimations.length; index++) {
  49637. var targetedAnimation = this._targetedAnimations[index];
  49638. var keys = targetedAnimation.animation.getKeys();
  49639. var startKey = keys[0];
  49640. var endKey = keys[keys.length - 1];
  49641. if (startKey.frame > beginFrame) {
  49642. var newKey = {
  49643. frame: beginFrame,
  49644. value: startKey.value,
  49645. inTangent: startKey.inTangent,
  49646. outTangent: startKey.outTangent,
  49647. interpolation: startKey.interpolation
  49648. };
  49649. keys.splice(0, 0, newKey);
  49650. }
  49651. if (endKey.frame < endFrame) {
  49652. var newKey = {
  49653. frame: endFrame,
  49654. value: endKey.value,
  49655. inTangent: endKey.outTangent,
  49656. outTangent: endKey.outTangent,
  49657. interpolation: endKey.interpolation
  49658. };
  49659. keys.push(newKey);
  49660. }
  49661. }
  49662. return this;
  49663. };
  49664. /**
  49665. * Start all animations on given targets
  49666. * @param loop defines if animations must loop
  49667. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  49668. * @param from defines the from key (optional)
  49669. * @param to defines the to key (optional)
  49670. * @returns the current animation group
  49671. */
  49672. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  49673. var _this = this;
  49674. if (loop === void 0) { loop = false; }
  49675. if (speedRatio === void 0) { speedRatio = 1; }
  49676. if (this._isStarted || this._targetedAnimations.length === 0) {
  49677. return this;
  49678. }
  49679. var _loop_1 = function () {
  49680. var targetedAnimation = this_1._targetedAnimations[index];
  49681. if (!targetedAnimation.target.animations) {
  49682. targetedAnimation.target.animations = [];
  49683. }
  49684. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  49685. targetedAnimation.target.animations.push(targetedAnimation.animation);
  49686. }
  49687. 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 () {
  49688. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  49689. }));
  49690. };
  49691. var this_1 = this;
  49692. for (var index = 0; index < this._targetedAnimations.length; index++) {
  49693. _loop_1();
  49694. }
  49695. this._speedRatio = speedRatio;
  49696. this._isStarted = true;
  49697. return this;
  49698. };
  49699. /**
  49700. * Pause all animations
  49701. */
  49702. AnimationGroup.prototype.pause = function () {
  49703. if (!this._isStarted) {
  49704. return this;
  49705. }
  49706. for (var index = 0; index < this._animatables.length; index++) {
  49707. var animatable = this._animatables[index];
  49708. animatable.pause();
  49709. }
  49710. return this;
  49711. };
  49712. /**
  49713. * Play all animations to initial state
  49714. * This function will start() the animations if they were not started or will restart() them if they were paused
  49715. * @param loop defines if animations must loop
  49716. */
  49717. AnimationGroup.prototype.play = function (loop) {
  49718. if (this.isStarted) {
  49719. if (loop !== undefined) {
  49720. for (var index = 0; index < this._animatables.length; index++) {
  49721. var animatable = this._animatables[index];
  49722. animatable.loopAnimation = loop;
  49723. }
  49724. }
  49725. this.restart();
  49726. }
  49727. else {
  49728. this.start(loop, this._speedRatio);
  49729. }
  49730. return this;
  49731. };
  49732. /**
  49733. * Reset all animations to initial state
  49734. */
  49735. AnimationGroup.prototype.reset = function () {
  49736. if (!this._isStarted) {
  49737. return this;
  49738. }
  49739. for (var index = 0; index < this._animatables.length; index++) {
  49740. var animatable = this._animatables[index];
  49741. animatable.reset();
  49742. }
  49743. return this;
  49744. };
  49745. /**
  49746. * Restart animations from key 0
  49747. */
  49748. AnimationGroup.prototype.restart = function () {
  49749. if (!this._isStarted) {
  49750. return this;
  49751. }
  49752. for (var index = 0; index < this._animatables.length; index++) {
  49753. var animatable = this._animatables[index];
  49754. animatable.restart();
  49755. }
  49756. return this;
  49757. };
  49758. /**
  49759. * Stop all animations
  49760. */
  49761. AnimationGroup.prototype.stop = function () {
  49762. if (!this._isStarted) {
  49763. return this;
  49764. }
  49765. for (var index = 0; index < this._animatables.length; index++) {
  49766. var animatable = this._animatables[index];
  49767. animatable.stop();
  49768. }
  49769. this._isStarted = false;
  49770. return this;
  49771. };
  49772. /**
  49773. * Goes to a specific frame in this animation group
  49774. *
  49775. * @param frame the frame number to go to
  49776. * @return the animationGroup
  49777. */
  49778. AnimationGroup.prototype.goToFrame = function (frame) {
  49779. if (!this._isStarted) {
  49780. return this;
  49781. }
  49782. for (var index = 0; index < this._animatables.length; index++) {
  49783. var animatable = this._animatables[index];
  49784. animatable.goToFrame(frame);
  49785. }
  49786. return this;
  49787. };
  49788. /**
  49789. * Dispose all associated resources
  49790. */
  49791. AnimationGroup.prototype.dispose = function () {
  49792. this._targetedAnimations = [];
  49793. this._animatables = [];
  49794. var index = this._scene.animationGroups.indexOf(this);
  49795. if (index > -1) {
  49796. this._scene.animationGroups.splice(index, 1);
  49797. }
  49798. };
  49799. return AnimationGroup;
  49800. }());
  49801. BABYLON.AnimationGroup = AnimationGroup;
  49802. })(BABYLON || (BABYLON = {}));
  49803. //# sourceMappingURL=babylon.animationGroup.js.map
  49804. "use strict";
  49805. var BABYLON;
  49806. (function (BABYLON) {
  49807. var RuntimeAnimation = /** @class */ (function () {
  49808. /**
  49809. * Create a new RuntimeAnimation object
  49810. * @param target defines the target of the animation
  49811. * @param animation defines the source {BABYLON.Animation} object
  49812. * @param scene defines the hosting scene
  49813. * @param host defines the initiating Animatable
  49814. */
  49815. function RuntimeAnimation(target, animation, scene, host) {
  49816. this._currentFrame = 0;
  49817. this._offsetsCache = {};
  49818. this._highLimitsCache = {};
  49819. this._stopped = false;
  49820. this._blendingFactor = 0;
  49821. this._targetPath = "";
  49822. this._weight = 1.0;
  49823. this._ratioOffset = 0;
  49824. this._previousDelay = 0;
  49825. this._previousRatio = 0;
  49826. this._animation = animation;
  49827. this._target = target;
  49828. this._scene = scene;
  49829. this._host = host;
  49830. animation._runtimeAnimations.push(this);
  49831. }
  49832. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  49833. /**
  49834. * Gets the current frame
  49835. */
  49836. get: function () {
  49837. return this._currentFrame;
  49838. },
  49839. enumerable: true,
  49840. configurable: true
  49841. });
  49842. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  49843. /**
  49844. * Gets the weight of the runtime animation
  49845. */
  49846. get: function () {
  49847. return this._weight;
  49848. },
  49849. enumerable: true,
  49850. configurable: true
  49851. });
  49852. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  49853. /**
  49854. * Gets the original value of the runtime animation
  49855. */
  49856. get: function () {
  49857. return this._originalValue;
  49858. },
  49859. enumerable: true,
  49860. configurable: true
  49861. });
  49862. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  49863. /**
  49864. * Gets the current value of the runtime animation
  49865. */
  49866. get: function () {
  49867. return this._currentValue;
  49868. },
  49869. enumerable: true,
  49870. configurable: true
  49871. });
  49872. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  49873. /**
  49874. * Gets the path where to store the animated value in the target
  49875. */
  49876. get: function () {
  49877. return this._targetPath;
  49878. },
  49879. enumerable: true,
  49880. configurable: true
  49881. });
  49882. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  49883. /**
  49884. * Gets the actual target of the runtime animation
  49885. */
  49886. get: function () {
  49887. return this._activeTarget;
  49888. },
  49889. enumerable: true,
  49890. configurable: true
  49891. });
  49892. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  49893. get: function () {
  49894. return this._animation;
  49895. },
  49896. enumerable: true,
  49897. configurable: true
  49898. });
  49899. RuntimeAnimation.prototype.reset = function () {
  49900. this._offsetsCache = {};
  49901. this._highLimitsCache = {};
  49902. this._currentFrame = 0;
  49903. this._blendingFactor = 0;
  49904. this._originalValue = null;
  49905. };
  49906. RuntimeAnimation.prototype.isStopped = function () {
  49907. return this._stopped;
  49908. };
  49909. RuntimeAnimation.prototype.dispose = function () {
  49910. var index = this._animation.runtimeAnimations.indexOf(this);
  49911. if (index > -1) {
  49912. this._animation.runtimeAnimations.splice(index, 1);
  49913. }
  49914. };
  49915. RuntimeAnimation.prototype._getKeyValue = function (value) {
  49916. if (typeof value === "function") {
  49917. return value();
  49918. }
  49919. return value;
  49920. };
  49921. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  49922. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49923. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49924. }
  49925. this._currentFrame = currentFrame;
  49926. var keys = this._animation.getKeys();
  49927. // Try to get a hash to find the right key
  49928. 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));
  49929. if (keys[startKeyIndex].frame >= currentFrame) {
  49930. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49931. startKeyIndex--;
  49932. }
  49933. }
  49934. for (var key = startKeyIndex; key < keys.length; key++) {
  49935. var endKey = keys[key + 1];
  49936. if (endKey.frame >= currentFrame) {
  49937. var startKey = keys[key];
  49938. var startValue = this._getKeyValue(startKey.value);
  49939. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  49940. return startValue;
  49941. }
  49942. var endValue = this._getKeyValue(endKey.value);
  49943. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49944. var frameDelta = endKey.frame - startKey.frame;
  49945. // gradient : percent of currentFrame between the frame inf and the frame sup
  49946. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49947. // check for easingFunction and correction of gradient
  49948. var easingFunction = this._animation.getEasingFunction();
  49949. if (easingFunction != null) {
  49950. gradient = easingFunction.ease(gradient);
  49951. }
  49952. switch (this._animation.dataType) {
  49953. // Float
  49954. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  49955. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  49956. switch (loopMode) {
  49957. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  49958. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  49959. return floatValue;
  49960. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  49961. return offsetValue * repeatCount + floatValue;
  49962. }
  49963. break;
  49964. // Quaternion
  49965. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  49966. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  49967. switch (loopMode) {
  49968. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  49969. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  49970. return quatValue;
  49971. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  49972. return quatValue.add(offsetValue.scale(repeatCount));
  49973. }
  49974. return quatValue;
  49975. // Vector3
  49976. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  49977. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  49978. switch (loopMode) {
  49979. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  49980. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  49981. return vec3Value;
  49982. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  49983. return vec3Value.add(offsetValue.scale(repeatCount));
  49984. }
  49985. // Vector2
  49986. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  49987. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  49988. switch (loopMode) {
  49989. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  49990. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  49991. return vec2Value;
  49992. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  49993. return vec2Value.add(offsetValue.scale(repeatCount));
  49994. }
  49995. // Size
  49996. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  49997. switch (loopMode) {
  49998. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  49999. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50000. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50001. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50002. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50003. }
  50004. // Color3
  50005. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50006. switch (loopMode) {
  50007. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50008. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50009. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50010. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50011. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50012. }
  50013. // Matrix
  50014. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50015. switch (loopMode) {
  50016. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50017. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50018. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50019. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  50020. }
  50021. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50022. return startValue;
  50023. }
  50024. default:
  50025. break;
  50026. }
  50027. break;
  50028. }
  50029. }
  50030. return this._getKeyValue(keys[keys.length - 1].value);
  50031. };
  50032. /**
  50033. * Affect the interpolated value to the target
  50034. * @param currentValue defines the value computed by the animation
  50035. * @param weight defines the weight to apply to this value
  50036. */
  50037. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50038. if (weight === void 0) { weight = 1.0; }
  50039. // Set value
  50040. var path;
  50041. var destination;
  50042. var targetPropertyPath = this._animation.targetPropertyPath;
  50043. if (targetPropertyPath.length > 1) {
  50044. var property = this._target[targetPropertyPath[0]];
  50045. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50046. property = property[targetPropertyPath[index]];
  50047. }
  50048. path = targetPropertyPath[targetPropertyPath.length - 1];
  50049. destination = property;
  50050. }
  50051. else {
  50052. path = targetPropertyPath[0];
  50053. destination = this._target;
  50054. }
  50055. this._targetPath = path;
  50056. this._activeTarget = destination;
  50057. this._weight = weight;
  50058. // Blending
  50059. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50060. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50061. if (enableBlending && this._blendingFactor <= 1.0) {
  50062. if (!this._originalBlendValue) {
  50063. var originalValue = destination[path];
  50064. if (originalValue.clone) {
  50065. this._originalBlendValue = originalValue.clone();
  50066. }
  50067. else {
  50068. this._originalBlendValue = originalValue;
  50069. }
  50070. }
  50071. }
  50072. if (weight !== -1.0) {
  50073. if (!this._originalValue) {
  50074. var originalValue = void 0;
  50075. if (destination.getRestPose) {
  50076. originalValue = destination.getRestPose();
  50077. }
  50078. else {
  50079. originalValue = destination[path];
  50080. }
  50081. if (originalValue.clone) {
  50082. this._originalValue = originalValue.clone();
  50083. }
  50084. else {
  50085. this._originalValue = originalValue;
  50086. }
  50087. }
  50088. }
  50089. if (enableBlending && this._blendingFactor <= 1.0) {
  50090. if (this._originalBlendValue.prototype) {
  50091. if (this._originalBlendValue.prototype.Lerp) {
  50092. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  50093. }
  50094. else {
  50095. this._currentValue = currentValue;
  50096. }
  50097. }
  50098. else if (this._originalBlendValue.m) {
  50099. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50100. }
  50101. else {
  50102. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  50103. }
  50104. this._blendingFactor += blendingSpeed;
  50105. }
  50106. else {
  50107. this._currentValue = currentValue;
  50108. }
  50109. if (weight !== -1.0) {
  50110. this._scene._registerTargetForLateAnimationBinding(this);
  50111. }
  50112. else {
  50113. destination[path] = this._currentValue;
  50114. }
  50115. if (this._target.markAsDirty) {
  50116. this._target.markAsDirty(this._animation.targetProperty);
  50117. }
  50118. };
  50119. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50120. if (this._target && this._target.animationPropertiesOverride) {
  50121. return this._target.animationPropertiesOverride.loopMode;
  50122. }
  50123. return this._animation.loopMode;
  50124. };
  50125. /**
  50126. * Move the current animation to a given frame
  50127. * @param frame defines the frame to move to
  50128. */
  50129. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50130. var keys = this._animation.getKeys();
  50131. if (frame < keys[0].frame) {
  50132. frame = keys[0].frame;
  50133. }
  50134. else if (frame > keys[keys.length - 1].frame) {
  50135. frame = keys[keys.length - 1].frame;
  50136. }
  50137. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50138. this.setValue(currentValue, -1);
  50139. };
  50140. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50141. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50142. this._ratioOffset = this._previousRatio - newRatio;
  50143. };
  50144. /**
  50145. * Execute the current animation
  50146. * @param delay defines the delay to add to the current frame
  50147. * @param from defines the lower bound of the animation range
  50148. * @param to defines the upper bound of the animation range
  50149. * @param loop defines if the current animation must loop
  50150. * @param speedRatio defines the current speed ratio
  50151. * @param weight defines the weight of the animation (default is -1 so no weight)
  50152. * @returns a boolean indicating if the animation has ended
  50153. */
  50154. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50155. if (weight === void 0) { weight = -1.0; }
  50156. var targetPropertyPath = this._animation.targetPropertyPath;
  50157. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50158. this._stopped = true;
  50159. return false;
  50160. }
  50161. var returnValue = true;
  50162. var keys = this._animation.getKeys();
  50163. // Adding a start key at frame 0 if missing
  50164. if (keys[0].frame !== 0) {
  50165. var newKey = { frame: 0, value: keys[0].value };
  50166. keys.splice(0, 0, newKey);
  50167. }
  50168. // Check limits
  50169. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50170. from = keys[0].frame;
  50171. }
  50172. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50173. to = keys[keys.length - 1].frame;
  50174. }
  50175. //to and from cannot be the same key
  50176. if (from === to) {
  50177. if (from > keys[0].frame) {
  50178. from--;
  50179. }
  50180. else if (to < keys[keys.length - 1].frame) {
  50181. to++;
  50182. }
  50183. }
  50184. // Compute ratio
  50185. var range = to - from;
  50186. var offsetValue;
  50187. // ratio represents the frame delta between from and to
  50188. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50189. var highLimitValue = 0;
  50190. this._previousDelay = delay;
  50191. this._previousRatio = ratio;
  50192. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  50193. returnValue = false;
  50194. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  50195. }
  50196. else {
  50197. // Get max value if required
  50198. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50199. var keyOffset = to.toString() + from.toString();
  50200. if (!this._offsetsCache[keyOffset]) {
  50201. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50202. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50203. switch (this._animation.dataType) {
  50204. // Float
  50205. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50206. this._offsetsCache[keyOffset] = toValue - fromValue;
  50207. break;
  50208. // Quaternion
  50209. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50210. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50211. break;
  50212. // Vector3
  50213. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50214. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50215. // Vector2
  50216. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50217. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50218. // Size
  50219. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50220. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50221. // Color3
  50222. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50223. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50224. default:
  50225. break;
  50226. }
  50227. this._highLimitsCache[keyOffset] = toValue;
  50228. }
  50229. highLimitValue = this._highLimitsCache[keyOffset];
  50230. offsetValue = this._offsetsCache[keyOffset];
  50231. }
  50232. }
  50233. if (offsetValue === undefined) {
  50234. switch (this._animation.dataType) {
  50235. // Float
  50236. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50237. offsetValue = 0;
  50238. break;
  50239. // Quaternion
  50240. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50241. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50242. break;
  50243. // Vector3
  50244. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50245. offsetValue = BABYLON.Vector3.Zero();
  50246. break;
  50247. // Vector2
  50248. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50249. offsetValue = BABYLON.Vector2.Zero();
  50250. break;
  50251. // Size
  50252. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50253. offsetValue = BABYLON.Size.Zero();
  50254. break;
  50255. // Color3
  50256. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50257. offsetValue = BABYLON.Color3.Black();
  50258. }
  50259. }
  50260. // Compute value
  50261. var repeatCount = (ratio / range) >> 0;
  50262. var currentFrame = returnValue ? from + ratio % range : to;
  50263. // Need to normalize?
  50264. if (this._host && this._host.syncRoot) {
  50265. var syncRoot = this._host.syncRoot;
  50266. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50267. currentFrame = from + (to - from) * hostNormalizedFrame;
  50268. }
  50269. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50270. // Set value
  50271. this.setValue(currentValue, weight);
  50272. // Check events
  50273. var events = this._animation.getEvents();
  50274. for (var index = 0; index < events.length; index++) {
  50275. // Make sure current frame has passed event frame and that event frame is within the current range
  50276. // Also, handle both forward and reverse animations
  50277. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50278. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50279. var event = events[index];
  50280. if (!event.isDone) {
  50281. // If event should be done only once, remove it.
  50282. if (event.onlyOnce) {
  50283. events.splice(index, 1);
  50284. index--;
  50285. }
  50286. event.isDone = true;
  50287. event.action();
  50288. } // Don't do anything if the event has already be done.
  50289. }
  50290. else if (events[index].isDone && !events[index].onlyOnce) {
  50291. // reset event, the animation is looping
  50292. events[index].isDone = false;
  50293. }
  50294. }
  50295. if (!returnValue) {
  50296. this._stopped = true;
  50297. }
  50298. return returnValue;
  50299. };
  50300. return RuntimeAnimation;
  50301. }());
  50302. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50303. })(BABYLON || (BABYLON = {}));
  50304. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50305. "use strict";
  50306. var BABYLON;
  50307. (function (BABYLON) {
  50308. var Animatable = /** @class */ (function () {
  50309. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  50310. if (fromFrame === void 0) { fromFrame = 0; }
  50311. if (toFrame === void 0) { toFrame = 100; }
  50312. if (loopAnimation === void 0) { loopAnimation = false; }
  50313. if (speedRatio === void 0) { speedRatio = 1.0; }
  50314. this.target = target;
  50315. this.fromFrame = fromFrame;
  50316. this.toFrame = toFrame;
  50317. this.loopAnimation = loopAnimation;
  50318. this.onAnimationEnd = onAnimationEnd;
  50319. this._localDelayOffset = null;
  50320. this._pausedDelay = null;
  50321. this._runtimeAnimations = new Array();
  50322. this._paused = false;
  50323. this._speedRatio = 1;
  50324. this._weight = -1.0;
  50325. this.animationStarted = false;
  50326. if (animations) {
  50327. this.appendAnimations(target, animations);
  50328. }
  50329. this._speedRatio = speedRatio;
  50330. this._scene = scene;
  50331. scene._activeAnimatables.push(this);
  50332. }
  50333. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50334. /**
  50335. * Gets the root Animatable used to synchronize and normalize animations
  50336. */
  50337. get: function () {
  50338. return this._syncRoot;
  50339. },
  50340. enumerable: true,
  50341. configurable: true
  50342. });
  50343. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50344. /**
  50345. * Gets the current frame of the first RuntimeAnimation
  50346. * Used to synchronize Animatables
  50347. */
  50348. get: function () {
  50349. if (this._runtimeAnimations.length === 0) {
  50350. return 0;
  50351. }
  50352. return this._runtimeAnimations[0].currentFrame;
  50353. },
  50354. enumerable: true,
  50355. configurable: true
  50356. });
  50357. Object.defineProperty(Animatable.prototype, "weight", {
  50358. /**
  50359. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50360. */
  50361. get: function () {
  50362. return this._weight;
  50363. },
  50364. set: function (value) {
  50365. if (value === -1) {
  50366. this._weight = -1;
  50367. return;
  50368. }
  50369. // Else weight must be in [0, 1] range
  50370. this._weight = Math.min(Math.max(value, 0), 1.0);
  50371. },
  50372. enumerable: true,
  50373. configurable: true
  50374. });
  50375. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50376. /**
  50377. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50378. */
  50379. get: function () {
  50380. return this._speedRatio;
  50381. },
  50382. set: function (value) {
  50383. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50384. var animation = this._runtimeAnimations[index];
  50385. animation._prepareForSpeedRatioChange(value);
  50386. }
  50387. this._speedRatio = value;
  50388. },
  50389. enumerable: true,
  50390. configurable: true
  50391. });
  50392. // Methods
  50393. /**
  50394. * Synchronize and normalize current Animatable with a source Animatable.
  50395. * This is useful when using animation weights and when animations are not of the same length
  50396. * @param root defines the root Animatable to synchronize with
  50397. * @returns the current Animatable
  50398. */
  50399. Animatable.prototype.syncWith = function (root) {
  50400. this._syncRoot = root;
  50401. if (root) {
  50402. // Make sure this animatable will animate after the root
  50403. var index = this._scene._activeAnimatables.indexOf(this);
  50404. if (index > -1) {
  50405. this._scene._activeAnimatables.splice(index, 1);
  50406. this._scene._activeAnimatables.push(this);
  50407. }
  50408. }
  50409. return this;
  50410. };
  50411. Animatable.prototype.getAnimations = function () {
  50412. return this._runtimeAnimations;
  50413. };
  50414. Animatable.prototype.appendAnimations = function (target, animations) {
  50415. for (var index = 0; index < animations.length; index++) {
  50416. var animation = animations[index];
  50417. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50418. }
  50419. };
  50420. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50421. var runtimeAnimations = this._runtimeAnimations;
  50422. for (var index = 0; index < runtimeAnimations.length; index++) {
  50423. if (runtimeAnimations[index].animation.targetProperty === property) {
  50424. return runtimeAnimations[index].animation;
  50425. }
  50426. }
  50427. return null;
  50428. };
  50429. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50430. var runtimeAnimations = this._runtimeAnimations;
  50431. for (var index = 0; index < runtimeAnimations.length; index++) {
  50432. if (runtimeAnimations[index].animation.targetProperty === property) {
  50433. return runtimeAnimations[index];
  50434. }
  50435. }
  50436. return null;
  50437. };
  50438. Animatable.prototype.reset = function () {
  50439. var runtimeAnimations = this._runtimeAnimations;
  50440. for (var index = 0; index < runtimeAnimations.length; index++) {
  50441. runtimeAnimations[index].reset();
  50442. }
  50443. // Reset to original value
  50444. for (index = 0; index < runtimeAnimations.length; index++) {
  50445. var animation = runtimeAnimations[index];
  50446. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  50447. }
  50448. this._localDelayOffset = null;
  50449. this._pausedDelay = null;
  50450. };
  50451. Animatable.prototype.enableBlending = function (blendingSpeed) {
  50452. var runtimeAnimations = this._runtimeAnimations;
  50453. for (var index = 0; index < runtimeAnimations.length; index++) {
  50454. runtimeAnimations[index].animation.enableBlending = true;
  50455. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  50456. }
  50457. };
  50458. Animatable.prototype.disableBlending = function () {
  50459. var runtimeAnimations = this._runtimeAnimations;
  50460. for (var index = 0; index < runtimeAnimations.length; index++) {
  50461. runtimeAnimations[index].animation.enableBlending = false;
  50462. }
  50463. };
  50464. Animatable.prototype.goToFrame = function (frame) {
  50465. var runtimeAnimations = this._runtimeAnimations;
  50466. if (runtimeAnimations[0]) {
  50467. var fps = runtimeAnimations[0].animation.framePerSecond;
  50468. var currentFrame = runtimeAnimations[0].currentFrame;
  50469. var adjustTime = frame - currentFrame;
  50470. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  50471. if (this._localDelayOffset === null) {
  50472. this._localDelayOffset = 0;
  50473. }
  50474. this._localDelayOffset -= delay;
  50475. }
  50476. for (var index = 0; index < runtimeAnimations.length; index++) {
  50477. runtimeAnimations[index].goToFrame(frame);
  50478. }
  50479. };
  50480. Animatable.prototype.pause = function () {
  50481. if (this._paused) {
  50482. return;
  50483. }
  50484. this._paused = true;
  50485. };
  50486. Animatable.prototype.restart = function () {
  50487. this._paused = false;
  50488. };
  50489. Animatable.prototype.stop = function (animationName) {
  50490. if (animationName) {
  50491. var idx = this._scene._activeAnimatables.indexOf(this);
  50492. if (idx > -1) {
  50493. var runtimeAnimations = this._runtimeAnimations;
  50494. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  50495. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  50496. continue;
  50497. }
  50498. runtimeAnimations[index].dispose();
  50499. runtimeAnimations.splice(index, 1);
  50500. }
  50501. if (runtimeAnimations.length == 0) {
  50502. this._scene._activeAnimatables.splice(idx, 1);
  50503. if (this.onAnimationEnd) {
  50504. this.onAnimationEnd();
  50505. }
  50506. }
  50507. }
  50508. }
  50509. else {
  50510. var index = this._scene._activeAnimatables.indexOf(this);
  50511. if (index > -1) {
  50512. this._scene._activeAnimatables.splice(index, 1);
  50513. var runtimeAnimations = this._runtimeAnimations;
  50514. for (var index = 0; index < runtimeAnimations.length; index++) {
  50515. runtimeAnimations[index].dispose();
  50516. }
  50517. if (this.onAnimationEnd) {
  50518. this.onAnimationEnd();
  50519. }
  50520. }
  50521. }
  50522. };
  50523. Animatable.prototype._animate = function (delay) {
  50524. if (this._paused) {
  50525. this.animationStarted = false;
  50526. if (this._pausedDelay === null) {
  50527. this._pausedDelay = delay;
  50528. }
  50529. return true;
  50530. }
  50531. if (this._localDelayOffset === null) {
  50532. this._localDelayOffset = delay;
  50533. this._pausedDelay = null;
  50534. }
  50535. else if (this._pausedDelay !== null) {
  50536. this._localDelayOffset += delay - this._pausedDelay;
  50537. this._pausedDelay = null;
  50538. }
  50539. if (this._weight === 0) {
  50540. return true;
  50541. }
  50542. // Animating
  50543. var running = false;
  50544. var runtimeAnimations = this._runtimeAnimations;
  50545. var index;
  50546. for (index = 0; index < runtimeAnimations.length; index++) {
  50547. var animation = runtimeAnimations[index];
  50548. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  50549. running = running || isRunning;
  50550. }
  50551. this.animationStarted = running;
  50552. if (!running) {
  50553. // Remove from active animatables
  50554. index = this._scene._activeAnimatables.indexOf(this);
  50555. this._scene._activeAnimatables.splice(index, 1);
  50556. // Dispose all runtime animations
  50557. for (index = 0; index < runtimeAnimations.length; index++) {
  50558. runtimeAnimations[index].dispose();
  50559. }
  50560. }
  50561. if (!running && this.onAnimationEnd) {
  50562. this.onAnimationEnd();
  50563. this.onAnimationEnd = null;
  50564. }
  50565. return running;
  50566. };
  50567. return Animatable;
  50568. }());
  50569. BABYLON.Animatable = Animatable;
  50570. })(BABYLON || (BABYLON = {}));
  50571. //# sourceMappingURL=babylon.animatable.js.map
  50572. "use strict";
  50573. var BABYLON;
  50574. (function (BABYLON) {
  50575. var EasingFunction = /** @class */ (function () {
  50576. function EasingFunction() {
  50577. // Properties
  50578. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  50579. }
  50580. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  50581. get: function () {
  50582. return EasingFunction._EASINGMODE_EASEIN;
  50583. },
  50584. enumerable: true,
  50585. configurable: true
  50586. });
  50587. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  50588. get: function () {
  50589. return EasingFunction._EASINGMODE_EASEOUT;
  50590. },
  50591. enumerable: true,
  50592. configurable: true
  50593. });
  50594. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  50595. get: function () {
  50596. return EasingFunction._EASINGMODE_EASEINOUT;
  50597. },
  50598. enumerable: true,
  50599. configurable: true
  50600. });
  50601. EasingFunction.prototype.setEasingMode = function (easingMode) {
  50602. var n = Math.min(Math.max(easingMode, 0), 2);
  50603. this._easingMode = n;
  50604. };
  50605. EasingFunction.prototype.getEasingMode = function () {
  50606. return this._easingMode;
  50607. };
  50608. EasingFunction.prototype.easeInCore = function (gradient) {
  50609. throw new Error('You must implement this method');
  50610. };
  50611. EasingFunction.prototype.ease = function (gradient) {
  50612. switch (this._easingMode) {
  50613. case EasingFunction.EASINGMODE_EASEIN:
  50614. return this.easeInCore(gradient);
  50615. case EasingFunction.EASINGMODE_EASEOUT:
  50616. return (1 - this.easeInCore(1 - gradient));
  50617. }
  50618. if (gradient >= 0.5) {
  50619. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  50620. }
  50621. return (this.easeInCore(gradient * 2) * 0.5);
  50622. };
  50623. //Statics
  50624. EasingFunction._EASINGMODE_EASEIN = 0;
  50625. EasingFunction._EASINGMODE_EASEOUT = 1;
  50626. EasingFunction._EASINGMODE_EASEINOUT = 2;
  50627. return EasingFunction;
  50628. }());
  50629. BABYLON.EasingFunction = EasingFunction;
  50630. var CircleEase = /** @class */ (function (_super) {
  50631. __extends(CircleEase, _super);
  50632. function CircleEase() {
  50633. return _super !== null && _super.apply(this, arguments) || this;
  50634. }
  50635. CircleEase.prototype.easeInCore = function (gradient) {
  50636. gradient = Math.max(0, Math.min(1, gradient));
  50637. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  50638. };
  50639. return CircleEase;
  50640. }(EasingFunction));
  50641. BABYLON.CircleEase = CircleEase;
  50642. var BackEase = /** @class */ (function (_super) {
  50643. __extends(BackEase, _super);
  50644. function BackEase(amplitude) {
  50645. if (amplitude === void 0) { amplitude = 1; }
  50646. var _this = _super.call(this) || this;
  50647. _this.amplitude = amplitude;
  50648. return _this;
  50649. }
  50650. BackEase.prototype.easeInCore = function (gradient) {
  50651. var num = Math.max(0, this.amplitude);
  50652. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  50653. };
  50654. return BackEase;
  50655. }(EasingFunction));
  50656. BABYLON.BackEase = BackEase;
  50657. var BounceEase = /** @class */ (function (_super) {
  50658. __extends(BounceEase, _super);
  50659. function BounceEase(bounces, bounciness) {
  50660. if (bounces === void 0) { bounces = 3; }
  50661. if (bounciness === void 0) { bounciness = 2; }
  50662. var _this = _super.call(this) || this;
  50663. _this.bounces = bounces;
  50664. _this.bounciness = bounciness;
  50665. return _this;
  50666. }
  50667. BounceEase.prototype.easeInCore = function (gradient) {
  50668. var y = Math.max(0.0, this.bounces);
  50669. var bounciness = this.bounciness;
  50670. if (bounciness <= 1.0) {
  50671. bounciness = 1.001;
  50672. }
  50673. var num9 = Math.pow(bounciness, y);
  50674. var num5 = 1.0 - bounciness;
  50675. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  50676. var num15 = gradient * num4;
  50677. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  50678. var num3 = Math.floor(num65);
  50679. var num13 = num3 + 1.0;
  50680. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  50681. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  50682. var num7 = (num8 + num12) * 0.5;
  50683. var num6 = gradient - num7;
  50684. var num2 = num7 - num8;
  50685. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  50686. };
  50687. return BounceEase;
  50688. }(EasingFunction));
  50689. BABYLON.BounceEase = BounceEase;
  50690. var CubicEase = /** @class */ (function (_super) {
  50691. __extends(CubicEase, _super);
  50692. function CubicEase() {
  50693. return _super !== null && _super.apply(this, arguments) || this;
  50694. }
  50695. CubicEase.prototype.easeInCore = function (gradient) {
  50696. return (gradient * gradient * gradient);
  50697. };
  50698. return CubicEase;
  50699. }(EasingFunction));
  50700. BABYLON.CubicEase = CubicEase;
  50701. var ElasticEase = /** @class */ (function (_super) {
  50702. __extends(ElasticEase, _super);
  50703. function ElasticEase(oscillations, springiness) {
  50704. if (oscillations === void 0) { oscillations = 3; }
  50705. if (springiness === void 0) { springiness = 3; }
  50706. var _this = _super.call(this) || this;
  50707. _this.oscillations = oscillations;
  50708. _this.springiness = springiness;
  50709. return _this;
  50710. }
  50711. ElasticEase.prototype.easeInCore = function (gradient) {
  50712. var num2;
  50713. var num3 = Math.max(0.0, this.oscillations);
  50714. var num = Math.max(0.0, this.springiness);
  50715. if (num == 0) {
  50716. num2 = gradient;
  50717. }
  50718. else {
  50719. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  50720. }
  50721. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  50722. };
  50723. return ElasticEase;
  50724. }(EasingFunction));
  50725. BABYLON.ElasticEase = ElasticEase;
  50726. var ExponentialEase = /** @class */ (function (_super) {
  50727. __extends(ExponentialEase, _super);
  50728. function ExponentialEase(exponent) {
  50729. if (exponent === void 0) { exponent = 2; }
  50730. var _this = _super.call(this) || this;
  50731. _this.exponent = exponent;
  50732. return _this;
  50733. }
  50734. ExponentialEase.prototype.easeInCore = function (gradient) {
  50735. if (this.exponent <= 0) {
  50736. return gradient;
  50737. }
  50738. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  50739. };
  50740. return ExponentialEase;
  50741. }(EasingFunction));
  50742. BABYLON.ExponentialEase = ExponentialEase;
  50743. var PowerEase = /** @class */ (function (_super) {
  50744. __extends(PowerEase, _super);
  50745. function PowerEase(power) {
  50746. if (power === void 0) { power = 2; }
  50747. var _this = _super.call(this) || this;
  50748. _this.power = power;
  50749. return _this;
  50750. }
  50751. PowerEase.prototype.easeInCore = function (gradient) {
  50752. var y = Math.max(0.0, this.power);
  50753. return Math.pow(gradient, y);
  50754. };
  50755. return PowerEase;
  50756. }(EasingFunction));
  50757. BABYLON.PowerEase = PowerEase;
  50758. var QuadraticEase = /** @class */ (function (_super) {
  50759. __extends(QuadraticEase, _super);
  50760. function QuadraticEase() {
  50761. return _super !== null && _super.apply(this, arguments) || this;
  50762. }
  50763. QuadraticEase.prototype.easeInCore = function (gradient) {
  50764. return (gradient * gradient);
  50765. };
  50766. return QuadraticEase;
  50767. }(EasingFunction));
  50768. BABYLON.QuadraticEase = QuadraticEase;
  50769. var QuarticEase = /** @class */ (function (_super) {
  50770. __extends(QuarticEase, _super);
  50771. function QuarticEase() {
  50772. return _super !== null && _super.apply(this, arguments) || this;
  50773. }
  50774. QuarticEase.prototype.easeInCore = function (gradient) {
  50775. return (gradient * gradient * gradient * gradient);
  50776. };
  50777. return QuarticEase;
  50778. }(EasingFunction));
  50779. BABYLON.QuarticEase = QuarticEase;
  50780. var QuinticEase = /** @class */ (function (_super) {
  50781. __extends(QuinticEase, _super);
  50782. function QuinticEase() {
  50783. return _super !== null && _super.apply(this, arguments) || this;
  50784. }
  50785. QuinticEase.prototype.easeInCore = function (gradient) {
  50786. return (gradient * gradient * gradient * gradient * gradient);
  50787. };
  50788. return QuinticEase;
  50789. }(EasingFunction));
  50790. BABYLON.QuinticEase = QuinticEase;
  50791. var SineEase = /** @class */ (function (_super) {
  50792. __extends(SineEase, _super);
  50793. function SineEase() {
  50794. return _super !== null && _super.apply(this, arguments) || this;
  50795. }
  50796. SineEase.prototype.easeInCore = function (gradient) {
  50797. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  50798. };
  50799. return SineEase;
  50800. }(EasingFunction));
  50801. BABYLON.SineEase = SineEase;
  50802. var BezierCurveEase = /** @class */ (function (_super) {
  50803. __extends(BezierCurveEase, _super);
  50804. function BezierCurveEase(x1, y1, x2, y2) {
  50805. if (x1 === void 0) { x1 = 0; }
  50806. if (y1 === void 0) { y1 = 0; }
  50807. if (x2 === void 0) { x2 = 1; }
  50808. if (y2 === void 0) { y2 = 1; }
  50809. var _this = _super.call(this) || this;
  50810. _this.x1 = x1;
  50811. _this.y1 = y1;
  50812. _this.x2 = x2;
  50813. _this.y2 = y2;
  50814. return _this;
  50815. }
  50816. BezierCurveEase.prototype.easeInCore = function (gradient) {
  50817. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  50818. };
  50819. return BezierCurveEase;
  50820. }(EasingFunction));
  50821. BABYLON.BezierCurveEase = BezierCurveEase;
  50822. })(BABYLON || (BABYLON = {}));
  50823. //# sourceMappingURL=babylon.easing.js.map
  50824. "use strict";
  50825. var BABYLON;
  50826. (function (BABYLON) {
  50827. /**
  50828. * A Condition applied to an Action
  50829. */
  50830. var Condition = /** @class */ (function () {
  50831. /**
  50832. * Creates a new Condition
  50833. * @param actionManager the manager of the action the condition is applied to
  50834. */
  50835. function Condition(actionManager) {
  50836. this._actionManager = actionManager;
  50837. }
  50838. /**
  50839. * Check if the current condition is valid
  50840. * @returns a boolean
  50841. */
  50842. Condition.prototype.isValid = function () {
  50843. return true;
  50844. };
  50845. /**
  50846. * Internal only
  50847. * @ignore
  50848. */
  50849. Condition.prototype._getProperty = function (propertyPath) {
  50850. return this._actionManager._getProperty(propertyPath);
  50851. };
  50852. /**
  50853. * Internal only
  50854. * @ignore
  50855. */
  50856. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  50857. return this._actionManager._getEffectiveTarget(target, propertyPath);
  50858. };
  50859. /**
  50860. * Serialize placeholder for child classes
  50861. * @returns the serialized object
  50862. */
  50863. Condition.prototype.serialize = function () {
  50864. };
  50865. /**
  50866. * Internal only
  50867. * @ignore
  50868. */
  50869. Condition.prototype._serialize = function (serializedCondition) {
  50870. return {
  50871. type: 2,
  50872. children: [],
  50873. name: serializedCondition.name,
  50874. properties: serializedCondition.properties
  50875. };
  50876. };
  50877. return Condition;
  50878. }());
  50879. BABYLON.Condition = Condition;
  50880. /**
  50881. * Defines specific conditional operators as extensions of Condition
  50882. */
  50883. var ValueCondition = /** @class */ (function (_super) {
  50884. __extends(ValueCondition, _super);
  50885. /**
  50886. * Creates a new ValueCondition
  50887. * @param actionManager manager for the action the condition applies to
  50888. * @param target for the action
  50889. * @param propertyPath path to specify the property of the target the conditional operator uses
  50890. * @param value the vale compared by the conditional operator against the current value of the property
  50891. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  50892. */
  50893. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  50894. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  50895. var _this = _super.call(this, actionManager) || this;
  50896. _this.propertyPath = propertyPath;
  50897. _this.value = value;
  50898. _this.operator = operator;
  50899. _this._target = target;
  50900. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  50901. _this._property = _this._getProperty(_this.propertyPath);
  50902. return _this;
  50903. }
  50904. Object.defineProperty(ValueCondition, "IsEqual", {
  50905. /**
  50906. * returns the number for IsEqual
  50907. */
  50908. get: function () {
  50909. return ValueCondition._IsEqual;
  50910. },
  50911. enumerable: true,
  50912. configurable: true
  50913. });
  50914. Object.defineProperty(ValueCondition, "IsDifferent", {
  50915. /**
  50916. * Returns the number for IsDifferent
  50917. */
  50918. get: function () {
  50919. return ValueCondition._IsDifferent;
  50920. },
  50921. enumerable: true,
  50922. configurable: true
  50923. });
  50924. Object.defineProperty(ValueCondition, "IsGreater", {
  50925. /**
  50926. * Returns the number for IsGreater
  50927. */
  50928. get: function () {
  50929. return ValueCondition._IsGreater;
  50930. },
  50931. enumerable: true,
  50932. configurable: true
  50933. });
  50934. Object.defineProperty(ValueCondition, "IsLesser", {
  50935. /**
  50936. * Returns the number for IsLesser
  50937. */
  50938. get: function () {
  50939. return ValueCondition._IsLesser;
  50940. },
  50941. enumerable: true,
  50942. configurable: true
  50943. });
  50944. /**
  50945. * Compares the given value with the property value for the specified conditional operator
  50946. * @returns the result of the comparison
  50947. */
  50948. ValueCondition.prototype.isValid = function () {
  50949. switch (this.operator) {
  50950. case ValueCondition.IsGreater:
  50951. return this._effectiveTarget[this._property] > this.value;
  50952. case ValueCondition.IsLesser:
  50953. return this._effectiveTarget[this._property] < this.value;
  50954. case ValueCondition.IsEqual:
  50955. case ValueCondition.IsDifferent:
  50956. var check;
  50957. if (this.value.equals) {
  50958. check = this.value.equals(this._effectiveTarget[this._property]);
  50959. }
  50960. else {
  50961. check = this.value === this._effectiveTarget[this._property];
  50962. }
  50963. return this.operator === ValueCondition.IsEqual ? check : !check;
  50964. }
  50965. return false;
  50966. };
  50967. /**
  50968. * Serialize the ValueCondition into a JSON compatible object
  50969. * @returns serialization object
  50970. */
  50971. ValueCondition.prototype.serialize = function () {
  50972. return this._serialize({
  50973. name: "ValueCondition",
  50974. properties: [
  50975. BABYLON.Action._GetTargetProperty(this._target),
  50976. { name: "propertyPath", value: this.propertyPath },
  50977. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  50978. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  50979. ]
  50980. });
  50981. };
  50982. /**
  50983. * Gets the name of the conditional operator for the ValueCondition
  50984. * @param operator the conditional operator
  50985. * @returns the name
  50986. */
  50987. ValueCondition.GetOperatorName = function (operator) {
  50988. switch (operator) {
  50989. case ValueCondition._IsEqual: return "IsEqual";
  50990. case ValueCondition._IsDifferent: return "IsDifferent";
  50991. case ValueCondition._IsGreater: return "IsGreater";
  50992. case ValueCondition._IsLesser: return "IsLesser";
  50993. default: return "";
  50994. }
  50995. };
  50996. /**
  50997. * Internal only
  50998. * @ignore
  50999. */
  51000. ValueCondition._IsEqual = 0;
  51001. /**
  51002. * Internal only
  51003. * @ignore
  51004. */
  51005. ValueCondition._IsDifferent = 1;
  51006. /**
  51007. * Internal only
  51008. * @ignore
  51009. */
  51010. ValueCondition._IsGreater = 2;
  51011. /**
  51012. * Internal only
  51013. * @ignore
  51014. */
  51015. ValueCondition._IsLesser = 3;
  51016. return ValueCondition;
  51017. }(Condition));
  51018. BABYLON.ValueCondition = ValueCondition;
  51019. /**
  51020. * Defines a predicate condition as an extension of Condition
  51021. */
  51022. var PredicateCondition = /** @class */ (function (_super) {
  51023. __extends(PredicateCondition, _super);
  51024. /**
  51025. * Creates a new {BABYLON.PredicateCondition}
  51026. * @param actionManager manager for the action the condition applies to
  51027. * @param predicate
  51028. */
  51029. function PredicateCondition(actionManager, predicate) {
  51030. var _this = _super.call(this, actionManager) || this;
  51031. _this.predicate = predicate;
  51032. return _this;
  51033. }
  51034. /**
  51035. * @returns the validity of the predicate condition
  51036. */
  51037. PredicateCondition.prototype.isValid = function () {
  51038. return this.predicate();
  51039. };
  51040. return PredicateCondition;
  51041. }(Condition));
  51042. BABYLON.PredicateCondition = PredicateCondition;
  51043. /**
  51044. * Defines a state condition as an extension of {BABYLON.Condition}
  51045. */
  51046. var StateCondition = /** @class */ (function (_super) {
  51047. __extends(StateCondition, _super);
  51048. /**
  51049. * Creates a new {BABYLON.StateCondition}
  51050. * @param actionManager manager for the action the condition applies to
  51051. * @param target of the condition
  51052. * @param value to compare with target state
  51053. */
  51054. function StateCondition(actionManager, target, value) {
  51055. var _this = _super.call(this, actionManager) || this;
  51056. _this.value = value;
  51057. _this._target = target;
  51058. return _this;
  51059. }
  51060. /**
  51061. * @returns the validity of the state
  51062. */
  51063. StateCondition.prototype.isValid = function () {
  51064. return this._target.state === this.value;
  51065. };
  51066. /**
  51067. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51068. * @returns serialization object
  51069. */
  51070. StateCondition.prototype.serialize = function () {
  51071. return this._serialize({
  51072. name: "StateCondition",
  51073. properties: [
  51074. BABYLON.Action._GetTargetProperty(this._target),
  51075. { name: "value", value: this.value }
  51076. ]
  51077. });
  51078. };
  51079. return StateCondition;
  51080. }(Condition));
  51081. BABYLON.StateCondition = StateCondition;
  51082. })(BABYLON || (BABYLON = {}));
  51083. //# sourceMappingURL=babylon.condition.js.map
  51084. "use strict";
  51085. var BABYLON;
  51086. (function (BABYLON) {
  51087. /**
  51088. * The action to be carried out following a trigger
  51089. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51090. */
  51091. var Action = /** @class */ (function () {
  51092. /**
  51093. * Creates a new Action
  51094. * @param triggerOptions the trigger, with or without parameters, for the action
  51095. * @param condition an optional determinant of action
  51096. */
  51097. function Action(triggerOptions, condition) {
  51098. this.triggerOptions = triggerOptions;
  51099. /**
  51100. * An event triggered prior to action being executed.
  51101. */
  51102. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51103. if (triggerOptions.parameter) {
  51104. this.trigger = triggerOptions.trigger;
  51105. this._triggerParameter = triggerOptions.parameter;
  51106. }
  51107. else {
  51108. this.trigger = triggerOptions;
  51109. }
  51110. this._nextActiveAction = this;
  51111. this._condition = condition;
  51112. }
  51113. /**
  51114. * Internal only
  51115. * @ignore
  51116. */
  51117. Action.prototype._prepare = function () {
  51118. };
  51119. /**
  51120. * Gets the trigger parameters
  51121. * @returns the trigger parameters
  51122. */
  51123. Action.prototype.getTriggerParameter = function () {
  51124. return this._triggerParameter;
  51125. };
  51126. /**
  51127. * Internal only - executes current action event
  51128. * @ignore
  51129. */
  51130. Action.prototype._executeCurrent = function (evt) {
  51131. if (this._nextActiveAction._condition) {
  51132. var condition = this._nextActiveAction._condition;
  51133. var currentRenderId = this._actionManager.getScene().getRenderId();
  51134. // We cache the current evaluation for the current frame
  51135. if (condition._evaluationId === currentRenderId) {
  51136. if (!condition._currentResult) {
  51137. return;
  51138. }
  51139. }
  51140. else {
  51141. condition._evaluationId = currentRenderId;
  51142. if (!condition.isValid()) {
  51143. condition._currentResult = false;
  51144. return;
  51145. }
  51146. condition._currentResult = true;
  51147. }
  51148. }
  51149. this.onBeforeExecuteObservable.notifyObservers(this);
  51150. this._nextActiveAction.execute(evt);
  51151. this.skipToNextActiveAction();
  51152. };
  51153. /**
  51154. * Execute placeholder for child classes
  51155. * @param evt optional action event
  51156. */
  51157. Action.prototype.execute = function (evt) {
  51158. };
  51159. /**
  51160. * Skips to next active action
  51161. */
  51162. Action.prototype.skipToNextActiveAction = function () {
  51163. if (this._nextActiveAction._child) {
  51164. if (!this._nextActiveAction._child._actionManager) {
  51165. this._nextActiveAction._child._actionManager = this._actionManager;
  51166. }
  51167. this._nextActiveAction = this._nextActiveAction._child;
  51168. }
  51169. else {
  51170. this._nextActiveAction = this;
  51171. }
  51172. };
  51173. /**
  51174. * Adds action to chain of actions, may be a DoNothingAction
  51175. * @param index The index of the attribute.
  51176. * @returns The action passed in
  51177. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51178. */
  51179. Action.prototype.then = function (action) {
  51180. this._child = action;
  51181. action._actionManager = this._actionManager;
  51182. action._prepare();
  51183. return action;
  51184. };
  51185. /**
  51186. * Internal only
  51187. * @ignore
  51188. */
  51189. Action.prototype._getProperty = function (propertyPath) {
  51190. return this._actionManager._getProperty(propertyPath);
  51191. };
  51192. /**
  51193. * Internal only
  51194. * @ignore
  51195. */
  51196. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51197. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51198. };
  51199. /**
  51200. * Serialize placeholder for child classes
  51201. * @param parent of child
  51202. * @returns the serialized object
  51203. */
  51204. Action.prototype.serialize = function (parent) {
  51205. };
  51206. /**
  51207. * Internal only called by serialize
  51208. * @ignore
  51209. */
  51210. Action.prototype._serialize = function (serializedAction, parent) {
  51211. var serializationObject = {
  51212. type: 1,
  51213. children: [],
  51214. name: serializedAction.name,
  51215. properties: serializedAction.properties || []
  51216. };
  51217. // Serialize child
  51218. if (this._child) {
  51219. this._child.serialize(serializationObject);
  51220. }
  51221. // Check if "this" has a condition
  51222. if (this._condition) {
  51223. var serializedCondition = this._condition.serialize();
  51224. serializedCondition.children.push(serializationObject);
  51225. if (parent) {
  51226. parent.children.push(serializedCondition);
  51227. }
  51228. return serializedCondition;
  51229. }
  51230. if (parent) {
  51231. parent.children.push(serializationObject);
  51232. }
  51233. return serializationObject;
  51234. };
  51235. /**
  51236. * Internal only
  51237. * @ignore
  51238. */
  51239. Action._SerializeValueAsString = function (value) {
  51240. if (typeof value === "number") {
  51241. return value.toString();
  51242. }
  51243. if (typeof value === "boolean") {
  51244. return value ? "true" : "false";
  51245. }
  51246. if (value instanceof BABYLON.Vector2) {
  51247. return value.x + ", " + value.y;
  51248. }
  51249. if (value instanceof BABYLON.Vector3) {
  51250. return value.x + ", " + value.y + ", " + value.z;
  51251. }
  51252. if (value instanceof BABYLON.Color3) {
  51253. return value.r + ", " + value.g + ", " + value.b;
  51254. }
  51255. if (value instanceof BABYLON.Color4) {
  51256. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51257. }
  51258. return value; // string
  51259. };
  51260. /**
  51261. * Internal only
  51262. * @ignore
  51263. */
  51264. Action._GetTargetProperty = function (target) {
  51265. return {
  51266. name: "target",
  51267. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51268. : target instanceof BABYLON.Light ? "LightProperties"
  51269. : target instanceof BABYLON.Camera ? "CameraProperties"
  51270. : "SceneProperties",
  51271. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51272. };
  51273. };
  51274. return Action;
  51275. }());
  51276. BABYLON.Action = Action;
  51277. })(BABYLON || (BABYLON = {}));
  51278. //# sourceMappingURL=babylon.action.js.map
  51279. "use strict";
  51280. var BABYLON;
  51281. (function (BABYLON) {
  51282. /**
  51283. * ActionEvent is the event being sent when an action is triggered.
  51284. */
  51285. var ActionEvent = /** @class */ (function () {
  51286. /**
  51287. * @param source The mesh or sprite that triggered the action.
  51288. * @param pointerX The X mouse cursor position at the time of the event
  51289. * @param pointerY The Y mouse cursor position at the time of the event
  51290. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51291. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51292. */
  51293. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  51294. this.source = source;
  51295. this.pointerX = pointerX;
  51296. this.pointerY = pointerY;
  51297. this.meshUnderPointer = meshUnderPointer;
  51298. this.sourceEvent = sourceEvent;
  51299. this.additionalData = additionalData;
  51300. }
  51301. /**
  51302. * Helper function to auto-create an ActionEvent from a source mesh.
  51303. * @param source The source mesh that triggered the event
  51304. * @param evt {Event} The original (browser) event
  51305. */
  51306. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51307. var scene = source.getScene();
  51308. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51309. };
  51310. /**
  51311. * Helper function to auto-create an ActionEvent from a source mesh.
  51312. * @param source The source sprite that triggered the event
  51313. * @param scene Scene associated with the sprite
  51314. * @param evt {Event} The original (browser) event
  51315. */
  51316. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51317. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51318. };
  51319. /**
  51320. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51321. * @param scene the scene where the event occurred
  51322. * @param evt {Event} The original (browser) event
  51323. */
  51324. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51325. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51326. };
  51327. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51328. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51329. };
  51330. return ActionEvent;
  51331. }());
  51332. BABYLON.ActionEvent = ActionEvent;
  51333. /**
  51334. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51335. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51336. */
  51337. var ActionManager = /** @class */ (function () {
  51338. function ActionManager(scene) {
  51339. // Members
  51340. this.actions = new Array();
  51341. this.hoverCursor = '';
  51342. this._scene = scene;
  51343. scene._actionManagers.push(this);
  51344. }
  51345. Object.defineProperty(ActionManager, "NothingTrigger", {
  51346. get: function () {
  51347. return ActionManager._NothingTrigger;
  51348. },
  51349. enumerable: true,
  51350. configurable: true
  51351. });
  51352. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51353. get: function () {
  51354. return ActionManager._OnPickTrigger;
  51355. },
  51356. enumerable: true,
  51357. configurable: true
  51358. });
  51359. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51360. get: function () {
  51361. return ActionManager._OnLeftPickTrigger;
  51362. },
  51363. enumerable: true,
  51364. configurable: true
  51365. });
  51366. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  51367. get: function () {
  51368. return ActionManager._OnRightPickTrigger;
  51369. },
  51370. enumerable: true,
  51371. configurable: true
  51372. });
  51373. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  51374. get: function () {
  51375. return ActionManager._OnCenterPickTrigger;
  51376. },
  51377. enumerable: true,
  51378. configurable: true
  51379. });
  51380. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  51381. get: function () {
  51382. return ActionManager._OnPickDownTrigger;
  51383. },
  51384. enumerable: true,
  51385. configurable: true
  51386. });
  51387. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  51388. get: function () {
  51389. return ActionManager._OnDoublePickTrigger;
  51390. },
  51391. enumerable: true,
  51392. configurable: true
  51393. });
  51394. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  51395. get: function () {
  51396. return ActionManager._OnPickUpTrigger;
  51397. },
  51398. enumerable: true,
  51399. configurable: true
  51400. });
  51401. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  51402. /// This trigger will only be raised if you also declared a OnPickDown
  51403. get: function () {
  51404. return ActionManager._OnPickOutTrigger;
  51405. },
  51406. enumerable: true,
  51407. configurable: true
  51408. });
  51409. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  51410. get: function () {
  51411. return ActionManager._OnLongPressTrigger;
  51412. },
  51413. enumerable: true,
  51414. configurable: true
  51415. });
  51416. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  51417. get: function () {
  51418. return ActionManager._OnPointerOverTrigger;
  51419. },
  51420. enumerable: true,
  51421. configurable: true
  51422. });
  51423. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  51424. get: function () {
  51425. return ActionManager._OnPointerOutTrigger;
  51426. },
  51427. enumerable: true,
  51428. configurable: true
  51429. });
  51430. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  51431. get: function () {
  51432. return ActionManager._OnEveryFrameTrigger;
  51433. },
  51434. enumerable: true,
  51435. configurable: true
  51436. });
  51437. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  51438. get: function () {
  51439. return ActionManager._OnIntersectionEnterTrigger;
  51440. },
  51441. enumerable: true,
  51442. configurable: true
  51443. });
  51444. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  51445. get: function () {
  51446. return ActionManager._OnIntersectionExitTrigger;
  51447. },
  51448. enumerable: true,
  51449. configurable: true
  51450. });
  51451. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  51452. get: function () {
  51453. return ActionManager._OnKeyDownTrigger;
  51454. },
  51455. enumerable: true,
  51456. configurable: true
  51457. });
  51458. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  51459. get: function () {
  51460. return ActionManager._OnKeyUpTrigger;
  51461. },
  51462. enumerable: true,
  51463. configurable: true
  51464. });
  51465. // Methods
  51466. ActionManager.prototype.dispose = function () {
  51467. var index = this._scene._actionManagers.indexOf(this);
  51468. for (var i = 0; i < this.actions.length; i++) {
  51469. var action = this.actions[i];
  51470. ActionManager.Triggers[action.trigger]--;
  51471. if (ActionManager.Triggers[action.trigger] === 0) {
  51472. delete ActionManager.Triggers[action.trigger];
  51473. }
  51474. }
  51475. if (index > -1) {
  51476. this._scene._actionManagers.splice(index, 1);
  51477. }
  51478. };
  51479. ActionManager.prototype.getScene = function () {
  51480. return this._scene;
  51481. };
  51482. /**
  51483. * Does this action manager handles actions of any of the given triggers
  51484. * @param {number[]} triggers - the triggers to be tested
  51485. * @return {boolean} whether one (or more) of the triggers is handeled
  51486. */
  51487. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  51488. for (var index = 0; index < this.actions.length; index++) {
  51489. var action = this.actions[index];
  51490. if (triggers.indexOf(action.trigger) > -1) {
  51491. return true;
  51492. }
  51493. }
  51494. return false;
  51495. };
  51496. /**
  51497. * Does this action manager handles actions of a given trigger
  51498. * @param {number} trigger - the trigger to be tested
  51499. * @return {boolean} whether the trigger is handeled
  51500. */
  51501. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  51502. for (var index = 0; index < this.actions.length; index++) {
  51503. var action = this.actions[index];
  51504. if (action.trigger === trigger) {
  51505. return true;
  51506. }
  51507. }
  51508. return false;
  51509. };
  51510. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  51511. /**
  51512. * Does this action manager has pointer triggers
  51513. * @return {boolean} whether or not it has pointer triggers
  51514. */
  51515. get: function () {
  51516. for (var index = 0; index < this.actions.length; index++) {
  51517. var action = this.actions[index];
  51518. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  51519. return true;
  51520. }
  51521. }
  51522. return false;
  51523. },
  51524. enumerable: true,
  51525. configurable: true
  51526. });
  51527. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  51528. /**
  51529. * Does this action manager has pick triggers
  51530. * @return {boolean} whether or not it has pick triggers
  51531. */
  51532. get: function () {
  51533. for (var index = 0; index < this.actions.length; index++) {
  51534. var action = this.actions[index];
  51535. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  51536. return true;
  51537. }
  51538. }
  51539. return false;
  51540. },
  51541. enumerable: true,
  51542. configurable: true
  51543. });
  51544. Object.defineProperty(ActionManager, "HasTriggers", {
  51545. /**
  51546. * Does exist one action manager with at least one trigger
  51547. * @return {boolean} whether or not it exists one action manager with one trigger
  51548. **/
  51549. get: function () {
  51550. for (var t in ActionManager.Triggers) {
  51551. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51552. return true;
  51553. }
  51554. }
  51555. return false;
  51556. },
  51557. enumerable: true,
  51558. configurable: true
  51559. });
  51560. Object.defineProperty(ActionManager, "HasPickTriggers", {
  51561. /**
  51562. * Does exist one action manager with at least one pick trigger
  51563. * @return {boolean} whether or not it exists one action manager with one pick trigger
  51564. **/
  51565. get: function () {
  51566. for (var t in ActionManager.Triggers) {
  51567. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51568. var t_int = parseInt(t);
  51569. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  51570. return true;
  51571. }
  51572. }
  51573. }
  51574. return false;
  51575. },
  51576. enumerable: true,
  51577. configurable: true
  51578. });
  51579. /**
  51580. * Does exist one action manager that handles actions of a given trigger
  51581. * @param {number} trigger - the trigger to be tested
  51582. * @return {boolean} whether the trigger is handeled by at least one action manager
  51583. **/
  51584. ActionManager.HasSpecificTrigger = function (trigger) {
  51585. for (var t in ActionManager.Triggers) {
  51586. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51587. var t_int = parseInt(t);
  51588. if (t_int === trigger) {
  51589. return true;
  51590. }
  51591. }
  51592. }
  51593. return false;
  51594. };
  51595. /**
  51596. * Registers an action to this action manager
  51597. * @param {BABYLON.Action} action - the action to be registered
  51598. * @return {BABYLON.Action} the action amended (prepared) after registration
  51599. */
  51600. ActionManager.prototype.registerAction = function (action) {
  51601. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  51602. if (this.getScene().actionManager !== this) {
  51603. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  51604. return null;
  51605. }
  51606. }
  51607. this.actions.push(action);
  51608. if (ActionManager.Triggers[action.trigger]) {
  51609. ActionManager.Triggers[action.trigger]++;
  51610. }
  51611. else {
  51612. ActionManager.Triggers[action.trigger] = 1;
  51613. }
  51614. action._actionManager = this;
  51615. action._prepare();
  51616. return action;
  51617. };
  51618. /**
  51619. * Unregisters an action to this action manager
  51620. * @param action The action to be unregistered
  51621. * @return whether the action has been unregistered
  51622. */
  51623. ActionManager.prototype.unregisterAction = function (action) {
  51624. var index = this.actions.indexOf(action);
  51625. if (index !== -1) {
  51626. this.actions.splice(index, 1);
  51627. ActionManager.Triggers[action.trigger] -= 1;
  51628. if (ActionManager.Triggers[action.trigger] === 0) {
  51629. delete ActionManager.Triggers[action.trigger];
  51630. }
  51631. delete action._actionManager;
  51632. return true;
  51633. }
  51634. return false;
  51635. };
  51636. /**
  51637. * Process a specific trigger
  51638. * @param {number} trigger - the trigger to process
  51639. * @param evt {BABYLON.ActionEvent} the event details to be processed
  51640. */
  51641. ActionManager.prototype.processTrigger = function (trigger, evt) {
  51642. for (var index = 0; index < this.actions.length; index++) {
  51643. var action = this.actions[index];
  51644. if (action.trigger === trigger) {
  51645. if (evt) {
  51646. if (trigger === ActionManager.OnKeyUpTrigger
  51647. || trigger === ActionManager.OnKeyDownTrigger) {
  51648. var parameter = action.getTriggerParameter();
  51649. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  51650. if (!parameter.toLowerCase) {
  51651. continue;
  51652. }
  51653. var lowerCase = parameter.toLowerCase();
  51654. if (lowerCase !== evt.sourceEvent.key) {
  51655. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  51656. var actualkey = String.fromCharCode(unicode).toLowerCase();
  51657. if (actualkey !== lowerCase) {
  51658. continue;
  51659. }
  51660. }
  51661. }
  51662. }
  51663. }
  51664. action._executeCurrent(evt);
  51665. }
  51666. }
  51667. };
  51668. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  51669. var properties = propertyPath.split(".");
  51670. for (var index = 0; index < properties.length - 1; index++) {
  51671. target = target[properties[index]];
  51672. }
  51673. return target;
  51674. };
  51675. ActionManager.prototype._getProperty = function (propertyPath) {
  51676. var properties = propertyPath.split(".");
  51677. return properties[properties.length - 1];
  51678. };
  51679. ActionManager.prototype.serialize = function (name) {
  51680. var root = {
  51681. children: new Array(),
  51682. name: name,
  51683. type: 3,
  51684. properties: new Array() // Empty for root but required
  51685. };
  51686. for (var i = 0; i < this.actions.length; i++) {
  51687. var triggerObject = {
  51688. type: 0,
  51689. children: new Array(),
  51690. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  51691. properties: new Array()
  51692. };
  51693. var triggerOptions = this.actions[i].triggerOptions;
  51694. if (triggerOptions && typeof triggerOptions !== "number") {
  51695. if (triggerOptions.parameter instanceof BABYLON.Node) {
  51696. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  51697. }
  51698. else {
  51699. var parameter = {};
  51700. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  51701. if (triggerOptions.parameter.mesh) {
  51702. parameter._meshId = triggerOptions.parameter.mesh.id;
  51703. }
  51704. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  51705. }
  51706. }
  51707. // Serialize child action, recursively
  51708. this.actions[i].serialize(triggerObject);
  51709. // Add serialized trigger
  51710. root.children.push(triggerObject);
  51711. }
  51712. return root;
  51713. };
  51714. ActionManager.Parse = function (parsedActions, object, scene) {
  51715. var actionManager = new ActionManager(scene);
  51716. if (object === null)
  51717. scene.actionManager = actionManager;
  51718. else
  51719. object.actionManager = actionManager;
  51720. // instanciate a new object
  51721. var instanciate = function (name, params) {
  51722. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  51723. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  51724. newInstance.constructor.apply(newInstance, params);
  51725. return newInstance;
  51726. };
  51727. var parseParameter = function (name, value, target, propertyPath) {
  51728. if (propertyPath === null) {
  51729. // String, boolean or float
  51730. var floatValue = parseFloat(value);
  51731. if (value === "true" || value === "false")
  51732. return value === "true";
  51733. else
  51734. return isNaN(floatValue) ? value : floatValue;
  51735. }
  51736. var effectiveTarget = propertyPath.split(".");
  51737. var values = value.split(",");
  51738. // Get effective Target
  51739. for (var i = 0; i < effectiveTarget.length; i++) {
  51740. target = target[effectiveTarget[i]];
  51741. }
  51742. // Return appropriate value with its type
  51743. if (typeof (target) === "boolean")
  51744. return values[0] === "true";
  51745. if (typeof (target) === "string")
  51746. return values[0];
  51747. // Parameters with multiple values such as Vector3 etc.
  51748. var split = new Array();
  51749. for (var i = 0; i < values.length; i++)
  51750. split.push(parseFloat(values[i]));
  51751. if (target instanceof BABYLON.Vector3)
  51752. return BABYLON.Vector3.FromArray(split);
  51753. if (target instanceof BABYLON.Vector4)
  51754. return BABYLON.Vector4.FromArray(split);
  51755. if (target instanceof BABYLON.Color3)
  51756. return BABYLON.Color3.FromArray(split);
  51757. if (target instanceof BABYLON.Color4)
  51758. return BABYLON.Color4.FromArray(split);
  51759. return parseFloat(values[0]);
  51760. };
  51761. // traverse graph per trigger
  51762. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  51763. if (combineArray === void 0) { combineArray = null; }
  51764. if (parsedAction.detached)
  51765. return;
  51766. var parameters = new Array();
  51767. var target = null;
  51768. var propertyPath = null;
  51769. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  51770. // Parameters
  51771. if (parsedAction.type === 2)
  51772. parameters.push(actionManager);
  51773. else
  51774. parameters.push(trigger);
  51775. if (combine) {
  51776. var actions = new Array();
  51777. for (var j = 0; j < parsedAction.combine.length; j++) {
  51778. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  51779. }
  51780. parameters.push(actions);
  51781. }
  51782. else {
  51783. for (var i = 0; i < parsedAction.properties.length; i++) {
  51784. var value = parsedAction.properties[i].value;
  51785. var name = parsedAction.properties[i].name;
  51786. var targetType = parsedAction.properties[i].targetType;
  51787. if (name === "target")
  51788. if (targetType !== null && targetType === "SceneProperties")
  51789. value = target = scene;
  51790. else
  51791. value = target = scene.getNodeByName(value);
  51792. else if (name === "parent")
  51793. value = scene.getNodeByName(value);
  51794. else if (name === "sound")
  51795. value = scene.getSoundByName(value);
  51796. else if (name !== "propertyPath") {
  51797. if (parsedAction.type === 2 && name === "operator")
  51798. value = BABYLON.ValueCondition[value];
  51799. else
  51800. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  51801. }
  51802. else {
  51803. propertyPath = value;
  51804. }
  51805. parameters.push(value);
  51806. }
  51807. }
  51808. if (combineArray === null) {
  51809. parameters.push(condition);
  51810. }
  51811. else {
  51812. parameters.push(null);
  51813. }
  51814. // If interpolate value action
  51815. if (parsedAction.name === "InterpolateValueAction") {
  51816. var param = parameters[parameters.length - 2];
  51817. parameters[parameters.length - 1] = param;
  51818. parameters[parameters.length - 2] = condition;
  51819. }
  51820. // Action or condition(s) and not CombineAction
  51821. var newAction = instanciate(parsedAction.name, parameters);
  51822. if (newAction instanceof BABYLON.Condition && condition !== null) {
  51823. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  51824. if (action)
  51825. action.then(nothing);
  51826. else
  51827. actionManager.registerAction(nothing);
  51828. action = nothing;
  51829. }
  51830. if (combineArray === null) {
  51831. if (newAction instanceof BABYLON.Condition) {
  51832. condition = newAction;
  51833. newAction = action;
  51834. }
  51835. else {
  51836. condition = null;
  51837. if (action)
  51838. action.then(newAction);
  51839. else
  51840. actionManager.registerAction(newAction);
  51841. }
  51842. }
  51843. else {
  51844. combineArray.push(newAction);
  51845. }
  51846. for (var i = 0; i < parsedAction.children.length; i++)
  51847. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  51848. };
  51849. // triggers
  51850. for (var i = 0; i < parsedActions.children.length; i++) {
  51851. var triggerParams;
  51852. var trigger = parsedActions.children[i];
  51853. if (trigger.properties.length > 0) {
  51854. var param = trigger.properties[0].value;
  51855. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  51856. if (value._meshId) {
  51857. value.mesh = scene.getMeshByID(value._meshId);
  51858. }
  51859. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  51860. }
  51861. else
  51862. triggerParams = ActionManager[trigger.name];
  51863. for (var j = 0; j < trigger.children.length; j++) {
  51864. if (!trigger.detached)
  51865. traverse(trigger.children[j], triggerParams, null, null);
  51866. }
  51867. }
  51868. };
  51869. ActionManager.GetTriggerName = function (trigger) {
  51870. switch (trigger) {
  51871. case 0: return "NothingTrigger";
  51872. case 1: return "OnPickTrigger";
  51873. case 2: return "OnLeftPickTrigger";
  51874. case 3: return "OnRightPickTrigger";
  51875. case 4: return "OnCenterPickTrigger";
  51876. case 5: return "OnPickDownTrigger";
  51877. case 6: return "OnPickUpTrigger";
  51878. case 7: return "OnLongPressTrigger";
  51879. case 8: return "OnPointerOverTrigger";
  51880. case 9: return "OnPointerOutTrigger";
  51881. case 10: return "OnEveryFrameTrigger";
  51882. case 11: return "OnIntersectionEnterTrigger";
  51883. case 12: return "OnIntersectionExitTrigger";
  51884. case 13: return "OnKeyDownTrigger";
  51885. case 14: return "OnKeyUpTrigger";
  51886. case 15: return "OnPickOutTrigger";
  51887. default: return "";
  51888. }
  51889. };
  51890. // Statics
  51891. ActionManager._NothingTrigger = 0;
  51892. ActionManager._OnPickTrigger = 1;
  51893. ActionManager._OnLeftPickTrigger = 2;
  51894. ActionManager._OnRightPickTrigger = 3;
  51895. ActionManager._OnCenterPickTrigger = 4;
  51896. ActionManager._OnPickDownTrigger = 5;
  51897. ActionManager._OnDoublePickTrigger = 6;
  51898. ActionManager._OnPickUpTrigger = 7;
  51899. ActionManager._OnLongPressTrigger = 8;
  51900. ActionManager._OnPointerOverTrigger = 9;
  51901. ActionManager._OnPointerOutTrigger = 10;
  51902. ActionManager._OnEveryFrameTrigger = 11;
  51903. ActionManager._OnIntersectionEnterTrigger = 12;
  51904. ActionManager._OnIntersectionExitTrigger = 13;
  51905. ActionManager._OnKeyDownTrigger = 14;
  51906. ActionManager._OnKeyUpTrigger = 15;
  51907. ActionManager._OnPickOutTrigger = 16;
  51908. ActionManager.Triggers = {};
  51909. return ActionManager;
  51910. }());
  51911. BABYLON.ActionManager = ActionManager;
  51912. })(BABYLON || (BABYLON = {}));
  51913. //# sourceMappingURL=babylon.actionManager.js.map
  51914. "use strict";
  51915. var BABYLON;
  51916. (function (BABYLON) {
  51917. var InterpolateValueAction = /** @class */ (function (_super) {
  51918. __extends(InterpolateValueAction, _super);
  51919. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  51920. if (duration === void 0) { duration = 1000; }
  51921. var _this = _super.call(this, triggerOptions, condition) || this;
  51922. _this.propertyPath = propertyPath;
  51923. _this.value = value;
  51924. _this.duration = duration;
  51925. _this.stopOtherAnimations = stopOtherAnimations;
  51926. _this.onInterpolationDone = onInterpolationDone;
  51927. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  51928. _this._target = _this._effectiveTarget = target;
  51929. return _this;
  51930. }
  51931. InterpolateValueAction.prototype._prepare = function () {
  51932. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  51933. this._property = this._getProperty(this.propertyPath);
  51934. };
  51935. InterpolateValueAction.prototype.execute = function () {
  51936. var _this = this;
  51937. var scene = this._actionManager.getScene();
  51938. var keys = [
  51939. {
  51940. frame: 0,
  51941. value: this._effectiveTarget[this._property]
  51942. }, {
  51943. frame: 100,
  51944. value: this.value
  51945. }
  51946. ];
  51947. var dataType;
  51948. if (typeof this.value === "number") {
  51949. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  51950. }
  51951. else if (this.value instanceof BABYLON.Color3) {
  51952. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  51953. }
  51954. else if (this.value instanceof BABYLON.Vector3) {
  51955. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  51956. }
  51957. else if (this.value instanceof BABYLON.Matrix) {
  51958. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  51959. }
  51960. else if (this.value instanceof BABYLON.Quaternion) {
  51961. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  51962. }
  51963. else {
  51964. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  51965. return;
  51966. }
  51967. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  51968. animation.setKeys(keys);
  51969. if (this.stopOtherAnimations) {
  51970. scene.stopAnimation(this._effectiveTarget);
  51971. }
  51972. var wrapper = function () {
  51973. _this.onInterpolationDoneObservable.notifyObservers(_this);
  51974. if (_this.onInterpolationDone) {
  51975. _this.onInterpolationDone();
  51976. }
  51977. };
  51978. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  51979. };
  51980. InterpolateValueAction.prototype.serialize = function (parent) {
  51981. return _super.prototype._serialize.call(this, {
  51982. name: "InterpolateValueAction",
  51983. properties: [
  51984. BABYLON.Action._GetTargetProperty(this._target),
  51985. { name: "propertyPath", value: this.propertyPath },
  51986. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51987. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  51988. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  51989. ]
  51990. }, parent);
  51991. };
  51992. return InterpolateValueAction;
  51993. }(BABYLON.Action));
  51994. BABYLON.InterpolateValueAction = InterpolateValueAction;
  51995. })(BABYLON || (BABYLON = {}));
  51996. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  51997. "use strict";
  51998. var BABYLON;
  51999. (function (BABYLON) {
  52000. var SwitchBooleanAction = /** @class */ (function (_super) {
  52001. __extends(SwitchBooleanAction, _super);
  52002. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52003. var _this = _super.call(this, triggerOptions, condition) || this;
  52004. _this.propertyPath = propertyPath;
  52005. _this._target = _this._effectiveTarget = target;
  52006. return _this;
  52007. }
  52008. SwitchBooleanAction.prototype._prepare = function () {
  52009. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52010. this._property = this._getProperty(this.propertyPath);
  52011. };
  52012. SwitchBooleanAction.prototype.execute = function () {
  52013. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52014. };
  52015. SwitchBooleanAction.prototype.serialize = function (parent) {
  52016. return _super.prototype._serialize.call(this, {
  52017. name: "SwitchBooleanAction",
  52018. properties: [
  52019. BABYLON.Action._GetTargetProperty(this._target),
  52020. { name: "propertyPath", value: this.propertyPath }
  52021. ]
  52022. }, parent);
  52023. };
  52024. return SwitchBooleanAction;
  52025. }(BABYLON.Action));
  52026. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52027. var SetStateAction = /** @class */ (function (_super) {
  52028. __extends(SetStateAction, _super);
  52029. function SetStateAction(triggerOptions, target, value, condition) {
  52030. var _this = _super.call(this, triggerOptions, condition) || this;
  52031. _this.value = value;
  52032. _this._target = target;
  52033. return _this;
  52034. }
  52035. SetStateAction.prototype.execute = function () {
  52036. this._target.state = this.value;
  52037. };
  52038. SetStateAction.prototype.serialize = function (parent) {
  52039. return _super.prototype._serialize.call(this, {
  52040. name: "SetStateAction",
  52041. properties: [
  52042. BABYLON.Action._GetTargetProperty(this._target),
  52043. { name: "value", value: this.value }
  52044. ]
  52045. }, parent);
  52046. };
  52047. return SetStateAction;
  52048. }(BABYLON.Action));
  52049. BABYLON.SetStateAction = SetStateAction;
  52050. var SetValueAction = /** @class */ (function (_super) {
  52051. __extends(SetValueAction, _super);
  52052. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52053. var _this = _super.call(this, triggerOptions, condition) || this;
  52054. _this.propertyPath = propertyPath;
  52055. _this.value = value;
  52056. _this._target = _this._effectiveTarget = target;
  52057. return _this;
  52058. }
  52059. SetValueAction.prototype._prepare = function () {
  52060. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52061. this._property = this._getProperty(this.propertyPath);
  52062. };
  52063. SetValueAction.prototype.execute = function () {
  52064. this._effectiveTarget[this._property] = this.value;
  52065. if (this._target.markAsDirty) {
  52066. this._target.markAsDirty(this._property);
  52067. }
  52068. };
  52069. SetValueAction.prototype.serialize = function (parent) {
  52070. return _super.prototype._serialize.call(this, {
  52071. name: "SetValueAction",
  52072. properties: [
  52073. BABYLON.Action._GetTargetProperty(this._target),
  52074. { name: "propertyPath", value: this.propertyPath },
  52075. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52076. ]
  52077. }, parent);
  52078. };
  52079. return SetValueAction;
  52080. }(BABYLON.Action));
  52081. BABYLON.SetValueAction = SetValueAction;
  52082. var IncrementValueAction = /** @class */ (function (_super) {
  52083. __extends(IncrementValueAction, _super);
  52084. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52085. var _this = _super.call(this, triggerOptions, condition) || this;
  52086. _this.propertyPath = propertyPath;
  52087. _this.value = value;
  52088. _this._target = _this._effectiveTarget = target;
  52089. return _this;
  52090. }
  52091. IncrementValueAction.prototype._prepare = function () {
  52092. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52093. this._property = this._getProperty(this.propertyPath);
  52094. if (typeof this._effectiveTarget[this._property] !== "number") {
  52095. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52096. }
  52097. };
  52098. IncrementValueAction.prototype.execute = function () {
  52099. this._effectiveTarget[this._property] += this.value;
  52100. if (this._target.markAsDirty) {
  52101. this._target.markAsDirty(this._property);
  52102. }
  52103. };
  52104. IncrementValueAction.prototype.serialize = function (parent) {
  52105. return _super.prototype._serialize.call(this, {
  52106. name: "IncrementValueAction",
  52107. properties: [
  52108. BABYLON.Action._GetTargetProperty(this._target),
  52109. { name: "propertyPath", value: this.propertyPath },
  52110. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52111. ]
  52112. }, parent);
  52113. };
  52114. return IncrementValueAction;
  52115. }(BABYLON.Action));
  52116. BABYLON.IncrementValueAction = IncrementValueAction;
  52117. var PlayAnimationAction = /** @class */ (function (_super) {
  52118. __extends(PlayAnimationAction, _super);
  52119. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52120. var _this = _super.call(this, triggerOptions, condition) || this;
  52121. _this.from = from;
  52122. _this.to = to;
  52123. _this.loop = loop;
  52124. _this._target = target;
  52125. return _this;
  52126. }
  52127. PlayAnimationAction.prototype._prepare = function () {
  52128. };
  52129. PlayAnimationAction.prototype.execute = function () {
  52130. var scene = this._actionManager.getScene();
  52131. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52132. };
  52133. PlayAnimationAction.prototype.serialize = function (parent) {
  52134. return _super.prototype._serialize.call(this, {
  52135. name: "PlayAnimationAction",
  52136. properties: [
  52137. BABYLON.Action._GetTargetProperty(this._target),
  52138. { name: "from", value: String(this.from) },
  52139. { name: "to", value: String(this.to) },
  52140. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52141. ]
  52142. }, parent);
  52143. };
  52144. return PlayAnimationAction;
  52145. }(BABYLON.Action));
  52146. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52147. var StopAnimationAction = /** @class */ (function (_super) {
  52148. __extends(StopAnimationAction, _super);
  52149. function StopAnimationAction(triggerOptions, target, condition) {
  52150. var _this = _super.call(this, triggerOptions, condition) || this;
  52151. _this._target = target;
  52152. return _this;
  52153. }
  52154. StopAnimationAction.prototype._prepare = function () {
  52155. };
  52156. StopAnimationAction.prototype.execute = function () {
  52157. var scene = this._actionManager.getScene();
  52158. scene.stopAnimation(this._target);
  52159. };
  52160. StopAnimationAction.prototype.serialize = function (parent) {
  52161. return _super.prototype._serialize.call(this, {
  52162. name: "StopAnimationAction",
  52163. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52164. }, parent);
  52165. };
  52166. return StopAnimationAction;
  52167. }(BABYLON.Action));
  52168. BABYLON.StopAnimationAction = StopAnimationAction;
  52169. var DoNothingAction = /** @class */ (function (_super) {
  52170. __extends(DoNothingAction, _super);
  52171. function DoNothingAction(triggerOptions, condition) {
  52172. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52173. return _super.call(this, triggerOptions, condition) || this;
  52174. }
  52175. DoNothingAction.prototype.execute = function () {
  52176. };
  52177. DoNothingAction.prototype.serialize = function (parent) {
  52178. return _super.prototype._serialize.call(this, {
  52179. name: "DoNothingAction",
  52180. properties: []
  52181. }, parent);
  52182. };
  52183. return DoNothingAction;
  52184. }(BABYLON.Action));
  52185. BABYLON.DoNothingAction = DoNothingAction;
  52186. var CombineAction = /** @class */ (function (_super) {
  52187. __extends(CombineAction, _super);
  52188. function CombineAction(triggerOptions, children, condition) {
  52189. var _this = _super.call(this, triggerOptions, condition) || this;
  52190. _this.children = children;
  52191. return _this;
  52192. }
  52193. CombineAction.prototype._prepare = function () {
  52194. for (var index = 0; index < this.children.length; index++) {
  52195. this.children[index]._actionManager = this._actionManager;
  52196. this.children[index]._prepare();
  52197. }
  52198. };
  52199. CombineAction.prototype.execute = function (evt) {
  52200. for (var index = 0; index < this.children.length; index++) {
  52201. this.children[index].execute(evt);
  52202. }
  52203. };
  52204. CombineAction.prototype.serialize = function (parent) {
  52205. var serializationObject = _super.prototype._serialize.call(this, {
  52206. name: "CombineAction",
  52207. properties: [],
  52208. combine: []
  52209. }, parent);
  52210. for (var i = 0; i < this.children.length; i++) {
  52211. serializationObject.combine.push(this.children[i].serialize(null));
  52212. }
  52213. return serializationObject;
  52214. };
  52215. return CombineAction;
  52216. }(BABYLON.Action));
  52217. BABYLON.CombineAction = CombineAction;
  52218. var ExecuteCodeAction = /** @class */ (function (_super) {
  52219. __extends(ExecuteCodeAction, _super);
  52220. function ExecuteCodeAction(triggerOptions, func, condition) {
  52221. var _this = _super.call(this, triggerOptions, condition) || this;
  52222. _this.func = func;
  52223. return _this;
  52224. }
  52225. ExecuteCodeAction.prototype.execute = function (evt) {
  52226. this.func(evt);
  52227. };
  52228. return ExecuteCodeAction;
  52229. }(BABYLON.Action));
  52230. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52231. var SetParentAction = /** @class */ (function (_super) {
  52232. __extends(SetParentAction, _super);
  52233. function SetParentAction(triggerOptions, target, parent, condition) {
  52234. var _this = _super.call(this, triggerOptions, condition) || this;
  52235. _this._target = target;
  52236. _this._parent = parent;
  52237. return _this;
  52238. }
  52239. SetParentAction.prototype._prepare = function () {
  52240. };
  52241. SetParentAction.prototype.execute = function () {
  52242. if (this._target.parent === this._parent) {
  52243. return;
  52244. }
  52245. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52246. invertParentWorldMatrix.invert();
  52247. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52248. this._target.parent = this._parent;
  52249. };
  52250. SetParentAction.prototype.serialize = function (parent) {
  52251. return _super.prototype._serialize.call(this, {
  52252. name: "SetParentAction",
  52253. properties: [
  52254. BABYLON.Action._GetTargetProperty(this._target),
  52255. BABYLON.Action._GetTargetProperty(this._parent),
  52256. ]
  52257. }, parent);
  52258. };
  52259. return SetParentAction;
  52260. }(BABYLON.Action));
  52261. BABYLON.SetParentAction = SetParentAction;
  52262. var PlaySoundAction = /** @class */ (function (_super) {
  52263. __extends(PlaySoundAction, _super);
  52264. function PlaySoundAction(triggerOptions, sound, condition) {
  52265. var _this = _super.call(this, triggerOptions, condition) || this;
  52266. _this._sound = sound;
  52267. return _this;
  52268. }
  52269. PlaySoundAction.prototype._prepare = function () {
  52270. };
  52271. PlaySoundAction.prototype.execute = function () {
  52272. if (this._sound !== undefined)
  52273. this._sound.play();
  52274. };
  52275. PlaySoundAction.prototype.serialize = function (parent) {
  52276. return _super.prototype._serialize.call(this, {
  52277. name: "PlaySoundAction",
  52278. properties: [{ name: "sound", value: this._sound.name }]
  52279. }, parent);
  52280. };
  52281. return PlaySoundAction;
  52282. }(BABYLON.Action));
  52283. BABYLON.PlaySoundAction = PlaySoundAction;
  52284. var StopSoundAction = /** @class */ (function (_super) {
  52285. __extends(StopSoundAction, _super);
  52286. function StopSoundAction(triggerOptions, sound, condition) {
  52287. var _this = _super.call(this, triggerOptions, condition) || this;
  52288. _this._sound = sound;
  52289. return _this;
  52290. }
  52291. StopSoundAction.prototype._prepare = function () {
  52292. };
  52293. StopSoundAction.prototype.execute = function () {
  52294. if (this._sound !== undefined)
  52295. this._sound.stop();
  52296. };
  52297. StopSoundAction.prototype.serialize = function (parent) {
  52298. return _super.prototype._serialize.call(this, {
  52299. name: "StopSoundAction",
  52300. properties: [{ name: "sound", value: this._sound.name }]
  52301. }, parent);
  52302. };
  52303. return StopSoundAction;
  52304. }(BABYLON.Action));
  52305. BABYLON.StopSoundAction = StopSoundAction;
  52306. })(BABYLON || (BABYLON = {}));
  52307. //# sourceMappingURL=babylon.directActions.js.map
  52308. "use strict";
  52309. var BABYLON;
  52310. (function (BABYLON) {
  52311. var SpriteManager = /** @class */ (function () {
  52312. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  52313. if (epsilon === void 0) { epsilon = 0.01; }
  52314. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52315. this.name = name;
  52316. this.sprites = new Array();
  52317. this.renderingGroupId = 0;
  52318. this.layerMask = 0x0FFFFFFF;
  52319. this.fogEnabled = true;
  52320. this.isPickable = false;
  52321. /**
  52322. * An event triggered when the manager is disposed.
  52323. */
  52324. this.onDisposeObservable = new BABYLON.Observable();
  52325. this._vertexBuffers = {};
  52326. this._capacity = capacity;
  52327. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  52328. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52329. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52330. if (cellSize.width && cellSize.height) {
  52331. this.cellWidth = cellSize.width;
  52332. this.cellHeight = cellSize.height;
  52333. }
  52334. else if (cellSize !== undefined) {
  52335. this.cellWidth = cellSize;
  52336. this.cellHeight = cellSize;
  52337. }
  52338. else {
  52339. return;
  52340. }
  52341. this._epsilon = epsilon;
  52342. this._scene = scene;
  52343. this._scene.spriteManagers.push(this);
  52344. var indices = [];
  52345. var index = 0;
  52346. for (var count = 0; count < capacity; count++) {
  52347. indices.push(index);
  52348. indices.push(index + 1);
  52349. indices.push(index + 2);
  52350. indices.push(index);
  52351. indices.push(index + 2);
  52352. indices.push(index + 3);
  52353. index += 4;
  52354. }
  52355. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  52356. // VBO
  52357. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  52358. this._vertexData = new Float32Array(capacity * 16 * 4);
  52359. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  52360. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  52361. var options = this._buffer.createVertexBuffer("options", 4, 4);
  52362. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  52363. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  52364. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  52365. this._vertexBuffers["options"] = options;
  52366. this._vertexBuffers["cellInfo"] = cellInfo;
  52367. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  52368. // Effects
  52369. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  52370. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  52371. }
  52372. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  52373. set: function (callback) {
  52374. if (this._onDisposeObserver) {
  52375. this.onDisposeObservable.remove(this._onDisposeObserver);
  52376. }
  52377. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52378. },
  52379. enumerable: true,
  52380. configurable: true
  52381. });
  52382. Object.defineProperty(SpriteManager.prototype, "texture", {
  52383. get: function () {
  52384. return this._spriteTexture;
  52385. },
  52386. set: function (value) {
  52387. this._spriteTexture = value;
  52388. },
  52389. enumerable: true,
  52390. configurable: true
  52391. });
  52392. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  52393. var arrayOffset = index * 16;
  52394. if (offsetX === 0)
  52395. offsetX = this._epsilon;
  52396. else if (offsetX === 1)
  52397. offsetX = 1 - this._epsilon;
  52398. if (offsetY === 0)
  52399. offsetY = this._epsilon;
  52400. else if (offsetY === 1)
  52401. offsetY = 1 - this._epsilon;
  52402. this._vertexData[arrayOffset] = sprite.position.x;
  52403. this._vertexData[arrayOffset + 1] = sprite.position.y;
  52404. this._vertexData[arrayOffset + 2] = sprite.position.z;
  52405. this._vertexData[arrayOffset + 3] = sprite.angle;
  52406. this._vertexData[arrayOffset + 4] = sprite.width;
  52407. this._vertexData[arrayOffset + 5] = sprite.height;
  52408. this._vertexData[arrayOffset + 6] = offsetX;
  52409. this._vertexData[arrayOffset + 7] = offsetY;
  52410. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  52411. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  52412. var offset = (sprite.cellIndex / rowSize) >> 0;
  52413. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  52414. this._vertexData[arrayOffset + 11] = offset;
  52415. // Color
  52416. this._vertexData[arrayOffset + 12] = sprite.color.r;
  52417. this._vertexData[arrayOffset + 13] = sprite.color.g;
  52418. this._vertexData[arrayOffset + 14] = sprite.color.b;
  52419. this._vertexData[arrayOffset + 15] = sprite.color.a;
  52420. };
  52421. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  52422. var count = Math.min(this._capacity, this.sprites.length);
  52423. var min = BABYLON.Vector3.Zero();
  52424. var max = BABYLON.Vector3.Zero();
  52425. var distance = Number.MAX_VALUE;
  52426. var currentSprite = null;
  52427. var cameraSpacePosition = BABYLON.Vector3.Zero();
  52428. var cameraView = camera.getViewMatrix();
  52429. for (var index = 0; index < count; index++) {
  52430. var sprite = this.sprites[index];
  52431. if (!sprite) {
  52432. continue;
  52433. }
  52434. if (predicate) {
  52435. if (!predicate(sprite)) {
  52436. continue;
  52437. }
  52438. }
  52439. else if (!sprite.isPickable) {
  52440. continue;
  52441. }
  52442. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  52443. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  52444. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  52445. if (ray.intersectsBoxMinMax(min, max)) {
  52446. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  52447. if (distance > currentDistance) {
  52448. distance = currentDistance;
  52449. currentSprite = sprite;
  52450. if (fastCheck) {
  52451. break;
  52452. }
  52453. }
  52454. }
  52455. }
  52456. if (currentSprite) {
  52457. var result = new BABYLON.PickingInfo();
  52458. result.hit = true;
  52459. result.pickedSprite = currentSprite;
  52460. result.distance = distance;
  52461. return result;
  52462. }
  52463. return null;
  52464. };
  52465. SpriteManager.prototype.render = function () {
  52466. // Check
  52467. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  52468. return;
  52469. var engine = this._scene.getEngine();
  52470. var baseSize = this._spriteTexture.getBaseSize();
  52471. // Sprites
  52472. var deltaTime = engine.getDeltaTime();
  52473. var max = Math.min(this._capacity, this.sprites.length);
  52474. var rowSize = baseSize.width / this.cellWidth;
  52475. var offset = 0;
  52476. for (var index = 0; index < max; index++) {
  52477. var sprite = this.sprites[index];
  52478. if (!sprite) {
  52479. continue;
  52480. }
  52481. sprite._animate(deltaTime);
  52482. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  52483. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  52484. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  52485. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  52486. }
  52487. this._buffer.update(this._vertexData);
  52488. // Render
  52489. var effect = this._effectBase;
  52490. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52491. effect = this._effectFog;
  52492. }
  52493. engine.enableEffect(effect);
  52494. var viewMatrix = this._scene.getViewMatrix();
  52495. effect.setTexture("diffuseSampler", this._spriteTexture);
  52496. effect.setMatrix("view", viewMatrix);
  52497. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52498. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  52499. // Fog
  52500. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52501. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  52502. effect.setColor3("vFogColor", this._scene.fogColor);
  52503. }
  52504. // VBOs
  52505. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52506. // Draw order
  52507. engine.setDepthFunctionToLessOrEqual();
  52508. effect.setBool("alphaTest", true);
  52509. engine.setColorWrite(false);
  52510. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52511. engine.setColorWrite(true);
  52512. effect.setBool("alphaTest", false);
  52513. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52514. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52515. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52516. };
  52517. SpriteManager.prototype.dispose = function () {
  52518. if (this._buffer) {
  52519. this._buffer.dispose();
  52520. this._buffer = null;
  52521. }
  52522. if (this._indexBuffer) {
  52523. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52524. this._indexBuffer = null;
  52525. }
  52526. if (this._spriteTexture) {
  52527. this._spriteTexture.dispose();
  52528. this._spriteTexture = null;
  52529. }
  52530. // Remove from scene
  52531. var index = this._scene.spriteManagers.indexOf(this);
  52532. this._scene.spriteManagers.splice(index, 1);
  52533. // Callback
  52534. this.onDisposeObservable.notifyObservers(this);
  52535. this.onDisposeObservable.clear();
  52536. };
  52537. return SpriteManager;
  52538. }());
  52539. BABYLON.SpriteManager = SpriteManager;
  52540. })(BABYLON || (BABYLON = {}));
  52541. //# sourceMappingURL=babylon.spriteManager.js.map
  52542. "use strict";
  52543. var BABYLON;
  52544. (function (BABYLON) {
  52545. var Sprite = /** @class */ (function () {
  52546. function Sprite(name, manager) {
  52547. this.name = name;
  52548. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52549. this.width = 1.0;
  52550. this.height = 1.0;
  52551. this.angle = 0;
  52552. this.cellIndex = 0;
  52553. this.invertU = 0;
  52554. this.invertV = 0;
  52555. this.animations = new Array();
  52556. this.isPickable = false;
  52557. this._animationStarted = false;
  52558. this._loopAnimation = false;
  52559. this._fromIndex = 0;
  52560. this._toIndex = 0;
  52561. this._delay = 0;
  52562. this._direction = 1;
  52563. this._time = 0;
  52564. this._manager = manager;
  52565. this._manager.sprites.push(this);
  52566. this.position = BABYLON.Vector3.Zero();
  52567. }
  52568. Object.defineProperty(Sprite.prototype, "size", {
  52569. get: function () {
  52570. return this.width;
  52571. },
  52572. set: function (value) {
  52573. this.width = value;
  52574. this.height = value;
  52575. },
  52576. enumerable: true,
  52577. configurable: true
  52578. });
  52579. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  52580. this._fromIndex = from;
  52581. this._toIndex = to;
  52582. this._loopAnimation = loop;
  52583. this._delay = delay;
  52584. this._animationStarted = true;
  52585. this._direction = from < to ? 1 : -1;
  52586. this.cellIndex = from;
  52587. this._time = 0;
  52588. this._onAnimationEnd = onAnimationEnd;
  52589. };
  52590. Sprite.prototype.stopAnimation = function () {
  52591. this._animationStarted = false;
  52592. };
  52593. Sprite.prototype._animate = function (deltaTime) {
  52594. if (!this._animationStarted)
  52595. return;
  52596. this._time += deltaTime;
  52597. if (this._time > this._delay) {
  52598. this._time = this._time % this._delay;
  52599. this.cellIndex += this._direction;
  52600. if (this.cellIndex > this._toIndex) {
  52601. if (this._loopAnimation) {
  52602. this.cellIndex = this._fromIndex;
  52603. }
  52604. else {
  52605. this.cellIndex = this._toIndex;
  52606. this._animationStarted = false;
  52607. if (this._onAnimationEnd) {
  52608. this._onAnimationEnd();
  52609. }
  52610. if (this.disposeWhenFinishedAnimating) {
  52611. this.dispose();
  52612. }
  52613. }
  52614. }
  52615. }
  52616. };
  52617. Sprite.prototype.dispose = function () {
  52618. for (var i = 0; i < this._manager.sprites.length; i++) {
  52619. if (this._manager.sprites[i] == this) {
  52620. this._manager.sprites.splice(i, 1);
  52621. }
  52622. }
  52623. };
  52624. return Sprite;
  52625. }());
  52626. BABYLON.Sprite = Sprite;
  52627. })(BABYLON || (BABYLON = {}));
  52628. //# sourceMappingURL=babylon.sprite.js.map
  52629. "use strict";
  52630. var BABYLON;
  52631. (function (BABYLON) {
  52632. var IntersectionInfo = /** @class */ (function () {
  52633. function IntersectionInfo(bu, bv, distance) {
  52634. this.bu = bu;
  52635. this.bv = bv;
  52636. this.distance = distance;
  52637. this.faceId = 0;
  52638. this.subMeshId = 0;
  52639. }
  52640. return IntersectionInfo;
  52641. }());
  52642. BABYLON.IntersectionInfo = IntersectionInfo;
  52643. var PickingInfo = /** @class */ (function () {
  52644. function PickingInfo() {
  52645. this.hit = false;
  52646. this.distance = 0;
  52647. this.pickedPoint = null;
  52648. this.pickedMesh = null;
  52649. this.bu = 0;
  52650. this.bv = 0;
  52651. this.faceId = -1;
  52652. this.subMeshId = 0;
  52653. this.pickedSprite = null;
  52654. }
  52655. // Methods
  52656. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  52657. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  52658. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  52659. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  52660. return null;
  52661. }
  52662. var indices = this.pickedMesh.getIndices();
  52663. if (!indices) {
  52664. return null;
  52665. }
  52666. var result;
  52667. if (useVerticesNormals) {
  52668. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52669. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  52670. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  52671. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  52672. normal0 = normal0.scale(this.bu);
  52673. normal1 = normal1.scale(this.bv);
  52674. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  52675. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  52676. }
  52677. else {
  52678. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52679. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  52680. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  52681. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  52682. var p1p2 = vertex1.subtract(vertex2);
  52683. var p3p2 = vertex3.subtract(vertex2);
  52684. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  52685. }
  52686. if (useWorldCoordinates) {
  52687. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  52688. }
  52689. return BABYLON.Vector3.Normalize(result);
  52690. };
  52691. PickingInfo.prototype.getTextureCoordinates = function () {
  52692. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52693. return null;
  52694. }
  52695. var indices = this.pickedMesh.getIndices();
  52696. if (!indices) {
  52697. return null;
  52698. }
  52699. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52700. if (!uvs) {
  52701. return null;
  52702. }
  52703. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  52704. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  52705. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  52706. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  52707. uv1 = uv1.scale(this.bu);
  52708. uv2 = uv2.scale(this.bv);
  52709. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  52710. };
  52711. return PickingInfo;
  52712. }());
  52713. BABYLON.PickingInfo = PickingInfo;
  52714. })(BABYLON || (BABYLON = {}));
  52715. //# sourceMappingURL=babylon.pickingInfo.js.map
  52716. "use strict";
  52717. var BABYLON;
  52718. (function (BABYLON) {
  52719. var Ray = /** @class */ (function () {
  52720. function Ray(origin, direction, length) {
  52721. if (length === void 0) { length = Number.MAX_VALUE; }
  52722. this.origin = origin;
  52723. this.direction = direction;
  52724. this.length = length;
  52725. }
  52726. // Methods
  52727. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  52728. var d = 0.0;
  52729. var maxValue = Number.MAX_VALUE;
  52730. var inv;
  52731. var min;
  52732. var max;
  52733. var temp;
  52734. if (Math.abs(this.direction.x) < 0.0000001) {
  52735. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  52736. return false;
  52737. }
  52738. }
  52739. else {
  52740. inv = 1.0 / this.direction.x;
  52741. min = (minimum.x - this.origin.x) * inv;
  52742. max = (maximum.x - this.origin.x) * inv;
  52743. if (max === -Infinity) {
  52744. max = Infinity;
  52745. }
  52746. if (min > max) {
  52747. temp = min;
  52748. min = max;
  52749. max = temp;
  52750. }
  52751. d = Math.max(min, d);
  52752. maxValue = Math.min(max, maxValue);
  52753. if (d > maxValue) {
  52754. return false;
  52755. }
  52756. }
  52757. if (Math.abs(this.direction.y) < 0.0000001) {
  52758. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  52759. return false;
  52760. }
  52761. }
  52762. else {
  52763. inv = 1.0 / this.direction.y;
  52764. min = (minimum.y - this.origin.y) * inv;
  52765. max = (maximum.y - this.origin.y) * inv;
  52766. if (max === -Infinity) {
  52767. max = Infinity;
  52768. }
  52769. if (min > max) {
  52770. temp = min;
  52771. min = max;
  52772. max = temp;
  52773. }
  52774. d = Math.max(min, d);
  52775. maxValue = Math.min(max, maxValue);
  52776. if (d > maxValue) {
  52777. return false;
  52778. }
  52779. }
  52780. if (Math.abs(this.direction.z) < 0.0000001) {
  52781. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  52782. return false;
  52783. }
  52784. }
  52785. else {
  52786. inv = 1.0 / this.direction.z;
  52787. min = (minimum.z - this.origin.z) * inv;
  52788. max = (maximum.z - this.origin.z) * inv;
  52789. if (max === -Infinity) {
  52790. max = Infinity;
  52791. }
  52792. if (min > max) {
  52793. temp = min;
  52794. min = max;
  52795. max = temp;
  52796. }
  52797. d = Math.max(min, d);
  52798. maxValue = Math.min(max, maxValue);
  52799. if (d > maxValue) {
  52800. return false;
  52801. }
  52802. }
  52803. return true;
  52804. };
  52805. Ray.prototype.intersectsBox = function (box) {
  52806. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  52807. };
  52808. Ray.prototype.intersectsSphere = function (sphere) {
  52809. var x = sphere.center.x - this.origin.x;
  52810. var y = sphere.center.y - this.origin.y;
  52811. var z = sphere.center.z - this.origin.z;
  52812. var pyth = (x * x) + (y * y) + (z * z);
  52813. var rr = sphere.radius * sphere.radius;
  52814. if (pyth <= rr) {
  52815. return true;
  52816. }
  52817. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  52818. if (dot < 0.0) {
  52819. return false;
  52820. }
  52821. var temp = pyth - (dot * dot);
  52822. return temp <= rr;
  52823. };
  52824. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  52825. if (!this._edge1) {
  52826. this._edge1 = BABYLON.Vector3.Zero();
  52827. this._edge2 = BABYLON.Vector3.Zero();
  52828. this._pvec = BABYLON.Vector3.Zero();
  52829. this._tvec = BABYLON.Vector3.Zero();
  52830. this._qvec = BABYLON.Vector3.Zero();
  52831. }
  52832. vertex1.subtractToRef(vertex0, this._edge1);
  52833. vertex2.subtractToRef(vertex0, this._edge2);
  52834. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  52835. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  52836. if (det === 0) {
  52837. return null;
  52838. }
  52839. var invdet = 1 / det;
  52840. this.origin.subtractToRef(vertex0, this._tvec);
  52841. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  52842. if (bu < 0 || bu > 1.0) {
  52843. return null;
  52844. }
  52845. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  52846. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  52847. if (bv < 0 || bu + bv > 1.0) {
  52848. return null;
  52849. }
  52850. //check if the distance is longer than the predefined length.
  52851. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  52852. if (distance > this.length) {
  52853. return null;
  52854. }
  52855. return new BABYLON.IntersectionInfo(bu, bv, distance);
  52856. };
  52857. Ray.prototype.intersectsPlane = function (plane) {
  52858. var distance;
  52859. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  52860. if (Math.abs(result1) < 9.99999997475243E-07) {
  52861. return null;
  52862. }
  52863. else {
  52864. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  52865. distance = (-plane.d - result2) / result1;
  52866. if (distance < 0.0) {
  52867. if (distance < -9.99999997475243E-07) {
  52868. return null;
  52869. }
  52870. else {
  52871. return 0;
  52872. }
  52873. }
  52874. return distance;
  52875. }
  52876. };
  52877. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  52878. var tm = BABYLON.Tmp.Matrix[0];
  52879. mesh.getWorldMatrix().invertToRef(tm);
  52880. if (this._tmpRay) {
  52881. Ray.TransformToRef(this, tm, this._tmpRay);
  52882. }
  52883. else {
  52884. this._tmpRay = Ray.Transform(this, tm);
  52885. }
  52886. return mesh.intersects(this._tmpRay, fastCheck);
  52887. };
  52888. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  52889. if (results) {
  52890. results.length = 0;
  52891. }
  52892. else {
  52893. results = [];
  52894. }
  52895. for (var i = 0; i < meshes.length; i++) {
  52896. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  52897. if (pickInfo.hit) {
  52898. results.push(pickInfo);
  52899. }
  52900. }
  52901. results.sort(this._comparePickingInfo);
  52902. return results;
  52903. };
  52904. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  52905. if (pickingInfoA.distance < pickingInfoB.distance) {
  52906. return -1;
  52907. }
  52908. else if (pickingInfoA.distance > pickingInfoB.distance) {
  52909. return 1;
  52910. }
  52911. else {
  52912. return 0;
  52913. }
  52914. };
  52915. /**
  52916. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  52917. * @param sega the first point of the segment to test the intersection against
  52918. * @param segb the second point of the segment to test the intersection against
  52919. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  52920. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  52921. */
  52922. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  52923. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  52924. var u = segb.subtract(sega);
  52925. var v = rsegb.subtract(this.origin);
  52926. var w = sega.subtract(this.origin);
  52927. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  52928. var b = BABYLON.Vector3.Dot(u, v);
  52929. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  52930. var d = BABYLON.Vector3.Dot(u, w);
  52931. var e = BABYLON.Vector3.Dot(v, w);
  52932. var D = a * c - b * b; // always >= 0
  52933. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  52934. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  52935. // compute the line parameters of the two closest points
  52936. if (D < Ray.smallnum) {
  52937. sN = 0.0; // force using point P0 on segment S1
  52938. sD = 1.0; // to prevent possible division by 0.0 later
  52939. tN = e;
  52940. tD = c;
  52941. }
  52942. else {
  52943. sN = (b * e - c * d);
  52944. tN = (a * e - b * d);
  52945. if (sN < 0.0) {
  52946. sN = 0.0;
  52947. tN = e;
  52948. tD = c;
  52949. }
  52950. else if (sN > sD) {
  52951. sN = sD;
  52952. tN = e + b;
  52953. tD = c;
  52954. }
  52955. }
  52956. if (tN < 0.0) {
  52957. tN = 0.0;
  52958. // recompute sc for this edge
  52959. if (-d < 0.0) {
  52960. sN = 0.0;
  52961. }
  52962. else if (-d > a)
  52963. sN = sD;
  52964. else {
  52965. sN = -d;
  52966. sD = a;
  52967. }
  52968. }
  52969. else if (tN > tD) {
  52970. tN = tD;
  52971. // recompute sc for this edge
  52972. if ((-d + b) < 0.0) {
  52973. sN = 0;
  52974. }
  52975. else if ((-d + b) > a) {
  52976. sN = sD;
  52977. }
  52978. else {
  52979. sN = (-d + b);
  52980. sD = a;
  52981. }
  52982. }
  52983. // finally do the division to get sc and tc
  52984. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  52985. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  52986. // get the difference of the two closest points
  52987. var qtc = v.multiplyByFloats(tc, tc, tc);
  52988. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  52989. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  52990. if (isIntersected) {
  52991. return qtc.length();
  52992. }
  52993. return -1;
  52994. };
  52995. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  52996. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  52997. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  52998. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  52999. this.direction.normalize();
  53000. return this;
  53001. };
  53002. // Statics
  53003. Ray.Zero = function () {
  53004. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53005. };
  53006. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53007. var result = Ray.Zero();
  53008. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53009. };
  53010. /**
  53011. * 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
  53012. * transformed to the given world matrix.
  53013. * @param origin The origin point
  53014. * @param end The end point
  53015. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53016. */
  53017. Ray.CreateNewFromTo = function (origin, end, world) {
  53018. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53019. var direction = end.subtract(origin);
  53020. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53021. direction.normalize();
  53022. return Ray.Transform(new Ray(origin, direction, length), world);
  53023. };
  53024. Ray.Transform = function (ray, matrix) {
  53025. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53026. Ray.TransformToRef(ray, matrix, result);
  53027. return result;
  53028. };
  53029. Ray.TransformToRef = function (ray, matrix, result) {
  53030. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53031. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53032. result.length = ray.length;
  53033. var dir = result.direction;
  53034. var len = dir.length();
  53035. if (!(len === 0 || len === 1)) {
  53036. var num = 1.0 / len;
  53037. dir.x *= num;
  53038. dir.y *= num;
  53039. dir.z *= num;
  53040. result.length *= len;
  53041. }
  53042. };
  53043. Ray.smallnum = 0.00000001;
  53044. Ray.rayl = 10e8;
  53045. return Ray;
  53046. }());
  53047. BABYLON.Ray = Ray;
  53048. })(BABYLON || (BABYLON = {}));
  53049. //# sourceMappingURL=babylon.ray.js.map
  53050. "use strict";
  53051. var BABYLON;
  53052. (function (BABYLON) {
  53053. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53054. if (boxMin.x > sphereCenter.x + sphereRadius)
  53055. return false;
  53056. if (sphereCenter.x - sphereRadius > boxMax.x)
  53057. return false;
  53058. if (boxMin.y > sphereCenter.y + sphereRadius)
  53059. return false;
  53060. if (sphereCenter.y - sphereRadius > boxMax.y)
  53061. return false;
  53062. if (boxMin.z > sphereCenter.z + sphereRadius)
  53063. return false;
  53064. if (sphereCenter.z - sphereRadius > boxMax.z)
  53065. return false;
  53066. return true;
  53067. };
  53068. var getLowestRoot = (function () {
  53069. var result = { root: 0, found: false };
  53070. return function (a, b, c, maxR) {
  53071. result.root = 0;
  53072. result.found = false;
  53073. var determinant = b * b - 4.0 * a * c;
  53074. if (determinant < 0)
  53075. return result;
  53076. var sqrtD = Math.sqrt(determinant);
  53077. var r1 = (-b - sqrtD) / (2.0 * a);
  53078. var r2 = (-b + sqrtD) / (2.0 * a);
  53079. if (r1 > r2) {
  53080. var temp = r2;
  53081. r2 = r1;
  53082. r1 = temp;
  53083. }
  53084. if (r1 > 0 && r1 < maxR) {
  53085. result.root = r1;
  53086. result.found = true;
  53087. return result;
  53088. }
  53089. if (r2 > 0 && r2 < maxR) {
  53090. result.root = r2;
  53091. result.found = true;
  53092. return result;
  53093. }
  53094. return result;
  53095. };
  53096. })();
  53097. var Collider = /** @class */ (function () {
  53098. function Collider() {
  53099. this._collisionPoint = BABYLON.Vector3.Zero();
  53100. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53101. this._tempVector = BABYLON.Vector3.Zero();
  53102. this._tempVector2 = BABYLON.Vector3.Zero();
  53103. this._tempVector3 = BABYLON.Vector3.Zero();
  53104. this._tempVector4 = BABYLON.Vector3.Zero();
  53105. this._edge = BABYLON.Vector3.Zero();
  53106. this._baseToVertex = BABYLON.Vector3.Zero();
  53107. this._destinationPoint = BABYLON.Vector3.Zero();
  53108. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53109. this._displacementVector = BABYLON.Vector3.Zero();
  53110. this._radius = BABYLON.Vector3.One();
  53111. this._retry = 0;
  53112. this._basePointWorld = BABYLON.Vector3.Zero();
  53113. this._velocityWorld = BABYLON.Vector3.Zero();
  53114. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53115. this._collisionMask = -1;
  53116. }
  53117. Object.defineProperty(Collider.prototype, "collisionMask", {
  53118. get: function () {
  53119. return this._collisionMask;
  53120. },
  53121. set: function (mask) {
  53122. this._collisionMask = !isNaN(mask) ? mask : -1;
  53123. },
  53124. enumerable: true,
  53125. configurable: true
  53126. });
  53127. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53128. /**
  53129. * Gets the plane normal used to compute the sliding response (in local space)
  53130. */
  53131. get: function () {
  53132. return this._slidePlaneNormal;
  53133. },
  53134. enumerable: true,
  53135. configurable: true
  53136. });
  53137. // Methods
  53138. Collider.prototype._initialize = function (source, dir, e) {
  53139. this._velocity = dir;
  53140. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53141. this._basePoint = source;
  53142. source.multiplyToRef(this._radius, this._basePointWorld);
  53143. dir.multiplyToRef(this._radius, this._velocityWorld);
  53144. this._velocityWorldLength = this._velocityWorld.length();
  53145. this._epsilon = e;
  53146. this.collisionFound = false;
  53147. };
  53148. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53149. pa.subtractToRef(point, this._tempVector);
  53150. pb.subtractToRef(point, this._tempVector2);
  53151. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53152. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53153. if (d < 0)
  53154. return false;
  53155. pc.subtractToRef(point, this._tempVector3);
  53156. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53157. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53158. if (d < 0)
  53159. return false;
  53160. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53161. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53162. return d >= 0;
  53163. };
  53164. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53165. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53166. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53167. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53168. return false;
  53169. }
  53170. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53171. return false;
  53172. return true;
  53173. };
  53174. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53175. var t0;
  53176. var embeddedInPlane = false;
  53177. //defensive programming, actually not needed.
  53178. if (!trianglePlaneArray) {
  53179. trianglePlaneArray = [];
  53180. }
  53181. if (!trianglePlaneArray[faceIndex]) {
  53182. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53183. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53184. }
  53185. var trianglePlane = trianglePlaneArray[faceIndex];
  53186. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53187. return;
  53188. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53189. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53190. if (normalDotVelocity == 0) {
  53191. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53192. return;
  53193. embeddedInPlane = true;
  53194. t0 = 0;
  53195. }
  53196. else {
  53197. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53198. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53199. if (t0 > t1) {
  53200. var temp = t1;
  53201. t1 = t0;
  53202. t0 = temp;
  53203. }
  53204. if (t0 > 1.0 || t1 < 0.0)
  53205. return;
  53206. if (t0 < 0)
  53207. t0 = 0;
  53208. if (t0 > 1.0)
  53209. t0 = 1.0;
  53210. }
  53211. this._collisionPoint.copyFromFloats(0, 0, 0);
  53212. var found = false;
  53213. var t = 1.0;
  53214. if (!embeddedInPlane) {
  53215. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53216. this._velocity.scaleToRef(t0, this._tempVector);
  53217. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53218. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53219. found = true;
  53220. t = t0;
  53221. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53222. }
  53223. }
  53224. if (!found) {
  53225. var velocitySquaredLength = this._velocity.lengthSquared();
  53226. var a = velocitySquaredLength;
  53227. this._basePoint.subtractToRef(p1, this._tempVector);
  53228. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53229. var c = this._tempVector.lengthSquared() - 1.0;
  53230. var lowestRoot = getLowestRoot(a, b, c, t);
  53231. if (lowestRoot.found) {
  53232. t = lowestRoot.root;
  53233. found = true;
  53234. this._collisionPoint.copyFrom(p1);
  53235. }
  53236. this._basePoint.subtractToRef(p2, this._tempVector);
  53237. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53238. c = this._tempVector.lengthSquared() - 1.0;
  53239. lowestRoot = getLowestRoot(a, b, c, t);
  53240. if (lowestRoot.found) {
  53241. t = lowestRoot.root;
  53242. found = true;
  53243. this._collisionPoint.copyFrom(p2);
  53244. }
  53245. this._basePoint.subtractToRef(p3, this._tempVector);
  53246. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53247. c = this._tempVector.lengthSquared() - 1.0;
  53248. lowestRoot = getLowestRoot(a, b, c, t);
  53249. if (lowestRoot.found) {
  53250. t = lowestRoot.root;
  53251. found = true;
  53252. this._collisionPoint.copyFrom(p3);
  53253. }
  53254. p2.subtractToRef(p1, this._edge);
  53255. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53256. var edgeSquaredLength = this._edge.lengthSquared();
  53257. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53258. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53259. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53260. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53261. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53262. lowestRoot = getLowestRoot(a, b, c, t);
  53263. if (lowestRoot.found) {
  53264. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53265. if (f >= 0.0 && f <= 1.0) {
  53266. t = lowestRoot.root;
  53267. found = true;
  53268. this._edge.scaleInPlace(f);
  53269. p1.addToRef(this._edge, this._collisionPoint);
  53270. }
  53271. }
  53272. p3.subtractToRef(p2, this._edge);
  53273. p2.subtractToRef(this._basePoint, this._baseToVertex);
  53274. edgeSquaredLength = this._edge.lengthSquared();
  53275. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53276. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53277. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53278. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53279. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53280. lowestRoot = getLowestRoot(a, b, c, t);
  53281. if (lowestRoot.found) {
  53282. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53283. if (f >= 0.0 && f <= 1.0) {
  53284. t = lowestRoot.root;
  53285. found = true;
  53286. this._edge.scaleInPlace(f);
  53287. p2.addToRef(this._edge, this._collisionPoint);
  53288. }
  53289. }
  53290. p1.subtractToRef(p3, this._edge);
  53291. p3.subtractToRef(this._basePoint, this._baseToVertex);
  53292. edgeSquaredLength = this._edge.lengthSquared();
  53293. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53294. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53295. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53296. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53297. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53298. lowestRoot = getLowestRoot(a, b, c, t);
  53299. if (lowestRoot.found) {
  53300. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53301. if (f >= 0.0 && f <= 1.0) {
  53302. t = lowestRoot.root;
  53303. found = true;
  53304. this._edge.scaleInPlace(f);
  53305. p3.addToRef(this._edge, this._collisionPoint);
  53306. }
  53307. }
  53308. }
  53309. if (found) {
  53310. var distToCollision = t * this._velocity.length();
  53311. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  53312. if (!this.intersectionPoint) {
  53313. this.intersectionPoint = this._collisionPoint.clone();
  53314. }
  53315. else {
  53316. this.intersectionPoint.copyFrom(this._collisionPoint);
  53317. }
  53318. this._nearestDistance = distToCollision;
  53319. this.collisionFound = true;
  53320. }
  53321. }
  53322. };
  53323. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  53324. for (var i = indexStart; i < indexEnd; i += 3) {
  53325. var p1 = pts[indices[i] - decal];
  53326. var p2 = pts[indices[i + 1] - decal];
  53327. var p3 = pts[indices[i + 2] - decal];
  53328. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  53329. }
  53330. };
  53331. Collider.prototype._getResponse = function (pos, vel) {
  53332. pos.addToRef(vel, this._destinationPoint);
  53333. vel.scaleInPlace((this._nearestDistance / vel.length()));
  53334. this._basePoint.addToRef(vel, pos);
  53335. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  53336. this._slidePlaneNormal.normalize();
  53337. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  53338. pos.addInPlace(this._displacementVector);
  53339. this.intersectionPoint.addInPlace(this._displacementVector);
  53340. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  53341. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  53342. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  53343. };
  53344. return Collider;
  53345. }());
  53346. BABYLON.Collider = Collider;
  53347. })(BABYLON || (BABYLON = {}));
  53348. //# sourceMappingURL=babylon.collider.js.map
  53349. "use strict";
  53350. var BABYLON;
  53351. (function (BABYLON) {
  53352. //WebWorker code will be inserted to this variable.
  53353. BABYLON.CollisionWorker = "";
  53354. var WorkerTaskType;
  53355. (function (WorkerTaskType) {
  53356. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  53357. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  53358. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  53359. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  53360. var WorkerReplyType;
  53361. (function (WorkerReplyType) {
  53362. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  53363. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  53364. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  53365. var CollisionCoordinatorWorker = /** @class */ (function () {
  53366. function CollisionCoordinatorWorker() {
  53367. var _this = this;
  53368. this._scaledPosition = BABYLON.Vector3.Zero();
  53369. this._scaledVelocity = BABYLON.Vector3.Zero();
  53370. this.onMeshUpdated = function (transformNode) {
  53371. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  53372. };
  53373. this.onGeometryUpdated = function (geometry) {
  53374. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  53375. };
  53376. this._afterRender = function () {
  53377. if (!_this._init)
  53378. return;
  53379. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  53380. return;
  53381. }
  53382. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  53383. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  53384. if (_this._runningUpdated > 4) {
  53385. return;
  53386. }
  53387. ++_this._runningUpdated;
  53388. var payload = {
  53389. updatedMeshes: _this._addUpdateMeshesList,
  53390. updatedGeometries: _this._addUpdateGeometriesList,
  53391. removedGeometries: _this._toRemoveGeometryArray,
  53392. removedMeshes: _this._toRemoveMeshesArray
  53393. };
  53394. var message = {
  53395. payload: payload,
  53396. taskType: WorkerTaskType.UPDATE
  53397. };
  53398. var serializable = [];
  53399. for (var id in payload.updatedGeometries) {
  53400. if (payload.updatedGeometries.hasOwnProperty(id)) {
  53401. //prepare transferables
  53402. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  53403. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  53404. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  53405. }
  53406. }
  53407. _this._worker.postMessage(message, serializable);
  53408. _this._addUpdateMeshesList = {};
  53409. _this._addUpdateGeometriesList = {};
  53410. _this._toRemoveGeometryArray = [];
  53411. _this._toRemoveMeshesArray = [];
  53412. };
  53413. this._onMessageFromWorker = function (e) {
  53414. var returnData = e.data;
  53415. if (returnData.error != WorkerReplyType.SUCCESS) {
  53416. //TODO what errors can be returned from the worker?
  53417. BABYLON.Tools.Warn("error returned from worker!");
  53418. return;
  53419. }
  53420. switch (returnData.taskType) {
  53421. case WorkerTaskType.INIT:
  53422. _this._init = true;
  53423. //Update the worked with ALL of the scene's current state
  53424. _this._scene.meshes.forEach(function (mesh) {
  53425. _this.onMeshAdded(mesh);
  53426. });
  53427. _this._scene.getGeometries().forEach(function (geometry) {
  53428. _this.onGeometryAdded(geometry);
  53429. });
  53430. break;
  53431. case WorkerTaskType.UPDATE:
  53432. _this._runningUpdated--;
  53433. break;
  53434. case WorkerTaskType.COLLIDE:
  53435. var returnPayload = returnData.payload;
  53436. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  53437. return;
  53438. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  53439. if (callback) {
  53440. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  53441. if (mesh) {
  53442. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  53443. }
  53444. }
  53445. //cleanup
  53446. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  53447. break;
  53448. }
  53449. };
  53450. this._collisionsCallbackArray = [];
  53451. this._init = false;
  53452. this._runningUpdated = 0;
  53453. this._addUpdateMeshesList = {};
  53454. this._addUpdateGeometriesList = {};
  53455. this._toRemoveGeometryArray = [];
  53456. this._toRemoveMeshesArray = [];
  53457. }
  53458. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53459. if (!this._init)
  53460. return;
  53461. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  53462. return;
  53463. position.divideToRef(collider._radius, this._scaledPosition);
  53464. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53465. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  53466. var payload = {
  53467. collider: {
  53468. position: this._scaledPosition.asArray(),
  53469. velocity: this._scaledVelocity.asArray(),
  53470. radius: collider._radius.asArray()
  53471. },
  53472. collisionId: collisionIndex,
  53473. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  53474. maximumRetry: maximumRetry
  53475. };
  53476. var message = {
  53477. payload: payload,
  53478. taskType: WorkerTaskType.COLLIDE
  53479. };
  53480. this._worker.postMessage(message);
  53481. };
  53482. CollisionCoordinatorWorker.prototype.init = function (scene) {
  53483. this._scene = scene;
  53484. this._scene.registerAfterRender(this._afterRender);
  53485. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  53486. this._worker = new Worker(workerUrl);
  53487. this._worker.onmessage = this._onMessageFromWorker;
  53488. var message = {
  53489. payload: {},
  53490. taskType: WorkerTaskType.INIT
  53491. };
  53492. this._worker.postMessage(message);
  53493. };
  53494. CollisionCoordinatorWorker.prototype.destroy = function () {
  53495. this._scene.unregisterAfterRender(this._afterRender);
  53496. this._worker.terminate();
  53497. };
  53498. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  53499. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  53500. this.onMeshUpdated(mesh);
  53501. };
  53502. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  53503. this._toRemoveMeshesArray.push(mesh.uniqueId);
  53504. };
  53505. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  53506. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  53507. geometry.onGeometryUpdated = this.onGeometryUpdated;
  53508. this.onGeometryUpdated(geometry);
  53509. };
  53510. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  53511. this._toRemoveGeometryArray.push(geometry.id);
  53512. };
  53513. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  53514. var submeshes = [];
  53515. if (mesh.subMeshes) {
  53516. submeshes = mesh.subMeshes.map(function (sm, idx) {
  53517. var boundingInfo = sm.getBoundingInfo();
  53518. return {
  53519. position: idx,
  53520. verticesStart: sm.verticesStart,
  53521. verticesCount: sm.verticesCount,
  53522. indexStart: sm.indexStart,
  53523. indexCount: sm.indexCount,
  53524. hasMaterial: !!sm.getMaterial(),
  53525. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53526. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53527. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53528. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  53529. };
  53530. });
  53531. }
  53532. var geometryId = null;
  53533. if (mesh instanceof BABYLON.Mesh) {
  53534. var geometry = mesh.geometry;
  53535. geometryId = geometry ? geometry.id : null;
  53536. }
  53537. else if (mesh instanceof BABYLON.InstancedMesh) {
  53538. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  53539. geometryId = geometry ? geometry.id : null;
  53540. }
  53541. var boundingInfo = mesh.getBoundingInfo();
  53542. return {
  53543. uniqueId: mesh.uniqueId,
  53544. id: mesh.id,
  53545. name: mesh.name,
  53546. geometryId: geometryId,
  53547. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53548. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53549. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53550. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  53551. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  53552. subMeshes: submeshes,
  53553. checkCollisions: mesh.checkCollisions
  53554. };
  53555. };
  53556. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  53557. return {
  53558. id: geometry.id,
  53559. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  53560. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  53561. indices: new Uint32Array(geometry.getIndices() || []),
  53562. };
  53563. };
  53564. return CollisionCoordinatorWorker;
  53565. }());
  53566. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  53567. var CollisionCoordinatorLegacy = /** @class */ (function () {
  53568. function CollisionCoordinatorLegacy() {
  53569. this._scaledPosition = BABYLON.Vector3.Zero();
  53570. this._scaledVelocity = BABYLON.Vector3.Zero();
  53571. this._finalPosition = BABYLON.Vector3.Zero();
  53572. }
  53573. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53574. position.divideToRef(collider._radius, this._scaledPosition);
  53575. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53576. collider.collidedMesh = null;
  53577. collider._retry = 0;
  53578. collider._initialVelocity = this._scaledVelocity;
  53579. collider._initialPosition = this._scaledPosition;
  53580. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  53581. this._finalPosition.multiplyInPlace(collider._radius);
  53582. //run the callback
  53583. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  53584. };
  53585. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  53586. this._scene = scene;
  53587. };
  53588. CollisionCoordinatorLegacy.prototype.destroy = function () {
  53589. //Legacy need no destruction method.
  53590. };
  53591. //No update in legacy mode
  53592. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  53593. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  53594. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  53595. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  53596. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  53597. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  53598. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  53599. if (excludedMesh === void 0) { excludedMesh = null; }
  53600. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  53601. if (collider._retry >= maximumRetry) {
  53602. finalPosition.copyFrom(position);
  53603. return;
  53604. }
  53605. // Check if this is a mesh else camera or -1
  53606. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  53607. collider._initialize(position, velocity, closeDistance);
  53608. // Check all meshes
  53609. for (var index = 0; index < this._scene.meshes.length; index++) {
  53610. var mesh = this._scene.meshes[index];
  53611. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  53612. mesh._checkCollision(collider);
  53613. }
  53614. }
  53615. if (!collider.collisionFound) {
  53616. position.addToRef(velocity, finalPosition);
  53617. return;
  53618. }
  53619. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  53620. collider._getResponse(position, velocity);
  53621. }
  53622. if (velocity.length() <= closeDistance) {
  53623. finalPosition.copyFrom(position);
  53624. return;
  53625. }
  53626. collider._retry++;
  53627. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  53628. };
  53629. return CollisionCoordinatorLegacy;
  53630. }());
  53631. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  53632. })(BABYLON || (BABYLON = {}));
  53633. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  53634. "use strict";
  53635. var BABYLON;
  53636. (function (BABYLON) {
  53637. /**
  53638. * A particle represents one of the element emitted by a particle system.
  53639. * This is mainly define by its coordinates, direction, velocity and age.
  53640. */
  53641. var Particle = /** @class */ (function () {
  53642. /**
  53643. * Creates a new instance Particle
  53644. * @param particleSystem the particle system the particle belongs to
  53645. */
  53646. function Particle(
  53647. /**
  53648. * particleSystem the particle system the particle belongs to.
  53649. */
  53650. particleSystem) {
  53651. this.particleSystem = particleSystem;
  53652. /**
  53653. * The world position of the particle in the scene.
  53654. */
  53655. this.position = BABYLON.Vector3.Zero();
  53656. /**
  53657. * The world direction of the particle in the scene.
  53658. */
  53659. this.direction = BABYLON.Vector3.Zero();
  53660. /**
  53661. * The color of the particle.
  53662. */
  53663. this.color = new BABYLON.Color4(0, 0, 0, 0);
  53664. /**
  53665. * The color change of the particle per step.
  53666. */
  53667. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  53668. /**
  53669. * Defines how long will the life of the particle be.
  53670. */
  53671. this.lifeTime = 1.0;
  53672. /**
  53673. * The current age of the particle.
  53674. */
  53675. this.age = 0;
  53676. /**
  53677. * The current size of the particle.
  53678. */
  53679. this.size = 0;
  53680. /**
  53681. * The current angle of the particle.
  53682. */
  53683. this.angle = 0;
  53684. /**
  53685. * Defines how fast is the angle changing.
  53686. */
  53687. this.angularSpeed = 0;
  53688. /**
  53689. * Defines the cell index used by the particle to be rendered from a sprite.
  53690. */
  53691. this.cellIndex = 0;
  53692. this._currentFrameCounter = 0;
  53693. if (!this.particleSystem.isAnimationSheetEnabled) {
  53694. return;
  53695. }
  53696. this.updateCellInfoFromSystem();
  53697. }
  53698. Particle.prototype.updateCellInfoFromSystem = function () {
  53699. this.cellIndex = this.particleSystem.startSpriteCellID;
  53700. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  53701. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  53702. }
  53703. else {
  53704. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  53705. }
  53706. };
  53707. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  53708. // (ageOffset / scaledUpdateSpeed) / available cells
  53709. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  53710. this._currentFrameCounter += scaledUpdateSpeed;
  53711. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  53712. this._currentFrameCounter = 0;
  53713. this.cellIndex++;
  53714. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  53715. this.cellIndex = this.particleSystem.endSpriteCellID;
  53716. }
  53717. }
  53718. };
  53719. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  53720. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  53721. this.cellIndex++;
  53722. this._currentFrameCounter = 0;
  53723. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  53724. if (this.particleSystem.spriteCellLoop) {
  53725. this.cellIndex = this.particleSystem.startSpriteCellID;
  53726. }
  53727. else {
  53728. this.cellIndex = this.particleSystem.endSpriteCellID;
  53729. }
  53730. }
  53731. }
  53732. else {
  53733. this._currentFrameCounter++;
  53734. }
  53735. };
  53736. /**
  53737. * Copy the properties of particle to another one.
  53738. * @param other the particle to copy the information to.
  53739. */
  53740. Particle.prototype.copyTo = function (other) {
  53741. other.position.copyFrom(this.position);
  53742. other.direction.copyFrom(this.direction);
  53743. other.color.copyFrom(this.color);
  53744. other.colorStep.copyFrom(this.colorStep);
  53745. other.lifeTime = this.lifeTime;
  53746. other.age = this.age;
  53747. other.size = this.size;
  53748. other.angle = this.angle;
  53749. other.angularSpeed = this.angularSpeed;
  53750. other.particleSystem = this.particleSystem;
  53751. other.cellIndex = this.cellIndex;
  53752. };
  53753. return Particle;
  53754. }());
  53755. BABYLON.Particle = Particle;
  53756. })(BABYLON || (BABYLON = {}));
  53757. //# sourceMappingURL=babylon.particle.js.map
  53758. "use strict";
  53759. var BABYLON;
  53760. (function (BABYLON) {
  53761. /**
  53762. * This represents a particle system in Babylon.
  53763. * 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.
  53764. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  53765. * @example https://doc.babylonjs.com/babylon101/particles
  53766. */
  53767. var ParticleSystem = /** @class */ (function () {
  53768. /**
  53769. * Instantiates a particle system.
  53770. * 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.
  53771. * @param name The name of the particle system
  53772. * @param capacity The max number of particles alive at the same time
  53773. * @param scene The scene the particle system belongs to
  53774. * @param customEffect a custom effect used to change the way particles are rendered by default
  53775. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  53776. * @param epsilon Offset used to render the particles
  53777. */
  53778. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  53779. if (customEffect === void 0) { customEffect = null; }
  53780. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  53781. if (epsilon === void 0) { epsilon = 0.01; }
  53782. var _this = this;
  53783. /**
  53784. * List of animations used by the particle system.
  53785. */
  53786. this.animations = [];
  53787. /**
  53788. * The rendering group used by the Particle system to chose when to render.
  53789. */
  53790. this.renderingGroupId = 0;
  53791. /**
  53792. * The emitter represents the Mesh or position we are attaching the particle system to.
  53793. */
  53794. this.emitter = null;
  53795. /**
  53796. * The maximum number of particles to emit per frame
  53797. */
  53798. this.emitRate = 10;
  53799. /**
  53800. * If you want to launch only a few particles at once, that can be done, as well.
  53801. */
  53802. this.manualEmitCount = -1;
  53803. /**
  53804. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53805. */
  53806. this.updateSpeed = 0.01;
  53807. /**
  53808. * The amount of time the particle system is running (depends of the overall update speed).
  53809. */
  53810. this.targetStopDuration = 0;
  53811. /**
  53812. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  53813. */
  53814. this.disposeOnStop = false;
  53815. /**
  53816. * Minimum power of emitting particles.
  53817. */
  53818. this.minEmitPower = 1;
  53819. /**
  53820. * Maximum power of emitting particles.
  53821. */
  53822. this.maxEmitPower = 1;
  53823. /**
  53824. * Minimum life time of emitting particles.
  53825. */
  53826. this.minLifeTime = 1;
  53827. /**
  53828. * Maximum life time of emitting particles.
  53829. */
  53830. this.maxLifeTime = 1;
  53831. /**
  53832. * Minimum Size of emitting particles.
  53833. */
  53834. this.minSize = 1;
  53835. /**
  53836. * Maximum Size of emitting particles.
  53837. */
  53838. this.maxSize = 1;
  53839. /**
  53840. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  53841. */
  53842. this.minAngularSpeed = 0;
  53843. /**
  53844. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  53845. */
  53846. this.maxAngularSpeed = 0;
  53847. /**
  53848. * The layer mask we are rendering the particles through.
  53849. */
  53850. this.layerMask = 0x0FFFFFFF;
  53851. /**
  53852. * This can help using your own shader to render the particle system.
  53853. * The according effect will be created
  53854. */
  53855. this.customShader = null;
  53856. /**
  53857. * By default particle system starts as soon as they are created. This prevents the
  53858. * automatic start to happen and let you decide when to start emitting particles.
  53859. */
  53860. this.preventAutoStart = false;
  53861. /**
  53862. * Callback triggered when the particle animation is ending.
  53863. */
  53864. this.onAnimationEnd = null;
  53865. /**
  53866. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53867. */
  53868. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  53869. /**
  53870. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53871. * to override the particles.
  53872. */
  53873. this.forceDepthWrite = false;
  53874. /**
  53875. * You can use gravity if you want to give an orientation to your particles.
  53876. */
  53877. this.gravity = BABYLON.Vector3.Zero();
  53878. /**
  53879. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53880. */
  53881. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53882. /**
  53883. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53884. */
  53885. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53886. /**
  53887. * Color the particle will have at the end of its lifetime.
  53888. */
  53889. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  53890. /**
  53891. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  53892. */
  53893. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53894. /**
  53895. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  53896. */
  53897. this.spriteCellLoop = true;
  53898. /**
  53899. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  53900. */
  53901. this.spriteCellChangeSpeed = 0;
  53902. /**
  53903. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  53904. */
  53905. this.startSpriteCellID = 0;
  53906. /**
  53907. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  53908. */
  53909. this.endSpriteCellID = 0;
  53910. /**
  53911. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  53912. */
  53913. this.spriteCellWidth = 0;
  53914. /**
  53915. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  53916. */
  53917. this.spriteCellHeight = 0;
  53918. /**
  53919. * An event triggered when the system is disposed.
  53920. */
  53921. this.onDisposeObservable = new BABYLON.Observable();
  53922. this._particles = new Array();
  53923. this._stockParticles = new Array();
  53924. this._newPartsExcess = 0;
  53925. this._vertexBuffers = {};
  53926. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  53927. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  53928. this._scaledDirection = BABYLON.Vector3.Zero();
  53929. this._scaledGravity = BABYLON.Vector3.Zero();
  53930. this._currentRenderId = -1;
  53931. this._started = false;
  53932. this._stopped = false;
  53933. this._actualFrame = 0;
  53934. this._vertexBufferSize = 11;
  53935. // start of sub system methods
  53936. /**
  53937. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  53938. * Its lifetime will start back at 0.
  53939. */
  53940. this.recycleParticle = function (particle) {
  53941. var lastParticle = _this._particles.pop();
  53942. if (lastParticle !== particle) {
  53943. lastParticle.copyTo(particle);
  53944. }
  53945. _this._stockParticles.push(lastParticle);
  53946. };
  53947. this._createParticle = function () {
  53948. var particle;
  53949. if (_this._stockParticles.length !== 0) {
  53950. particle = _this._stockParticles.pop();
  53951. particle.age = 0;
  53952. particle.cellIndex = _this.startSpriteCellID;
  53953. }
  53954. else {
  53955. particle = new BABYLON.Particle(_this);
  53956. }
  53957. return particle;
  53958. };
  53959. this._emitFromParticle = function (particle) {
  53960. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  53961. return;
  53962. }
  53963. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  53964. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  53965. subSystem._rootParticleSystem = _this;
  53966. _this.activeSubSystems.push(subSystem);
  53967. subSystem.start();
  53968. };
  53969. this._appendParticleVertexes = null;
  53970. this.id = name;
  53971. this.name = name;
  53972. this._capacity = capacity;
  53973. this._epsilon = epsilon;
  53974. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  53975. if (isAnimationSheetEnabled) {
  53976. this._vertexBufferSize = 12;
  53977. }
  53978. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53979. this._customEffect = customEffect;
  53980. scene.particleSystems.push(this);
  53981. this._createIndexBuffer();
  53982. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  53983. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  53984. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  53985. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  53986. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  53987. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  53988. if (this._isAnimationSheetEnabled) {
  53989. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  53990. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  53991. }
  53992. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53993. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53994. this._vertexBuffers["options"] = options;
  53995. // Default emitter type
  53996. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53997. this.updateFunction = function (particles) {
  53998. for (var index = 0; index < particles.length; index++) {
  53999. var particle = particles[index];
  54000. particle.age += _this._scaledUpdateSpeed;
  54001. if (particle.age >= particle.lifeTime) {
  54002. _this._emitFromParticle(particle);
  54003. _this.recycleParticle(particle);
  54004. index--;
  54005. continue;
  54006. }
  54007. else {
  54008. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54009. particle.color.addInPlace(_this._scaledColorStep);
  54010. if (particle.color.a < 0)
  54011. particle.color.a = 0;
  54012. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54013. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54014. particle.position.addInPlace(_this._scaledDirection);
  54015. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54016. particle.direction.addInPlace(_this._scaledGravity);
  54017. if (_this._isAnimationSheetEnabled) {
  54018. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54019. }
  54020. }
  54021. }
  54022. };
  54023. }
  54024. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54025. /**
  54026. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54027. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54028. */
  54029. get: function () {
  54030. if (this.particleEmitterType.direction1) {
  54031. return this.particleEmitterType.direction1;
  54032. }
  54033. return BABYLON.Vector3.Zero();
  54034. },
  54035. set: function (value) {
  54036. if (this.particleEmitterType.direction1) {
  54037. this.particleEmitterType.direction1 = value;
  54038. }
  54039. },
  54040. enumerable: true,
  54041. configurable: true
  54042. });
  54043. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54044. /**
  54045. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54046. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54047. */
  54048. get: function () {
  54049. if (this.particleEmitterType.direction2) {
  54050. return this.particleEmitterType.direction2;
  54051. }
  54052. return BABYLON.Vector3.Zero();
  54053. },
  54054. set: function (value) {
  54055. if (this.particleEmitterType.direction2) {
  54056. this.particleEmitterType.direction2 = value;
  54057. }
  54058. },
  54059. enumerable: true,
  54060. configurable: true
  54061. });
  54062. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54063. /**
  54064. * 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.
  54065. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54066. */
  54067. get: function () {
  54068. if (this.particleEmitterType.minEmitBox) {
  54069. return this.particleEmitterType.minEmitBox;
  54070. }
  54071. return BABYLON.Vector3.Zero();
  54072. },
  54073. set: function (value) {
  54074. if (this.particleEmitterType.minEmitBox) {
  54075. this.particleEmitterType.minEmitBox = value;
  54076. }
  54077. },
  54078. enumerable: true,
  54079. configurable: true
  54080. });
  54081. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54082. /**
  54083. * 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.
  54084. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54085. */
  54086. get: function () {
  54087. if (this.particleEmitterType.maxEmitBox) {
  54088. return this.particleEmitterType.maxEmitBox;
  54089. }
  54090. return BABYLON.Vector3.Zero();
  54091. },
  54092. set: function (value) {
  54093. if (this.particleEmitterType.maxEmitBox) {
  54094. this.particleEmitterType.maxEmitBox = value;
  54095. }
  54096. },
  54097. enumerable: true,
  54098. configurable: true
  54099. });
  54100. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54101. /**
  54102. * Sets a callback that will be triggered when the system is disposed.
  54103. */
  54104. set: function (callback) {
  54105. if (this._onDisposeObserver) {
  54106. this.onDisposeObservable.remove(this._onDisposeObserver);
  54107. }
  54108. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54109. },
  54110. enumerable: true,
  54111. configurable: true
  54112. });
  54113. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54114. /**
  54115. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  54116. */
  54117. get: function () {
  54118. return this._isAnimationSheetEnabled;
  54119. },
  54120. enumerable: true,
  54121. configurable: true
  54122. });
  54123. Object.defineProperty(ParticleSystem.prototype, "particles", {
  54124. //end of Sub-emitter
  54125. /**
  54126. * Gets the current list of active particles
  54127. */
  54128. get: function () {
  54129. return this._particles;
  54130. },
  54131. enumerable: true,
  54132. configurable: true
  54133. });
  54134. /**
  54135. * Returns the string "ParticleSystem"
  54136. * @returns a string containing the class name
  54137. */
  54138. ParticleSystem.prototype.getClassName = function () {
  54139. return "ParticleSystem";
  54140. };
  54141. ParticleSystem.prototype._createIndexBuffer = function () {
  54142. var indices = [];
  54143. var index = 0;
  54144. for (var count = 0; count < this._capacity; count++) {
  54145. indices.push(index);
  54146. indices.push(index + 1);
  54147. indices.push(index + 2);
  54148. indices.push(index);
  54149. indices.push(index + 2);
  54150. indices.push(index + 3);
  54151. index += 4;
  54152. }
  54153. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  54154. };
  54155. /**
  54156. * Gets the maximum number of particles active at the same time.
  54157. * @returns The max number of active particles.
  54158. */
  54159. ParticleSystem.prototype.getCapacity = function () {
  54160. return this._capacity;
  54161. };
  54162. /**
  54163. * Gets Wether there are still active particles in the system.
  54164. * @returns True if it is alive, otherwise false.
  54165. */
  54166. ParticleSystem.prototype.isAlive = function () {
  54167. return this._alive;
  54168. };
  54169. /**
  54170. * Gets Wether the system has been started.
  54171. * @returns True if it has been started, otherwise false.
  54172. */
  54173. ParticleSystem.prototype.isStarted = function () {
  54174. return this._started;
  54175. };
  54176. /**
  54177. * Starts the particle system and begins to emit.
  54178. */
  54179. ParticleSystem.prototype.start = function () {
  54180. this._started = true;
  54181. this._stopped = false;
  54182. this._actualFrame = 0;
  54183. if (this.subEmitters && this.subEmitters.length != 0) {
  54184. this.activeSubSystems = new Array();
  54185. }
  54186. };
  54187. /**
  54188. * Stops the particle system.
  54189. * @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.
  54190. */
  54191. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  54192. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  54193. this._stopped = true;
  54194. if (stopSubEmitters) {
  54195. this._stopSubEmitters();
  54196. }
  54197. };
  54198. // animation sheet
  54199. /**
  54200. * Remove all active particles
  54201. */
  54202. ParticleSystem.prototype.reset = function () {
  54203. this._stockParticles = [];
  54204. this._particles = [];
  54205. };
  54206. /**
  54207. * @ignore (for internal use only)
  54208. */
  54209. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  54210. var offset = index * this._vertexBufferSize;
  54211. this._vertexData[offset] = particle.position.x;
  54212. this._vertexData[offset + 1] = particle.position.y;
  54213. this._vertexData[offset + 2] = particle.position.z;
  54214. this._vertexData[offset + 3] = particle.color.r;
  54215. this._vertexData[offset + 4] = particle.color.g;
  54216. this._vertexData[offset + 5] = particle.color.b;
  54217. this._vertexData[offset + 6] = particle.color.a;
  54218. this._vertexData[offset + 7] = particle.angle;
  54219. this._vertexData[offset + 8] = particle.size;
  54220. this._vertexData[offset + 9] = offsetX;
  54221. this._vertexData[offset + 10] = offsetY;
  54222. };
  54223. /**
  54224. * @ignore (for internal use only)
  54225. */
  54226. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  54227. if (offsetX === 0)
  54228. offsetX = this._epsilon;
  54229. else if (offsetX === 1)
  54230. offsetX = 1 - this._epsilon;
  54231. if (offsetY === 0)
  54232. offsetY = this._epsilon;
  54233. else if (offsetY === 1)
  54234. offsetY = 1 - this._epsilon;
  54235. var offset = index * this._vertexBufferSize;
  54236. this._vertexData[offset] = particle.position.x;
  54237. this._vertexData[offset + 1] = particle.position.y;
  54238. this._vertexData[offset + 2] = particle.position.z;
  54239. this._vertexData[offset + 3] = particle.color.r;
  54240. this._vertexData[offset + 4] = particle.color.g;
  54241. this._vertexData[offset + 5] = particle.color.b;
  54242. this._vertexData[offset + 6] = particle.color.a;
  54243. this._vertexData[offset + 7] = particle.angle;
  54244. this._vertexData[offset + 8] = particle.size;
  54245. this._vertexData[offset + 9] = offsetX;
  54246. this._vertexData[offset + 10] = offsetY;
  54247. this._vertexData[offset + 11] = particle.cellIndex;
  54248. };
  54249. ParticleSystem.prototype._stopSubEmitters = function () {
  54250. if (!this.activeSubSystems) {
  54251. return;
  54252. }
  54253. this.activeSubSystems.forEach(function (subSystem) {
  54254. subSystem.stop(true);
  54255. });
  54256. this.activeSubSystems = new Array();
  54257. };
  54258. ParticleSystem.prototype._removeFromRoot = function () {
  54259. if (!this._rootParticleSystem) {
  54260. return;
  54261. }
  54262. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  54263. if (index !== -1) {
  54264. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  54265. }
  54266. };
  54267. // end of sub system methods
  54268. ParticleSystem.prototype._update = function (newParticles) {
  54269. // Update current
  54270. this._alive = this._particles.length > 0;
  54271. this.updateFunction(this._particles);
  54272. // Add new ones
  54273. var worldMatrix;
  54274. if (this.emitter.position) {
  54275. var emitterMesh = this.emitter;
  54276. worldMatrix = emitterMesh.getWorldMatrix();
  54277. }
  54278. else {
  54279. var emitterPosition = this.emitter;
  54280. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  54281. }
  54282. var particle;
  54283. for (var index = 0; index < newParticles; index++) {
  54284. if (this._particles.length === this._capacity) {
  54285. break;
  54286. }
  54287. particle = this._createParticle();
  54288. this._particles.push(particle);
  54289. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  54290. if (this.startPositionFunction) {
  54291. this.startPositionFunction(worldMatrix, particle.position, particle);
  54292. }
  54293. else {
  54294. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  54295. }
  54296. if (this.startDirectionFunction) {
  54297. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54298. }
  54299. else {
  54300. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54301. }
  54302. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  54303. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  54304. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  54305. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  54306. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  54307. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  54308. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  54309. }
  54310. };
  54311. ParticleSystem.prototype._getEffect = function () {
  54312. if (this._customEffect) {
  54313. return this._customEffect;
  54314. }
  54315. ;
  54316. var defines = [];
  54317. if (this._scene.clipPlane) {
  54318. defines.push("#define CLIPPLANE");
  54319. }
  54320. if (this._isAnimationSheetEnabled) {
  54321. defines.push("#define ANIMATESHEET");
  54322. }
  54323. // Effect
  54324. var join = defines.join("\n");
  54325. if (this._cachedDefines !== join) {
  54326. this._cachedDefines = join;
  54327. var attributesNamesOrOptions;
  54328. var effectCreationOption;
  54329. if (this._isAnimationSheetEnabled) {
  54330. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  54331. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  54332. }
  54333. else {
  54334. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  54335. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  54336. }
  54337. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  54338. }
  54339. return this._effect;
  54340. };
  54341. /**
  54342. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  54343. */
  54344. ParticleSystem.prototype.animate = function () {
  54345. if (!this._started)
  54346. return;
  54347. var effect = this._getEffect();
  54348. // Check
  54349. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  54350. return;
  54351. if (this._currentRenderId === this._scene.getRenderId()) {
  54352. return;
  54353. }
  54354. this._currentRenderId = this._scene.getRenderId();
  54355. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  54356. // determine the number of particles we need to create
  54357. var newParticles;
  54358. if (this.manualEmitCount > -1) {
  54359. newParticles = this.manualEmitCount;
  54360. this._newPartsExcess = 0;
  54361. this.manualEmitCount = 0;
  54362. }
  54363. else {
  54364. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  54365. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  54366. }
  54367. if (this._newPartsExcess > 1.0) {
  54368. newParticles += this._newPartsExcess >> 0;
  54369. this._newPartsExcess -= this._newPartsExcess >> 0;
  54370. }
  54371. this._alive = false;
  54372. if (!this._stopped) {
  54373. this._actualFrame += this._scaledUpdateSpeed;
  54374. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  54375. this.stop();
  54376. }
  54377. else {
  54378. newParticles = 0;
  54379. }
  54380. this._update(newParticles);
  54381. // Stopped?
  54382. if (this._stopped) {
  54383. if (!this._alive) {
  54384. this._started = false;
  54385. if (this.onAnimationEnd) {
  54386. this.onAnimationEnd();
  54387. }
  54388. if (this.disposeOnStop) {
  54389. this._scene._toBeDisposed.push(this);
  54390. }
  54391. }
  54392. }
  54393. // Animation sheet
  54394. if (this._isAnimationSheetEnabled) {
  54395. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  54396. }
  54397. else {
  54398. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  54399. }
  54400. // Update VBO
  54401. var offset = 0;
  54402. for (var index = 0; index < this._particles.length; index++) {
  54403. var particle = this._particles[index];
  54404. this._appendParticleVertexes(offset, particle);
  54405. offset += 4;
  54406. }
  54407. if (this._vertexBuffer) {
  54408. this._vertexBuffer.update(this._vertexData);
  54409. }
  54410. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  54411. this.stop();
  54412. }
  54413. };
  54414. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  54415. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  54416. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  54417. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  54418. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  54419. };
  54420. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  54421. this._appendParticleVertex(offset++, particle, 0, 0);
  54422. this._appendParticleVertex(offset++, particle, 1, 0);
  54423. this._appendParticleVertex(offset++, particle, 1, 1);
  54424. this._appendParticleVertex(offset++, particle, 0, 1);
  54425. };
  54426. /**
  54427. * Rebuilds the particle system.
  54428. */
  54429. ParticleSystem.prototype.rebuild = function () {
  54430. this._createIndexBuffer();
  54431. if (this._vertexBuffer) {
  54432. this._vertexBuffer._rebuild();
  54433. }
  54434. };
  54435. /**
  54436. * Is this system ready to be used/rendered
  54437. * @return true if the system is ready
  54438. */
  54439. ParticleSystem.prototype.isReady = function () {
  54440. var effect = this._getEffect();
  54441. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  54442. return false;
  54443. }
  54444. return true;
  54445. };
  54446. /**
  54447. * Renders the particle system in its current state.
  54448. * @returns the current number of particles
  54449. */
  54450. ParticleSystem.prototype.render = function () {
  54451. var effect = this._getEffect();
  54452. // Check
  54453. if (!this.isReady() || !this._particles.length) {
  54454. return 0;
  54455. }
  54456. var engine = this._scene.getEngine();
  54457. // Render
  54458. engine.enableEffect(effect);
  54459. engine.setState(false);
  54460. var viewMatrix = this._scene.getViewMatrix();
  54461. effect.setTexture("diffuseSampler", this.particleTexture);
  54462. effect.setMatrix("view", viewMatrix);
  54463. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54464. if (this._isAnimationSheetEnabled && this.particleTexture) {
  54465. var baseSize = this.particleTexture.getBaseSize();
  54466. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  54467. }
  54468. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  54469. if (this._scene.clipPlane) {
  54470. var clipPlane = this._scene.clipPlane;
  54471. var invView = viewMatrix.clone();
  54472. invView.invert();
  54473. effect.setMatrix("invView", invView);
  54474. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  54475. }
  54476. // VBOs
  54477. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54478. // Draw order
  54479. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  54480. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  54481. }
  54482. else {
  54483. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54484. }
  54485. if (this.forceDepthWrite) {
  54486. engine.setDepthWrite(true);
  54487. }
  54488. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  54489. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54490. return this._particles.length;
  54491. };
  54492. /**
  54493. * Disposes the particle system and free the associated resources
  54494. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  54495. */
  54496. ParticleSystem.prototype.dispose = function (disposeTexture) {
  54497. if (disposeTexture === void 0) { disposeTexture = true; }
  54498. if (this._vertexBuffer) {
  54499. this._vertexBuffer.dispose();
  54500. this._vertexBuffer = null;
  54501. }
  54502. if (this._indexBuffer) {
  54503. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54504. this._indexBuffer = null;
  54505. }
  54506. if (disposeTexture && this.particleTexture) {
  54507. this.particleTexture.dispose();
  54508. this.particleTexture = null;
  54509. }
  54510. this._removeFromRoot();
  54511. // Remove from scene
  54512. var index = this._scene.particleSystems.indexOf(this);
  54513. if (index > -1) {
  54514. this._scene.particleSystems.splice(index, 1);
  54515. }
  54516. // Callback
  54517. this.onDisposeObservable.notifyObservers(this);
  54518. this.onDisposeObservable.clear();
  54519. };
  54520. /**
  54521. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  54522. * @param radius The radius of the sphere to emit from
  54523. * @returns the emitter
  54524. */
  54525. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  54526. if (radius === void 0) { radius = 1; }
  54527. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  54528. this.particleEmitterType = particleEmitter;
  54529. return particleEmitter;
  54530. };
  54531. /**
  54532. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  54533. * @param radius The radius of the sphere to emit from
  54534. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  54535. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  54536. * @returns the emitter
  54537. */
  54538. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  54539. if (radius === void 0) { radius = 1; }
  54540. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  54541. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  54542. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  54543. this.particleEmitterType = particleEmitter;
  54544. return particleEmitter;
  54545. };
  54546. /**
  54547. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  54548. * @param radius The radius of the cone to emit from
  54549. * @param angle The base angle of the cone
  54550. * @returns the emitter
  54551. */
  54552. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  54553. if (radius === void 0) { radius = 1; }
  54554. if (angle === void 0) { angle = Math.PI / 4; }
  54555. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  54556. this.particleEmitterType = particleEmitter;
  54557. return particleEmitter;
  54558. };
  54559. // 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.
  54560. /**
  54561. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  54562. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  54563. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  54564. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54565. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54566. * @returns the emitter
  54567. */
  54568. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  54569. var particleEmitter = new BABYLON.BoxParticleEmitter();
  54570. this.particleEmitterType = particleEmitter;
  54571. this.direction1 = direction1;
  54572. this.direction2 = direction2;
  54573. this.minEmitBox = minEmitBox;
  54574. this.maxEmitBox = maxEmitBox;
  54575. return particleEmitter;
  54576. };
  54577. // Clone
  54578. /**
  54579. * Clones the particle system.
  54580. * @param name The name of the cloned object
  54581. * @param newEmitter The new emitter to use
  54582. * @returns the cloned particle system
  54583. */
  54584. ParticleSystem.prototype.clone = function (name, newEmitter) {
  54585. var custom = null;
  54586. var program = null;
  54587. if (this.customShader != null) {
  54588. program = this.customShader;
  54589. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  54590. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  54591. }
  54592. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  54593. result.customShader = program;
  54594. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  54595. if (newEmitter === undefined) {
  54596. newEmitter = this.emitter;
  54597. }
  54598. result.emitter = newEmitter;
  54599. if (this.particleTexture) {
  54600. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  54601. }
  54602. if (!this.preventAutoStart) {
  54603. result.start();
  54604. }
  54605. return result;
  54606. };
  54607. /**
  54608. * Serializes the particle system to a JSON object.
  54609. * @returns the JSON object
  54610. */
  54611. ParticleSystem.prototype.serialize = function () {
  54612. var serializationObject = {};
  54613. serializationObject.name = this.name;
  54614. serializationObject.id = this.id;
  54615. // Emitter
  54616. if (this.emitter.position) {
  54617. var emitterMesh = this.emitter;
  54618. serializationObject.emitterId = emitterMesh.id;
  54619. }
  54620. else {
  54621. var emitterPosition = this.emitter;
  54622. serializationObject.emitter = emitterPosition.asArray();
  54623. }
  54624. serializationObject.capacity = this.getCapacity();
  54625. if (this.particleTexture) {
  54626. serializationObject.textureName = this.particleTexture.name;
  54627. }
  54628. // Animations
  54629. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  54630. // Particle system
  54631. serializationObject.minAngularSpeed = this.minAngularSpeed;
  54632. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  54633. serializationObject.minSize = this.minSize;
  54634. serializationObject.maxSize = this.maxSize;
  54635. serializationObject.minEmitPower = this.minEmitPower;
  54636. serializationObject.maxEmitPower = this.maxEmitPower;
  54637. serializationObject.minLifeTime = this.minLifeTime;
  54638. serializationObject.maxLifeTime = this.maxLifeTime;
  54639. serializationObject.emitRate = this.emitRate;
  54640. serializationObject.minEmitBox = this.minEmitBox.asArray();
  54641. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  54642. serializationObject.gravity = this.gravity.asArray();
  54643. serializationObject.direction1 = this.direction1.asArray();
  54644. serializationObject.direction2 = this.direction2.asArray();
  54645. serializationObject.color1 = this.color1.asArray();
  54646. serializationObject.color2 = this.color2.asArray();
  54647. serializationObject.colorDead = this.colorDead.asArray();
  54648. serializationObject.updateSpeed = this.updateSpeed;
  54649. serializationObject.targetStopDuration = this.targetStopDuration;
  54650. serializationObject.textureMask = this.textureMask.asArray();
  54651. serializationObject.blendMode = this.blendMode;
  54652. serializationObject.customShader = this.customShader;
  54653. serializationObject.preventAutoStart = this.preventAutoStart;
  54654. serializationObject.startSpriteCellID = this.startSpriteCellID;
  54655. serializationObject.endSpriteCellID = this.endSpriteCellID;
  54656. serializationObject.spriteCellLoop = this.spriteCellLoop;
  54657. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  54658. serializationObject.spriteCellWidth = this.spriteCellWidth;
  54659. serializationObject.spriteCellHeight = this.spriteCellHeight;
  54660. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  54661. // Emitter
  54662. if (this.particleEmitterType) {
  54663. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  54664. }
  54665. return serializationObject;
  54666. };
  54667. /**
  54668. * Parses a JSON object to create a particle system.
  54669. * @param parsedParticleSystem The JSON object to parse
  54670. * @param scene The scene to create the particle system in
  54671. * @param rootUrl The root url to use to load external dependencies like texture
  54672. * @returns the Parsed particle system
  54673. */
  54674. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  54675. var name = parsedParticleSystem.name;
  54676. var custom = null;
  54677. var program = null;
  54678. if (parsedParticleSystem.customShader) {
  54679. program = parsedParticleSystem.customShader;
  54680. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  54681. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  54682. }
  54683. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  54684. particleSystem.customShader = program;
  54685. if (parsedParticleSystem.id) {
  54686. particleSystem.id = parsedParticleSystem.id;
  54687. }
  54688. // Auto start
  54689. if (parsedParticleSystem.preventAutoStart) {
  54690. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  54691. }
  54692. // Texture
  54693. if (parsedParticleSystem.textureName) {
  54694. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  54695. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  54696. }
  54697. // Emitter
  54698. if (parsedParticleSystem.emitterId) {
  54699. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  54700. }
  54701. else {
  54702. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  54703. }
  54704. // Animations
  54705. if (parsedParticleSystem.animations) {
  54706. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  54707. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  54708. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54709. }
  54710. }
  54711. if (parsedParticleSystem.autoAnimate) {
  54712. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  54713. }
  54714. // Particle system
  54715. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  54716. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  54717. particleSystem.minSize = parsedParticleSystem.minSize;
  54718. particleSystem.maxSize = parsedParticleSystem.maxSize;
  54719. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  54720. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  54721. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  54722. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  54723. particleSystem.emitRate = parsedParticleSystem.emitRate;
  54724. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  54725. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  54726. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  54727. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  54728. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  54729. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  54730. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  54731. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  54732. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  54733. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  54734. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  54735. particleSystem.blendMode = parsedParticleSystem.blendMode;
  54736. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  54737. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  54738. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  54739. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  54740. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  54741. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  54742. if (!particleSystem.preventAutoStart) {
  54743. particleSystem.start();
  54744. }
  54745. return particleSystem;
  54746. };
  54747. /**
  54748. * Source color is added to the destination color without alpha affecting the result.
  54749. */
  54750. ParticleSystem.BLENDMODE_ONEONE = 0;
  54751. /**
  54752. * Blend current color and particle color using particle’s alpha.
  54753. */
  54754. ParticleSystem.BLENDMODE_STANDARD = 1;
  54755. return ParticleSystem;
  54756. }());
  54757. BABYLON.ParticleSystem = ParticleSystem;
  54758. })(BABYLON || (BABYLON = {}));
  54759. //# sourceMappingURL=babylon.particleSystem.js.map
  54760. "use strict";
  54761. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  54762. "use strict";
  54763. var BABYLON;
  54764. (function (BABYLON) {
  54765. /**
  54766. * Particle emitter emitting particles from the inside of a box.
  54767. * It emits the particles randomly between 2 given directions.
  54768. */
  54769. var BoxParticleEmitter = /** @class */ (function () {
  54770. /**
  54771. * Creates a new instance BoxParticleEmitter
  54772. */
  54773. function BoxParticleEmitter() {
  54774. /**
  54775. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54776. */
  54777. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  54778. /**
  54779. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54780. */
  54781. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  54782. /**
  54783. * 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.
  54784. */
  54785. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  54786. /**
  54787. * 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.
  54788. */
  54789. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  54790. }
  54791. /**
  54792. * Called by the particle System when the direction is computed for the created particle.
  54793. * @param emitPower is the power of the particle (speed)
  54794. * @param worldMatrix is the world matrix of the particle system
  54795. * @param directionToUpdate is the direction vector to update with the result
  54796. * @param particle is the particle we are computed the direction for
  54797. */
  54798. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  54799. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  54800. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  54801. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  54802. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  54803. };
  54804. /**
  54805. * Called by the particle System when the position is computed for the created particle.
  54806. * @param worldMatrix is the world matrix of the particle system
  54807. * @param positionToUpdate is the position vector to update with the result
  54808. * @param particle is the particle we are computed the position for
  54809. */
  54810. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  54811. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  54812. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  54813. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  54814. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  54815. };
  54816. /**
  54817. * Clones the current emitter and returns a copy of it
  54818. * @returns the new emitter
  54819. */
  54820. BoxParticleEmitter.prototype.clone = function () {
  54821. var newOne = new BoxParticleEmitter();
  54822. BABYLON.Tools.DeepCopy(this, newOne);
  54823. return newOne;
  54824. };
  54825. /**
  54826. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  54827. * @param effect defines the update shader
  54828. */
  54829. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  54830. effect.setVector3("direction1", this.direction1);
  54831. effect.setVector3("direction2", this.direction2);
  54832. effect.setVector3("minEmitBox", this.minEmitBox);
  54833. effect.setVector3("maxEmitBox", this.maxEmitBox);
  54834. };
  54835. /**
  54836. * Returns a string to use to update the GPU particles update shader
  54837. * @returns a string containng the defines string
  54838. */
  54839. BoxParticleEmitter.prototype.getEffectDefines = function () {
  54840. return "#define BOXEMITTER";
  54841. };
  54842. /**
  54843. * Returns the string "BoxEmitter"
  54844. * @returns a string containing the class name
  54845. */
  54846. BoxParticleEmitter.prototype.getClassName = function () {
  54847. return "BoxEmitter";
  54848. };
  54849. /**
  54850. * Serializes the particle system to a JSON object.
  54851. * @returns the JSON object
  54852. */
  54853. BoxParticleEmitter.prototype.serialize = function () {
  54854. var serializationObject = {};
  54855. serializationObject.type = this.getClassName();
  54856. serializationObject.direction1 = this.direction1.asArray();
  54857. ;
  54858. serializationObject.direction2 = this.direction2.asArray();
  54859. ;
  54860. serializationObject.minEmitBox = this.minEmitBox.asArray();
  54861. ;
  54862. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  54863. ;
  54864. return serializationObject;
  54865. };
  54866. /**
  54867. * Parse properties from a JSON object
  54868. * @param serializationObject defines the JSON object
  54869. */
  54870. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  54871. this.direction1.copyFrom(serializationObject.direction1);
  54872. this.direction2.copyFrom(serializationObject.direction2);
  54873. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  54874. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  54875. };
  54876. return BoxParticleEmitter;
  54877. }());
  54878. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  54879. })(BABYLON || (BABYLON = {}));
  54880. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  54881. "use strict";
  54882. var BABYLON;
  54883. (function (BABYLON) {
  54884. /**
  54885. * Particle emitter emitting particles from the inside of a cone.
  54886. * It emits the particles alongside the cone volume from the base to the particle.
  54887. * The emission direction might be randomized.
  54888. */
  54889. var ConeParticleEmitter = /** @class */ (function () {
  54890. /**
  54891. * Creates a new instance ConeParticleEmitter
  54892. * @param radius the radius of the emission cone (1 by default)
  54893. * @param angles the cone base angle (PI by default)
  54894. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  54895. */
  54896. function ConeParticleEmitter(radius,
  54897. /**
  54898. * The radius of the emission cone.
  54899. */
  54900. angle,
  54901. /**
  54902. * The cone base angle.
  54903. */
  54904. directionRandomizer) {
  54905. if (radius === void 0) { radius = 1; }
  54906. if (angle === void 0) { angle = Math.PI; }
  54907. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  54908. this.angle = angle;
  54909. this.directionRandomizer = directionRandomizer;
  54910. this.radius = radius;
  54911. }
  54912. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  54913. /**
  54914. * Gets the radius of the emission cone.
  54915. */
  54916. get: function () {
  54917. return this._radius;
  54918. },
  54919. /**
  54920. * Sets the radius of the emission cone.
  54921. */
  54922. set: function (value) {
  54923. this._radius = value;
  54924. if (this.angle !== 0) {
  54925. this._height = value / Math.tan(this.angle / 2);
  54926. }
  54927. else {
  54928. this._height = 1;
  54929. }
  54930. },
  54931. enumerable: true,
  54932. configurable: true
  54933. });
  54934. /**
  54935. * Called by the particle System when the direction is computed for the created particle.
  54936. * @param emitPower is the power of the particle (speed)
  54937. * @param worldMatrix is the world matrix of the particle system
  54938. * @param directionToUpdate is the direction vector to update with the result
  54939. * @param particle is the particle we are computed the direction for
  54940. */
  54941. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  54942. if (this.angle === 0) {
  54943. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  54944. }
  54945. else {
  54946. // measure the direction Vector from the emitter to the particle.
  54947. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  54948. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  54949. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  54950. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  54951. direction.x += randX;
  54952. direction.y += randY;
  54953. direction.z += randZ;
  54954. direction.normalize();
  54955. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  54956. }
  54957. };
  54958. /**
  54959. * Called by the particle System when the position is computed for the created particle.
  54960. * @param worldMatrix is the world matrix of the particle system
  54961. * @param positionToUpdate is the position vector to update with the result
  54962. * @param particle is the particle we are computed the position for
  54963. */
  54964. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  54965. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  54966. var h = BABYLON.Scalar.RandomRange(0, 1);
  54967. // Better distribution in a cone at normal angles.
  54968. h = 1 - h * h;
  54969. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  54970. radius = radius * h;
  54971. var randX = radius * Math.sin(s);
  54972. var randZ = radius * Math.cos(s);
  54973. var randY = h * this._height;
  54974. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  54975. };
  54976. /**
  54977. * Clones the current emitter and returns a copy of it
  54978. * @returns the new emitter
  54979. */
  54980. ConeParticleEmitter.prototype.clone = function () {
  54981. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  54982. BABYLON.Tools.DeepCopy(this, newOne);
  54983. return newOne;
  54984. };
  54985. /**
  54986. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  54987. * @param effect defines the update shader
  54988. */
  54989. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  54990. effect.setFloat("radius", this.radius);
  54991. effect.setFloat("angle", this.angle);
  54992. effect.setFloat("height", this._height);
  54993. effect.setFloat("directionRandomizer", this.directionRandomizer);
  54994. };
  54995. /**
  54996. * Returns a string to use to update the GPU particles update shader
  54997. * @returns a string containng the defines string
  54998. */
  54999. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55000. return "#define CONEEMITTER";
  55001. };
  55002. /**
  55003. * Returns the string "BoxEmitter"
  55004. * @returns a string containing the class name
  55005. */
  55006. ConeParticleEmitter.prototype.getClassName = function () {
  55007. return "ConeEmitter";
  55008. };
  55009. /**
  55010. * Serializes the particle system to a JSON object.
  55011. * @returns the JSON object
  55012. */
  55013. ConeParticleEmitter.prototype.serialize = function () {
  55014. var serializationObject = {};
  55015. serializationObject.type = this.getClassName();
  55016. serializationObject.radius = this.radius;
  55017. serializationObject.angle = this.angle;
  55018. serializationObject.directionRandomizer = this.directionRandomizer;
  55019. return serializationObject;
  55020. };
  55021. /**
  55022. * Parse properties from a JSON object
  55023. * @param serializationObject defines the JSON object
  55024. */
  55025. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55026. this.radius = serializationObject.radius;
  55027. this.angle = serializationObject.angle;
  55028. this.directionRandomizer = serializationObject.directionRandomizer;
  55029. };
  55030. return ConeParticleEmitter;
  55031. }());
  55032. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55033. })(BABYLON || (BABYLON = {}));
  55034. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55035. "use strict";
  55036. var BABYLON;
  55037. (function (BABYLON) {
  55038. /**
  55039. * Particle emitter emitting particles from the inside of a sphere.
  55040. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55041. */
  55042. var SphereParticleEmitter = /** @class */ (function () {
  55043. /**
  55044. * Creates a new instance SphereParticleEmitter
  55045. * @param radius the radius of the emission sphere (1 by default)
  55046. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55047. */
  55048. function SphereParticleEmitter(
  55049. /**
  55050. * The radius of the emission sphere.
  55051. */
  55052. radius,
  55053. /**
  55054. * How much to randomize the particle direction [0-1].
  55055. */
  55056. directionRandomizer) {
  55057. if (radius === void 0) { radius = 1; }
  55058. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55059. this.radius = radius;
  55060. this.directionRandomizer = directionRandomizer;
  55061. }
  55062. /**
  55063. * Called by the particle System when the direction is computed for the created particle.
  55064. * @param emitPower is the power of the particle (speed)
  55065. * @param worldMatrix is the world matrix of the particle system
  55066. * @param directionToUpdate is the direction vector to update with the result
  55067. * @param particle is the particle we are computed the direction for
  55068. */
  55069. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55070. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55071. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55072. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55073. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55074. direction.x += randX;
  55075. direction.y += randY;
  55076. direction.z += randZ;
  55077. direction.normalize();
  55078. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55079. };
  55080. /**
  55081. * Called by the particle System when the position is computed for the created particle.
  55082. * @param worldMatrix is the world matrix of the particle system
  55083. * @param positionToUpdate is the position vector to update with the result
  55084. * @param particle is the particle we are computed the position for
  55085. */
  55086. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55087. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55088. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55089. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55090. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55091. var randY = randRadius * Math.cos(theta);
  55092. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55093. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55094. };
  55095. /**
  55096. * Clones the current emitter and returns a copy of it
  55097. * @returns the new emitter
  55098. */
  55099. SphereParticleEmitter.prototype.clone = function () {
  55100. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  55101. BABYLON.Tools.DeepCopy(this, newOne);
  55102. return newOne;
  55103. };
  55104. /**
  55105. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55106. * @param effect defines the update shader
  55107. */
  55108. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  55109. effect.setFloat("radius", this.radius);
  55110. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55111. };
  55112. /**
  55113. * Returns a string to use to update the GPU particles update shader
  55114. * @returns a string containng the defines string
  55115. */
  55116. SphereParticleEmitter.prototype.getEffectDefines = function () {
  55117. return "#define SPHEREEMITTER";
  55118. };
  55119. /**
  55120. * Returns the string "SphereParticleEmitter"
  55121. * @returns a string containing the class name
  55122. */
  55123. SphereParticleEmitter.prototype.getClassName = function () {
  55124. return "SphereParticleEmitter";
  55125. };
  55126. /**
  55127. * Serializes the particle system to a JSON object.
  55128. * @returns the JSON object
  55129. */
  55130. SphereParticleEmitter.prototype.serialize = function () {
  55131. var serializationObject = {};
  55132. serializationObject.type = this.getClassName();
  55133. serializationObject.radius = this.radius;
  55134. serializationObject.directionRandomizer = this.directionRandomizer;
  55135. return serializationObject;
  55136. };
  55137. /**
  55138. * Parse properties from a JSON object
  55139. * @param serializationObject defines the JSON object
  55140. */
  55141. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  55142. this.radius = serializationObject.radius;
  55143. this.directionRandomizer = serializationObject.directionRandomizer;
  55144. };
  55145. return SphereParticleEmitter;
  55146. }());
  55147. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  55148. /**
  55149. * Particle emitter emitting particles from the inside of a sphere.
  55150. * It emits the particles randomly between two vectors.
  55151. */
  55152. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  55153. __extends(SphereDirectedParticleEmitter, _super);
  55154. /**
  55155. * Creates a new instance SphereDirectedParticleEmitter
  55156. * @param radius the radius of the emission sphere (1 by default)
  55157. * @param direction1 the min limit of the emission direction (up vector by default)
  55158. * @param direction2 the max limit of the emission direction (up vector by default)
  55159. */
  55160. function SphereDirectedParticleEmitter(radius,
  55161. /**
  55162. * The min limit of the emission direction.
  55163. */
  55164. direction1,
  55165. /**
  55166. * The max limit of the emission direction.
  55167. */
  55168. direction2) {
  55169. if (radius === void 0) { radius = 1; }
  55170. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  55171. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  55172. var _this = _super.call(this, radius) || this;
  55173. _this.direction1 = direction1;
  55174. _this.direction2 = direction2;
  55175. return _this;
  55176. }
  55177. /**
  55178. * Called by the particle System when the direction is computed for the created particle.
  55179. * @param emitPower is the power of the particle (speed)
  55180. * @param worldMatrix is the world matrix of the particle system
  55181. * @param directionToUpdate is the direction vector to update with the result
  55182. * @param particle is the particle we are computed the direction for
  55183. */
  55184. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55185. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55186. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55187. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55188. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55189. };
  55190. /**
  55191. * Clones the current emitter and returns a copy of it
  55192. * @returns the new emitter
  55193. */
  55194. SphereDirectedParticleEmitter.prototype.clone = function () {
  55195. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  55196. BABYLON.Tools.DeepCopy(this, newOne);
  55197. return newOne;
  55198. };
  55199. /**
  55200. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55201. * @param effect defines the update shader
  55202. */
  55203. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  55204. effect.setFloat("radius", this.radius);
  55205. effect.setVector3("direction1", this.direction1);
  55206. effect.setVector3("direction2", this.direction2);
  55207. };
  55208. /**
  55209. * Returns a string to use to update the GPU particles update shader
  55210. * @returns a string containng the defines string
  55211. */
  55212. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  55213. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  55214. };
  55215. /**
  55216. * Returns the string "SphereDirectedParticleEmitter"
  55217. * @returns a string containing the class name
  55218. */
  55219. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  55220. return "SphereDirectedParticleEmitter";
  55221. };
  55222. /**
  55223. * Serializes the particle system to a JSON object.
  55224. * @returns the JSON object
  55225. */
  55226. SphereDirectedParticleEmitter.prototype.serialize = function () {
  55227. var serializationObject = _super.prototype.serialize.call(this);
  55228. ;
  55229. serializationObject.direction1 = this.direction1.asArray();
  55230. ;
  55231. serializationObject.direction2 = this.direction2.asArray();
  55232. ;
  55233. return serializationObject;
  55234. };
  55235. /**
  55236. * Parse properties from a JSON object
  55237. * @param serializationObject defines the JSON object
  55238. */
  55239. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  55240. _super.prototype.parse.call(this, serializationObject);
  55241. this.direction1.copyFrom(serializationObject.direction1);
  55242. this.direction2.copyFrom(serializationObject.direction2);
  55243. };
  55244. return SphereDirectedParticleEmitter;
  55245. }(SphereParticleEmitter));
  55246. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  55247. })(BABYLON || (BABYLON = {}));
  55248. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  55249. "use strict";
  55250. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55251. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55252. s = arguments[i];
  55253. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55254. t[p] = s[p];
  55255. }
  55256. return t;
  55257. };
  55258. var BABYLON;
  55259. (function (BABYLON) {
  55260. /**
  55261. * This represents a GPU particle system in Babylon
  55262. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  55263. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  55264. */
  55265. var GPUParticleSystem = /** @class */ (function () {
  55266. /**
  55267. * Instantiates a GPU particle system.
  55268. * 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.
  55269. * @param name The name of the particle system
  55270. * @param capacity The max number of particles alive at the same time
  55271. * @param scene The scene the particle system belongs to
  55272. */
  55273. function GPUParticleSystem(name, options, scene) {
  55274. /**
  55275. * The emitter represents the Mesh or position we are attaching the particle system to.
  55276. */
  55277. this.emitter = null;
  55278. /**
  55279. * The rendering group used by the Particle system to chose when to render.
  55280. */
  55281. this.renderingGroupId = 0;
  55282. /**
  55283. * The layer mask we are rendering the particles through.
  55284. */
  55285. this.layerMask = 0x0FFFFFFF;
  55286. this._targetIndex = 0;
  55287. this._currentRenderId = -1;
  55288. this._started = false;
  55289. this._stopped = false;
  55290. this._timeDelta = 0;
  55291. this._attributesStrideSize = 14;
  55292. this._actualFrame = 0;
  55293. /**
  55294. * List of animations used by the particle system.
  55295. */
  55296. this.animations = [];
  55297. /**
  55298. * An event triggered when the system is disposed.
  55299. */
  55300. this.onDisposeObservable = new BABYLON.Observable();
  55301. /**
  55302. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55303. */
  55304. this.updateSpeed = 0.01;
  55305. /**
  55306. * The amount of time the particle system is running (depends of the overall update speed).
  55307. */
  55308. this.targetStopDuration = 0;
  55309. /**
  55310. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55311. */
  55312. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55313. /**
  55314. * Minimum life time of emitting particles.
  55315. */
  55316. this.minLifeTime = 1;
  55317. /**
  55318. * Maximum life time of emitting particles.
  55319. */
  55320. this.maxLifeTime = 1;
  55321. /**
  55322. * Minimum Size of emitting particles.
  55323. */
  55324. this.minSize = 1;
  55325. /**
  55326. * Maximum Size of emitting particles.
  55327. */
  55328. this.maxSize = 1;
  55329. /**
  55330. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55331. */
  55332. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55333. /**
  55334. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55335. */
  55336. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55337. /**
  55338. * Color the particle will have at the end of its lifetime.
  55339. */
  55340. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  55341. /**
  55342. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  55343. */
  55344. this.emitRate = 100;
  55345. /**
  55346. * You can use gravity if you want to give an orientation to your particles.
  55347. */
  55348. this.gravity = BABYLON.Vector3.Zero();
  55349. /**
  55350. * Minimum power of emitting particles.
  55351. */
  55352. this.minEmitPower = 1;
  55353. /**
  55354. * Maximum power of emitting particles.
  55355. */
  55356. this.maxEmitPower = 1;
  55357. /**
  55358. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55359. * to override the particles.
  55360. */
  55361. this.forceDepthWrite = false;
  55362. this.id = name;
  55363. this.name = name;
  55364. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55365. this._engine = this._scene.getEngine();
  55366. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  55367. this._capacity = fullOptions.capacity;
  55368. this._activeCount = fullOptions.capacity;
  55369. this._currentActiveCount = 0;
  55370. this._scene.particleSystems.push(this);
  55371. this._updateEffectOptions = {
  55372. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  55373. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  55374. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  55375. uniformBuffersNames: [],
  55376. samplers: ["randomSampler"],
  55377. defines: "",
  55378. fallbacks: null,
  55379. onCompiled: null,
  55380. onError: null,
  55381. indexParameters: null,
  55382. maxSimultaneousLights: 0,
  55383. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  55384. };
  55385. // Random data
  55386. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  55387. var d = [];
  55388. for (var i = 0; i < maxTextureSize; ++i) {
  55389. d.push(Math.random());
  55390. d.push(Math.random());
  55391. d.push(Math.random());
  55392. d.push(Math.random());
  55393. }
  55394. 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);
  55395. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55396. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55397. this._randomTextureSize = maxTextureSize;
  55398. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55399. }
  55400. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  55401. /**
  55402. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  55403. */
  55404. get: function () {
  55405. if (!BABYLON.Engine.LastCreatedEngine) {
  55406. return false;
  55407. }
  55408. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  55409. },
  55410. enumerable: true,
  55411. configurable: true
  55412. });
  55413. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  55414. /**
  55415. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55416. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55417. */
  55418. get: function () {
  55419. if (this.particleEmitterType.direction1) {
  55420. return this.particleEmitterType.direction1;
  55421. }
  55422. return BABYLON.Vector3.Zero();
  55423. },
  55424. set: function (value) {
  55425. if (this.particleEmitterType.direction1) {
  55426. this.particleEmitterType.direction1 = value;
  55427. }
  55428. },
  55429. enumerable: true,
  55430. configurable: true
  55431. });
  55432. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  55433. /**
  55434. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55435. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55436. */
  55437. get: function () {
  55438. if (this.particleEmitterType.direction2) {
  55439. return this.particleEmitterType.direction2;
  55440. }
  55441. return BABYLON.Vector3.Zero();
  55442. },
  55443. set: function (value) {
  55444. if (this.particleEmitterType.direction2) {
  55445. this.particleEmitterType.direction2 = value;
  55446. }
  55447. },
  55448. enumerable: true,
  55449. configurable: true
  55450. });
  55451. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  55452. /**
  55453. * 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.
  55454. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55455. */
  55456. get: function () {
  55457. if (this.particleEmitterType.minEmitBox) {
  55458. return this.particleEmitterType.minEmitBox;
  55459. }
  55460. return BABYLON.Vector3.Zero();
  55461. },
  55462. set: function (value) {
  55463. if (this.particleEmitterType.minEmitBox) {
  55464. this.particleEmitterType.minEmitBox = value;
  55465. }
  55466. },
  55467. enumerable: true,
  55468. configurable: true
  55469. });
  55470. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  55471. /**
  55472. * 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.
  55473. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55474. */
  55475. get: function () {
  55476. if (this.particleEmitterType.maxEmitBox) {
  55477. return this.particleEmitterType.maxEmitBox;
  55478. }
  55479. return BABYLON.Vector3.Zero();
  55480. },
  55481. set: function (value) {
  55482. if (this.particleEmitterType.maxEmitBox) {
  55483. this.particleEmitterType.maxEmitBox = value;
  55484. }
  55485. },
  55486. enumerable: true,
  55487. configurable: true
  55488. });
  55489. /**
  55490. * Gets the maximum number of particles active at the same time.
  55491. * @returns The max number of active particles.
  55492. */
  55493. GPUParticleSystem.prototype.getCapacity = function () {
  55494. return this._capacity;
  55495. };
  55496. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  55497. /**
  55498. * Gets or set the number of active particles
  55499. */
  55500. get: function () {
  55501. return this._activeCount;
  55502. },
  55503. set: function (value) {
  55504. this._activeCount = Math.min(value, this._capacity);
  55505. },
  55506. enumerable: true,
  55507. configurable: true
  55508. });
  55509. /**
  55510. * Is this system ready to be used/rendered
  55511. * @return true if the system is ready
  55512. */
  55513. GPUParticleSystem.prototype.isReady = function () {
  55514. if (!this._updateEffect) {
  55515. this._recreateUpdateEffect();
  55516. this._recreateRenderEffect();
  55517. return false;
  55518. }
  55519. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55520. return false;
  55521. }
  55522. return true;
  55523. };
  55524. /**
  55525. * Gets Wether the system has been started.
  55526. * @returns True if it has been started, otherwise false.
  55527. */
  55528. GPUParticleSystem.prototype.isStarted = function () {
  55529. return this._started;
  55530. };
  55531. /**
  55532. * Starts the particle system and begins to emit.
  55533. */
  55534. GPUParticleSystem.prototype.start = function () {
  55535. this._started = true;
  55536. this._stopped = false;
  55537. };
  55538. /**
  55539. * Stops the particle system.
  55540. */
  55541. GPUParticleSystem.prototype.stop = function () {
  55542. this._stopped = true;
  55543. };
  55544. /**
  55545. * Remove all active particles
  55546. */
  55547. GPUParticleSystem.prototype.reset = function () {
  55548. this._releaseBuffers();
  55549. this._releaseVAOs();
  55550. this._currentActiveCount = 0;
  55551. this._targetIndex = 0;
  55552. };
  55553. /**
  55554. * Returns the string "GPUParticleSystem"
  55555. * @returns a string containing the class name
  55556. */
  55557. GPUParticleSystem.prototype.getClassName = function () {
  55558. return "GPUParticleSystem";
  55559. };
  55560. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  55561. var updateVertexBuffers = {};
  55562. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  55563. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  55564. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  55565. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  55566. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  55567. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  55568. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  55569. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  55570. this._engine.bindArrayBuffer(null);
  55571. return vao;
  55572. };
  55573. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  55574. var renderVertexBuffers = {};
  55575. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  55576. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  55577. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  55578. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  55579. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  55580. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  55581. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  55582. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  55583. this._engine.bindArrayBuffer(null);
  55584. return vao;
  55585. };
  55586. GPUParticleSystem.prototype._initialize = function (force) {
  55587. if (force === void 0) { force = false; }
  55588. if (this._buffer0 && !force) {
  55589. return;
  55590. }
  55591. var engine = this._scene.getEngine();
  55592. var data = new Array();
  55593. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  55594. // position
  55595. data.push(0.0);
  55596. data.push(0.0);
  55597. data.push(0.0);
  55598. // Age and life
  55599. data.push(0.0); // create the particle as a dead one to create a new one at start
  55600. data.push(0.0);
  55601. // Seed
  55602. data.push(Math.random());
  55603. // Size
  55604. data.push(0.0);
  55605. // color
  55606. data.push(0.0);
  55607. data.push(0.0);
  55608. data.push(0.0);
  55609. data.push(0.0);
  55610. // direction
  55611. data.push(0.0);
  55612. data.push(0.0);
  55613. data.push(0.0);
  55614. }
  55615. // Sprite data
  55616. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  55617. -0.5, 0.5, 0, 1,
  55618. -0.5, -0.5, 0, 0,
  55619. 0.5, -0.5, 1, 0]);
  55620. // Buffers
  55621. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  55622. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  55623. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  55624. // Update VAO
  55625. this._updateVAO = [];
  55626. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  55627. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  55628. // Render VAO
  55629. this._renderVAO = [];
  55630. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  55631. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  55632. // Links
  55633. this._sourceBuffer = this._buffer0;
  55634. this._targetBuffer = this._buffer1;
  55635. };
  55636. /** @ignore */
  55637. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  55638. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  55639. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  55640. return;
  55641. }
  55642. this._updateEffectOptions.defines = defines;
  55643. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  55644. };
  55645. /** @ignore */
  55646. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  55647. var defines = "";
  55648. if (this._scene.clipPlane) {
  55649. defines = "\n#define CLIPPLANE";
  55650. }
  55651. if (this._renderEffect && this._renderEffect.defines === defines) {
  55652. return;
  55653. }
  55654. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  55655. };
  55656. /**
  55657. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55658. */
  55659. GPUParticleSystem.prototype.animate = function () {
  55660. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  55661. this._actualFrame += this._timeDelta;
  55662. if (!this._stopped) {
  55663. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  55664. this.stop();
  55665. }
  55666. }
  55667. };
  55668. /**
  55669. * Renders the particle system in its current state.
  55670. * @returns the current number of particles
  55671. */
  55672. GPUParticleSystem.prototype.render = function () {
  55673. if (!this._started) {
  55674. return 0;
  55675. }
  55676. this._recreateUpdateEffect();
  55677. this._recreateRenderEffect();
  55678. if (!this.isReady()) {
  55679. return 0;
  55680. }
  55681. if (this._currentRenderId === this._scene.getRenderId()) {
  55682. return 0;
  55683. }
  55684. this._currentRenderId = this._scene.getRenderId();
  55685. // Get everything ready to render
  55686. this._initialize();
  55687. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  55688. // Enable update effect
  55689. this._engine.enableEffect(this._updateEffect);
  55690. this._engine.setState(false);
  55691. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  55692. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  55693. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  55694. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  55695. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  55696. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  55697. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  55698. this._updateEffect.setDirectColor4("color1", this.color1);
  55699. this._updateEffect.setDirectColor4("color2", this.color2);
  55700. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  55701. this._updateEffect.setVector3("gravity", this.gravity);
  55702. if (this.particleEmitterType) {
  55703. this.particleEmitterType.applyToShader(this._updateEffect);
  55704. }
  55705. var emitterWM;
  55706. if (this.emitter.position) {
  55707. var emitterMesh = this.emitter;
  55708. emitterWM = emitterMesh.getWorldMatrix();
  55709. }
  55710. else {
  55711. var emitterPosition = this.emitter;
  55712. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55713. }
  55714. this._updateEffect.setMatrix("emitterWM", emitterWM);
  55715. // Bind source VAO
  55716. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  55717. // Update
  55718. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  55719. this._engine.setRasterizerState(false);
  55720. this._engine.beginTransformFeedback();
  55721. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  55722. this._engine.endTransformFeedback();
  55723. this._engine.setRasterizerState(true);
  55724. this._engine.bindTransformFeedbackBuffer(null);
  55725. // Enable render effect
  55726. this._engine.enableEffect(this._renderEffect);
  55727. var viewMatrix = this._scene.getViewMatrix();
  55728. this._renderEffect.setMatrix("view", viewMatrix);
  55729. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  55730. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  55731. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  55732. if (this._scene.clipPlane) {
  55733. var clipPlane = this._scene.clipPlane;
  55734. var invView = viewMatrix.clone();
  55735. invView.invert();
  55736. this._renderEffect.setMatrix("invView", invView);
  55737. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55738. }
  55739. // Draw order
  55740. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  55741. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55742. }
  55743. else {
  55744. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55745. }
  55746. if (this.forceDepthWrite) {
  55747. this._engine.setDepthWrite(true);
  55748. }
  55749. // Bind source VAO
  55750. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  55751. // Render
  55752. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  55753. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55754. // Switch VAOs
  55755. this._targetIndex++;
  55756. if (this._targetIndex === 2) {
  55757. this._targetIndex = 0;
  55758. }
  55759. // Switch buffers
  55760. var tmpBuffer = this._sourceBuffer;
  55761. this._sourceBuffer = this._targetBuffer;
  55762. this._targetBuffer = tmpBuffer;
  55763. return this._currentActiveCount;
  55764. };
  55765. /**
  55766. * Rebuilds the particle system
  55767. */
  55768. GPUParticleSystem.prototype.rebuild = function () {
  55769. this._initialize(true);
  55770. };
  55771. GPUParticleSystem.prototype._releaseBuffers = function () {
  55772. if (this._buffer0) {
  55773. this._buffer0.dispose();
  55774. this._buffer0 = null;
  55775. }
  55776. if (this._buffer1) {
  55777. this._buffer1.dispose();
  55778. this._buffer1 = null;
  55779. }
  55780. if (this._spriteBuffer) {
  55781. this._spriteBuffer.dispose();
  55782. this._spriteBuffer = null;
  55783. }
  55784. };
  55785. GPUParticleSystem.prototype._releaseVAOs = function () {
  55786. if (!this._updateVAO) {
  55787. return;
  55788. }
  55789. for (var index = 0; index < this._updateVAO.length; index++) {
  55790. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  55791. }
  55792. this._updateVAO = [];
  55793. for (var index = 0; index < this._renderVAO.length; index++) {
  55794. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  55795. }
  55796. this._renderVAO = [];
  55797. };
  55798. /**
  55799. * Disposes the particle system and free the associated resources
  55800. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55801. */
  55802. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  55803. if (disposeTexture === void 0) { disposeTexture = true; }
  55804. var index = this._scene.particleSystems.indexOf(this);
  55805. if (index > -1) {
  55806. this._scene.particleSystems.splice(index, 1);
  55807. }
  55808. this._releaseBuffers();
  55809. this._releaseVAOs();
  55810. if (this._randomTexture) {
  55811. this._randomTexture.dispose();
  55812. this._randomTexture = null;
  55813. }
  55814. if (disposeTexture && this.particleTexture) {
  55815. this.particleTexture.dispose();
  55816. this.particleTexture = null;
  55817. }
  55818. // Callback
  55819. this.onDisposeObservable.notifyObservers(this);
  55820. this.onDisposeObservable.clear();
  55821. };
  55822. /**
  55823. * Clones the particle system.
  55824. * @param name The name of the cloned object
  55825. * @param newEmitter The new emitter to use
  55826. * @returns the cloned particle system
  55827. */
  55828. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  55829. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  55830. BABYLON.Tools.DeepCopy(this, result);
  55831. if (newEmitter === undefined) {
  55832. newEmitter = this.emitter;
  55833. }
  55834. result.emitter = newEmitter;
  55835. if (this.particleTexture) {
  55836. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55837. }
  55838. return result;
  55839. };
  55840. /**
  55841. * Serializes the particle system to a JSON object.
  55842. * @returns the JSON object
  55843. */
  55844. GPUParticleSystem.prototype.serialize = function () {
  55845. var serializationObject = {};
  55846. serializationObject.name = this.name;
  55847. serializationObject.id = this.id;
  55848. // Emitter
  55849. if (this.emitter.position) {
  55850. var emitterMesh = this.emitter;
  55851. serializationObject.emitterId = emitterMesh.id;
  55852. }
  55853. else {
  55854. var emitterPosition = this.emitter;
  55855. serializationObject.emitter = emitterPosition.asArray();
  55856. }
  55857. serializationObject.capacity = this.getCapacity();
  55858. if (this.particleTexture) {
  55859. serializationObject.textureName = this.particleTexture.name;
  55860. }
  55861. // Animations
  55862. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55863. // Particle system
  55864. serializationObject.activeParticleCount = this.activeParticleCount;
  55865. serializationObject.randomTextureSize = this._randomTextureSize;
  55866. serializationObject.minSize = this.minSize;
  55867. serializationObject.maxSize = this.maxSize;
  55868. serializationObject.minEmitPower = this.minEmitPower;
  55869. serializationObject.maxEmitPower = this.maxEmitPower;
  55870. serializationObject.minLifeTime = this.minLifeTime;
  55871. serializationObject.maxLifeTime = this.maxLifeTime;
  55872. serializationObject.emitRate = this.emitRate;
  55873. serializationObject.gravity = this.gravity.asArray();
  55874. serializationObject.color1 = this.color1.asArray();
  55875. serializationObject.color2 = this.color2.asArray();
  55876. serializationObject.colorDead = this.colorDead.asArray();
  55877. serializationObject.updateSpeed = this.updateSpeed;
  55878. serializationObject.targetStopDuration = this.targetStopDuration;
  55879. serializationObject.blendMode = this.blendMode;
  55880. // Emitter
  55881. if (this.particleEmitterType) {
  55882. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55883. }
  55884. return serializationObject;
  55885. };
  55886. /**
  55887. * Parses a JSON object to create a GPU particle system.
  55888. * @param parsedParticleSystem The JSON object to parse
  55889. * @param scene The scene to create the particle system in
  55890. * @param rootUrl The root url to use to load external dependencies like texture
  55891. * @returns the parsed GPU particle system
  55892. */
  55893. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55894. var name = parsedParticleSystem.name;
  55895. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  55896. if (parsedParticleSystem.id) {
  55897. particleSystem.id = parsedParticleSystem.id;
  55898. }
  55899. // Texture
  55900. if (parsedParticleSystem.textureName) {
  55901. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55902. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55903. }
  55904. // Emitter
  55905. if (parsedParticleSystem.emitterId) {
  55906. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55907. }
  55908. else {
  55909. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55910. }
  55911. // Animations
  55912. if (parsedParticleSystem.animations) {
  55913. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55914. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55915. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55916. }
  55917. }
  55918. // Particle system
  55919. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  55920. particleSystem.minSize = parsedParticleSystem.minSize;
  55921. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55922. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55923. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55924. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55925. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55926. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55927. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55928. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55929. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55930. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55931. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55932. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55933. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55934. // Emitter
  55935. if (parsedParticleSystem.particleEmitterType) {
  55936. var emitterType = void 0;
  55937. switch (parsedParticleSystem.particleEmitterType.type) {
  55938. case "SphereEmitter":
  55939. emitterType = new BABYLON.SphereParticleEmitter();
  55940. break;
  55941. case "SphereDirectedParticleEmitter":
  55942. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  55943. break;
  55944. case "ConeEmitter":
  55945. emitterType = new BABYLON.ConeParticleEmitter();
  55946. break;
  55947. case "BoxEmitter":
  55948. default:
  55949. emitterType = new BABYLON.BoxParticleEmitter();
  55950. break;
  55951. }
  55952. emitterType.parse(parsedParticleSystem.particleEmitterType);
  55953. particleSystem.particleEmitterType = emitterType;
  55954. }
  55955. return particleSystem;
  55956. };
  55957. return GPUParticleSystem;
  55958. }());
  55959. BABYLON.GPUParticleSystem = GPUParticleSystem;
  55960. })(BABYLON || (BABYLON = {}));
  55961. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  55962. "use strict";
  55963. var BABYLON;
  55964. (function (BABYLON) {
  55965. /**
  55966. * Represents one particle of a solid particle system.
  55967. */
  55968. var SolidParticle = /** @class */ (function () {
  55969. /**
  55970. * Creates a Solid Particle object.
  55971. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  55972. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  55973. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  55974. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  55975. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  55976. * @param shapeId (integer) is the model shape identifier in the SPS.
  55977. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  55978. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  55979. */
  55980. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  55981. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  55982. /**
  55983. * particle global index
  55984. */
  55985. this.idx = 0;
  55986. /**
  55987. * The color of the particle
  55988. */
  55989. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55990. /**
  55991. * The world space position of the particle.
  55992. */
  55993. this.position = BABYLON.Vector3.Zero();
  55994. /**
  55995. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  55996. */
  55997. this.rotation = BABYLON.Vector3.Zero();
  55998. /**
  55999. * The scaling of the particle.
  56000. */
  56001. this.scaling = BABYLON.Vector3.One();
  56002. /**
  56003. * The uvs of the particle.
  56004. */
  56005. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56006. /**
  56007. * The current speed of the particle.
  56008. */
  56009. this.velocity = BABYLON.Vector3.Zero();
  56010. /**
  56011. * The pivot point in the particle local space.
  56012. */
  56013. this.pivot = BABYLON.Vector3.Zero();
  56014. /**
  56015. * Must the particle be translated from its pivot point in its local space ?
  56016. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56017. * Default : false
  56018. */
  56019. this.translateFromPivot = false;
  56020. /**
  56021. * Is the particle active or not ?
  56022. */
  56023. this.alive = true;
  56024. /**
  56025. * Is the particle visible or not ?
  56026. */
  56027. this.isVisible = true;
  56028. /**
  56029. * Index of this particle in the global "positions" array (Internal use)
  56030. */
  56031. this._pos = 0;
  56032. /**
  56033. * Index of this particle in the global "indices" array (Internal use)
  56034. */
  56035. this._ind = 0;
  56036. /**
  56037. * ModelShape id of this particle
  56038. */
  56039. this.shapeId = 0;
  56040. /**
  56041. * Index of the particle in its shape id (Internal use)
  56042. */
  56043. this.idxInShape = 0;
  56044. /**
  56045. * Still set as invisible in order to skip useless computations (Internal use)
  56046. */
  56047. this._stillInvisible = false;
  56048. /**
  56049. * Last computed particle rotation matrix
  56050. */
  56051. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56052. /**
  56053. * Parent particle Id, if any.
  56054. * Default null.
  56055. */
  56056. this.parentId = null;
  56057. /**
  56058. * Internal global position in the SPS.
  56059. */
  56060. this._globalPosition = BABYLON.Vector3.Zero();
  56061. this.idx = particleIndex;
  56062. this._pos = positionIndex;
  56063. this._ind = indiceIndex;
  56064. this._model = model;
  56065. this.shapeId = shapeId;
  56066. this.idxInShape = idxInShape;
  56067. this._sps = sps;
  56068. if (modelBoundingInfo) {
  56069. this._modelBoundingInfo = modelBoundingInfo;
  56070. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56071. }
  56072. }
  56073. Object.defineProperty(SolidParticle.prototype, "scale", {
  56074. /**
  56075. * Legacy support, changed scale to scaling
  56076. */
  56077. get: function () {
  56078. return this.scaling;
  56079. },
  56080. /**
  56081. * Legacy support, changed scale to scaling
  56082. */
  56083. set: function (scale) {
  56084. this.scaling = scale;
  56085. },
  56086. enumerable: true,
  56087. configurable: true
  56088. });
  56089. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56090. /**
  56091. * Legacy support, changed quaternion to rotationQuaternion
  56092. */
  56093. get: function () {
  56094. return this.rotationQuaternion;
  56095. },
  56096. /**
  56097. * Legacy support, changed quaternion to rotationQuaternion
  56098. */
  56099. set: function (q) {
  56100. this.rotationQuaternion = q;
  56101. },
  56102. enumerable: true,
  56103. configurable: true
  56104. });
  56105. /**
  56106. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  56107. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  56108. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  56109. * @returns true if it intersects
  56110. */
  56111. SolidParticle.prototype.intersectsMesh = function (target) {
  56112. if (!this._boundingInfo || !target._boundingInfo) {
  56113. return false;
  56114. }
  56115. if (this._sps._bSphereOnly) {
  56116. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  56117. }
  56118. return this._boundingInfo.intersects(target._boundingInfo, false);
  56119. };
  56120. return SolidParticle;
  56121. }());
  56122. BABYLON.SolidParticle = SolidParticle;
  56123. /**
  56124. * Represents the shape of the model used by one particle of a solid particle system.
  56125. * SPS internal tool, don't use it manually.
  56126. */
  56127. var ModelShape = /** @class */ (function () {
  56128. /**
  56129. * 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.
  56130. * SPS internal tool, don't use it manually.
  56131. * @ignore
  56132. */
  56133. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  56134. /**
  56135. * length of the shape in the model indices array (internal use)
  56136. */
  56137. this._indicesLength = 0;
  56138. this.shapeID = id;
  56139. this._shape = shape;
  56140. this._indicesLength = indicesLength;
  56141. this._shapeUV = shapeUV;
  56142. this._positionFunction = posFunction;
  56143. this._vertexFunction = vtxFunction;
  56144. }
  56145. return ModelShape;
  56146. }());
  56147. BABYLON.ModelShape = ModelShape;
  56148. /**
  56149. * Represents a Depth Sorted Particle in the solid particle system.
  56150. */
  56151. var DepthSortedParticle = /** @class */ (function () {
  56152. function DepthSortedParticle() {
  56153. /**
  56154. * Index of the particle in the "indices" array
  56155. */
  56156. this.ind = 0;
  56157. /**
  56158. * Length of the particle shape in the "indices" array
  56159. */
  56160. this.indicesLength = 0;
  56161. /**
  56162. * Squared distance from the particle to the camera
  56163. */
  56164. this.sqDistance = 0.0;
  56165. }
  56166. return DepthSortedParticle;
  56167. }());
  56168. BABYLON.DepthSortedParticle = DepthSortedParticle;
  56169. })(BABYLON || (BABYLON = {}));
  56170. //# sourceMappingURL=babylon.solidParticle.js.map
  56171. "use strict";
  56172. var BABYLON;
  56173. (function (BABYLON) {
  56174. /**
  56175. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  56176. *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.
  56177. * The SPS is also a particle system. It provides some methods to manage the particles.
  56178. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  56179. *
  56180. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56181. */
  56182. var SolidParticleSystem = /** @class */ (function () {
  56183. /**
  56184. * Creates a SPS (Solid Particle System) object.
  56185. * @param name (String) is the SPS name, this will be the underlying mesh name.
  56186. * @param scene (Scene) is the scene in which the SPS is added.
  56187. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  56188. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  56189. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  56190. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  56191. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  56192. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  56193. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  56194. */
  56195. function SolidParticleSystem(name, scene, options) {
  56196. /**
  56197. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56198. * Example : var p = SPS.particles[i];
  56199. */
  56200. this.particles = new Array();
  56201. /**
  56202. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56203. */
  56204. this.nbParticles = 0;
  56205. /**
  56206. * If the particles must ever face the camera (default false). Useful for planar particles.
  56207. */
  56208. this.billboard = false;
  56209. /**
  56210. * Recompute normals when adding a shape
  56211. */
  56212. this.recomputeNormals = true;
  56213. /**
  56214. * This a counter ofr your own usage. It's not set by any SPS functions.
  56215. */
  56216. this.counter = 0;
  56217. /**
  56218. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56219. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56220. */
  56221. this.vars = {};
  56222. /**
  56223. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  56224. */
  56225. this._bSphereOnly = false;
  56226. /**
  56227. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  56228. */
  56229. this._bSphereRadiusFactor = 1.0;
  56230. this._positions = new Array();
  56231. this._indices = new Array();
  56232. this._normals = new Array();
  56233. this._colors = new Array();
  56234. this._uvs = new Array();
  56235. this._index = 0; // indices index
  56236. this._updatable = true;
  56237. this._pickable = false;
  56238. this._isVisibilityBoxLocked = false;
  56239. this._alwaysVisible = false;
  56240. this._depthSort = false;
  56241. this._shapeCounter = 0;
  56242. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  56243. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56244. this._computeParticleColor = true;
  56245. this._computeParticleTexture = true;
  56246. this._computeParticleRotation = true;
  56247. this._computeParticleVertex = false;
  56248. this._computeBoundingBox = false;
  56249. this._depthSortParticles = true;
  56250. this._cam_axisZ = BABYLON.Vector3.Zero();
  56251. this._cam_axisY = BABYLON.Vector3.Zero();
  56252. this._cam_axisX = BABYLON.Vector3.Zero();
  56253. this._axisZ = BABYLON.Axis.Z;
  56254. this._camDir = BABYLON.Vector3.Zero();
  56255. this._camInvertedPosition = BABYLON.Vector3.Zero();
  56256. this._rotMatrix = new BABYLON.Matrix();
  56257. this._invertMatrix = new BABYLON.Matrix();
  56258. this._rotated = BABYLON.Vector3.Zero();
  56259. this._quaternion = new BABYLON.Quaternion();
  56260. this._vertex = BABYLON.Vector3.Zero();
  56261. this._normal = BABYLON.Vector3.Zero();
  56262. this._yaw = 0.0;
  56263. this._pitch = 0.0;
  56264. this._roll = 0.0;
  56265. this._halfroll = 0.0;
  56266. this._halfpitch = 0.0;
  56267. this._halfyaw = 0.0;
  56268. this._sinRoll = 0.0;
  56269. this._cosRoll = 0.0;
  56270. this._sinPitch = 0.0;
  56271. this._cosPitch = 0.0;
  56272. this._sinYaw = 0.0;
  56273. this._cosYaw = 0.0;
  56274. this._mustUnrotateFixedNormals = false;
  56275. this._minimum = BABYLON.Vector3.Zero();
  56276. this._maximum = BABYLON.Vector3.Zero();
  56277. this._minBbox = BABYLON.Vector3.Zero();
  56278. this._maxBbox = BABYLON.Vector3.Zero();
  56279. this._particlesIntersect = false;
  56280. this._depthSortFunction = function (p1, p2) {
  56281. return (p2.sqDistance - p1.sqDistance);
  56282. };
  56283. this._needs32Bits = false;
  56284. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  56285. this._scaledPivot = BABYLON.Vector3.Zero();
  56286. this._particleHasParent = false;
  56287. this.name = name;
  56288. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56289. this._camera = scene.activeCamera;
  56290. this._pickable = options ? options.isPickable : false;
  56291. this._depthSort = options ? options.enableDepthSort : false;
  56292. this._particlesIntersect = options ? options.particleIntersection : false;
  56293. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  56294. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  56295. if (options && options.updatable) {
  56296. this._updatable = options.updatable;
  56297. }
  56298. else {
  56299. this._updatable = true;
  56300. }
  56301. if (this._pickable) {
  56302. this.pickedParticles = [];
  56303. }
  56304. if (this._depthSort) {
  56305. this.depthSortedParticles = [];
  56306. }
  56307. }
  56308. /**
  56309. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56310. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56311. * @returns the created mesh
  56312. */
  56313. SolidParticleSystem.prototype.buildMesh = function () {
  56314. if (this.nbParticles === 0) {
  56315. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56316. this.addShape(triangle, 1);
  56317. triangle.dispose();
  56318. }
  56319. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  56320. this._positions32 = new Float32Array(this._positions);
  56321. this._uvs32 = new Float32Array(this._uvs);
  56322. this._colors32 = new Float32Array(this._colors);
  56323. if (this.recomputeNormals) {
  56324. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  56325. }
  56326. this._normals32 = new Float32Array(this._normals);
  56327. this._fixedNormal32 = new Float32Array(this._normals);
  56328. if (this._mustUnrotateFixedNormals) {
  56329. this._unrotateFixedNormals();
  56330. }
  56331. var vertexData = new BABYLON.VertexData();
  56332. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  56333. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56334. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56335. if (this._uvs32) {
  56336. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56337. ;
  56338. }
  56339. if (this._colors32) {
  56340. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56341. }
  56342. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56343. vertexData.applyToMesh(mesh, this._updatable);
  56344. this.mesh = mesh;
  56345. this.mesh.isPickable = this._pickable;
  56346. // free memory
  56347. if (!this._depthSort) {
  56348. this._indices = null;
  56349. }
  56350. this._positions = null;
  56351. this._normals = null;
  56352. this._uvs = null;
  56353. this._colors = null;
  56354. if (!this._updatable) {
  56355. this.particles.length = 0;
  56356. }
  56357. return mesh;
  56358. };
  56359. /**
  56360. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56361. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56362. * Thus the particles generated from `digest()` have their property `position` set yet.
  56363. * @param mesh ( Mesh ) is the mesh to be digested
  56364. * @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
  56365. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56366. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56367. * @returns the current SPS
  56368. */
  56369. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56370. var size = (options && options.facetNb) || 1;
  56371. var number = (options && options.number) || 0;
  56372. var delta = (options && options.delta) || 0;
  56373. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56374. var meshInd = mesh.getIndices();
  56375. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56376. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56377. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56378. var f = 0; // facet counter
  56379. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56380. // compute size from number
  56381. if (number) {
  56382. number = (number > totalFacets) ? totalFacets : number;
  56383. size = Math.round(totalFacets / number);
  56384. delta = 0;
  56385. }
  56386. else {
  56387. size = (size > totalFacets) ? totalFacets : size;
  56388. }
  56389. var facetPos = []; // submesh positions
  56390. var facetInd = []; // submesh indices
  56391. var facetUV = []; // submesh UV
  56392. var facetCol = []; // submesh colors
  56393. var barycenter = BABYLON.Vector3.Zero();
  56394. var sizeO = size;
  56395. while (f < totalFacets) {
  56396. size = sizeO + Math.floor((1 + delta) * Math.random());
  56397. if (f > totalFacets - size) {
  56398. size = totalFacets - f;
  56399. }
  56400. // reset temp arrays
  56401. facetPos.length = 0;
  56402. facetInd.length = 0;
  56403. facetUV.length = 0;
  56404. facetCol.length = 0;
  56405. // iterate over "size" facets
  56406. var fi = 0;
  56407. for (var j = f * 3; j < (f + size) * 3; j++) {
  56408. facetInd.push(fi);
  56409. var i = meshInd[j];
  56410. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56411. if (meshUV) {
  56412. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56413. }
  56414. if (meshCol) {
  56415. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56416. }
  56417. fi++;
  56418. }
  56419. // create a model shape for each single particle
  56420. var idx = this.nbParticles;
  56421. var shape = this._posToShape(facetPos);
  56422. var shapeUV = this._uvsToShapeUV(facetUV);
  56423. // compute the barycenter of the shape
  56424. var v;
  56425. for (v = 0; v < shape.length; v++) {
  56426. barycenter.addInPlace(shape[v]);
  56427. }
  56428. barycenter.scaleInPlace(1 / shape.length);
  56429. // shift the shape from its barycenter to the origin
  56430. for (v = 0; v < shape.length; v++) {
  56431. shape[v].subtractInPlace(barycenter);
  56432. }
  56433. var bInfo;
  56434. if (this._particlesIntersect) {
  56435. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  56436. }
  56437. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  56438. // add the particle in the SPS
  56439. var currentPos = this._positions.length;
  56440. var currentInd = this._indices.length;
  56441. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  56442. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  56443. // initialize the particle position
  56444. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56445. this._index += shape.length;
  56446. idx++;
  56447. this.nbParticles++;
  56448. this._shapeCounter++;
  56449. f += size;
  56450. }
  56451. return this;
  56452. };
  56453. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  56454. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  56455. var index = 0;
  56456. var idx = 0;
  56457. for (var p = 0; p < this.particles.length; p++) {
  56458. this._particle = this.particles[p];
  56459. this._shape = this._particle._model._shape;
  56460. if (this._particle.rotationQuaternion) {
  56461. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56462. }
  56463. else {
  56464. this._yaw = this._particle.rotation.y;
  56465. this._pitch = this._particle.rotation.x;
  56466. this._roll = this._particle.rotation.z;
  56467. this._quaternionRotationYPR();
  56468. }
  56469. this._quaternionToRotationMatrix();
  56470. this._rotMatrix.invertToRef(this._invertMatrix);
  56471. for (var pt = 0; pt < this._shape.length; pt++) {
  56472. idx = index + pt * 3;
  56473. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  56474. this._fixedNormal32[idx] = this._normal.x;
  56475. this._fixedNormal32[idx + 1] = this._normal.y;
  56476. this._fixedNormal32[idx + 2] = this._normal.z;
  56477. }
  56478. index = idx + 3;
  56479. }
  56480. };
  56481. //reset copy
  56482. SolidParticleSystem.prototype._resetCopy = function () {
  56483. this._copy.position.x = 0;
  56484. this._copy.position.y = 0;
  56485. this._copy.position.z = 0;
  56486. this._copy.rotation.x = 0;
  56487. this._copy.rotation.y = 0;
  56488. this._copy.rotation.z = 0;
  56489. this._copy.rotationQuaternion = null;
  56490. this._copy.scaling.x = 1.0;
  56491. this._copy.scaling.y = 1.0;
  56492. this._copy.scaling.z = 1.0;
  56493. this._copy.uvs.x = 0;
  56494. this._copy.uvs.y = 0;
  56495. this._copy.uvs.z = 1.0;
  56496. this._copy.uvs.w = 1.0;
  56497. this._copy.color = null;
  56498. this._copy.translateFromPivot = false;
  56499. };
  56500. // _meshBuilder : inserts the shape model in the global SPS mesh
  56501. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  56502. var i;
  56503. var u = 0;
  56504. var c = 0;
  56505. var n = 0;
  56506. this._resetCopy();
  56507. if (options && options.positionFunction) {
  56508. options.positionFunction(this._copy, idx, idxInShape);
  56509. this._mustUnrotateFixedNormals = true;
  56510. }
  56511. if (this._copy.rotationQuaternion) {
  56512. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56513. }
  56514. else {
  56515. this._yaw = this._copy.rotation.y;
  56516. this._pitch = this._copy.rotation.x;
  56517. this._roll = this._copy.rotation.z;
  56518. this._quaternionRotationYPR();
  56519. }
  56520. this._quaternionToRotationMatrix();
  56521. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  56522. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  56523. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  56524. if (this._copy.translateFromPivot) {
  56525. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  56526. }
  56527. else {
  56528. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  56529. }
  56530. for (i = 0; i < shape.length; i++) {
  56531. this._vertex.x = shape[i].x;
  56532. this._vertex.y = shape[i].y;
  56533. this._vertex.z = shape[i].z;
  56534. if (options && options.vertexFunction) {
  56535. options.vertexFunction(this._copy, this._vertex, i);
  56536. }
  56537. this._vertex.x *= this._copy.scaling.x;
  56538. this._vertex.y *= this._copy.scaling.y;
  56539. this._vertex.z *= this._copy.scaling.z;
  56540. this._vertex.x -= this._scaledPivot.x;
  56541. this._vertex.y -= this._scaledPivot.y;
  56542. this._vertex.z -= this._scaledPivot.z;
  56543. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56544. this._rotated.addInPlace(this._pivotBackTranslation);
  56545. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56546. if (meshUV) {
  56547. 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);
  56548. u += 2;
  56549. }
  56550. if (this._copy.color) {
  56551. this._color = this._copy.color;
  56552. }
  56553. else if (meshCol && meshCol[c] !== undefined) {
  56554. this._color.r = meshCol[c];
  56555. this._color.g = meshCol[c + 1];
  56556. this._color.b = meshCol[c + 2];
  56557. this._color.a = meshCol[c + 3];
  56558. }
  56559. else {
  56560. this._color.r = 1.0;
  56561. this._color.g = 1.0;
  56562. this._color.b = 1.0;
  56563. this._color.a = 1.0;
  56564. }
  56565. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56566. c += 4;
  56567. if (!this.recomputeNormals && meshNor) {
  56568. this._normal.x = meshNor[n];
  56569. this._normal.y = meshNor[n + 1];
  56570. this._normal.z = meshNor[n + 2];
  56571. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  56572. normals.push(this._normal.x, this._normal.y, this._normal.z);
  56573. n += 3;
  56574. }
  56575. }
  56576. for (i = 0; i < meshInd.length; i++) {
  56577. var current_ind = p + meshInd[i];
  56578. indices.push(current_ind);
  56579. if (current_ind > 65535) {
  56580. this._needs32Bits = true;
  56581. }
  56582. }
  56583. if (this._pickable) {
  56584. var nbfaces = meshInd.length / 3;
  56585. for (i = 0; i < nbfaces; i++) {
  56586. this.pickedParticles.push({ idx: idx, faceId: i });
  56587. }
  56588. }
  56589. if (this._depthSort) {
  56590. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  56591. }
  56592. return this._copy;
  56593. };
  56594. // returns a shape array from positions array
  56595. SolidParticleSystem.prototype._posToShape = function (positions) {
  56596. var shape = [];
  56597. for (var i = 0; i < positions.length; i += 3) {
  56598. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  56599. }
  56600. return shape;
  56601. };
  56602. // returns a shapeUV array from a Vector4 uvs
  56603. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  56604. var shapeUV = [];
  56605. if (uvs) {
  56606. for (var i = 0; i < uvs.length; i++)
  56607. shapeUV.push(uvs[i]);
  56608. }
  56609. return shapeUV;
  56610. };
  56611. // adds a new particle object in the particles array
  56612. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  56613. if (bInfo === void 0) { bInfo = null; }
  56614. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  56615. this.particles.push(sp);
  56616. return sp;
  56617. };
  56618. /**
  56619. * Adds some particles to the SPS from the model shape. Returns the shape id.
  56620. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  56621. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  56622. * @param nb (positive integer) the number of particles to be created from this model
  56623. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  56624. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  56625. * @returns the number of shapes in the system
  56626. */
  56627. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  56628. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56629. var meshInd = mesh.getIndices();
  56630. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56631. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56632. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56633. var bbInfo;
  56634. if (this._particlesIntersect) {
  56635. bbInfo = mesh.getBoundingInfo();
  56636. }
  56637. var shape = this._posToShape(meshPos);
  56638. var shapeUV = this._uvsToShapeUV(meshUV);
  56639. var posfunc = options ? options.positionFunction : null;
  56640. var vtxfunc = options ? options.vertexFunction : null;
  56641. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  56642. // particles
  56643. var sp;
  56644. var currentCopy;
  56645. var idx = this.nbParticles;
  56646. for (var i = 0; i < nb; i++) {
  56647. var currentPos = this._positions.length;
  56648. var currentInd = this._indices.length;
  56649. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  56650. if (this._updatable) {
  56651. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  56652. sp.position.copyFrom(currentCopy.position);
  56653. sp.rotation.copyFrom(currentCopy.rotation);
  56654. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  56655. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  56656. }
  56657. if (currentCopy.color && sp.color) {
  56658. sp.color.copyFrom(currentCopy.color);
  56659. }
  56660. sp.scaling.copyFrom(currentCopy.scaling);
  56661. sp.uvs.copyFrom(currentCopy.uvs);
  56662. }
  56663. this._index += shape.length;
  56664. idx++;
  56665. }
  56666. this.nbParticles += nb;
  56667. this._shapeCounter++;
  56668. return this._shapeCounter - 1;
  56669. };
  56670. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  56671. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  56672. this._resetCopy();
  56673. if (particle._model._positionFunction) {
  56674. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  56675. }
  56676. if (this._copy.rotationQuaternion) {
  56677. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56678. }
  56679. else {
  56680. this._yaw = this._copy.rotation.y;
  56681. this._pitch = this._copy.rotation.x;
  56682. this._roll = this._copy.rotation.z;
  56683. this._quaternionRotationYPR();
  56684. }
  56685. this._quaternionToRotationMatrix();
  56686. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  56687. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  56688. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  56689. if (this._copy.translateFromPivot) {
  56690. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  56691. }
  56692. else {
  56693. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  56694. }
  56695. this._shape = particle._model._shape;
  56696. for (var pt = 0; pt < this._shape.length; pt++) {
  56697. this._vertex.x = this._shape[pt].x;
  56698. this._vertex.y = this._shape[pt].y;
  56699. this._vertex.z = this._shape[pt].z;
  56700. if (particle._model._vertexFunction) {
  56701. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  56702. }
  56703. this._vertex.x *= this._copy.scaling.x;
  56704. this._vertex.y *= this._copy.scaling.y;
  56705. this._vertex.z *= this._copy.scaling.z;
  56706. this._vertex.x -= this._scaledPivot.x;
  56707. this._vertex.y -= this._scaledPivot.y;
  56708. this._vertex.z -= this._scaledPivot.z;
  56709. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56710. this._rotated.addInPlace(this._pivotBackTranslation);
  56711. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  56712. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  56713. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  56714. }
  56715. particle.position.x = 0.0;
  56716. particle.position.y = 0.0;
  56717. particle.position.z = 0.0;
  56718. particle.rotation.x = 0.0;
  56719. particle.rotation.y = 0.0;
  56720. particle.rotation.z = 0.0;
  56721. particle.rotationQuaternion = null;
  56722. particle.scaling.x = 1.0;
  56723. particle.scaling.y = 1.0;
  56724. particle.scaling.z = 1.0;
  56725. particle.uvs.x = 0.0;
  56726. particle.uvs.y = 0.0;
  56727. particle.uvs.z = 1.0;
  56728. particle.uvs.w = 1.0;
  56729. particle.pivot.x = 0.0;
  56730. particle.pivot.y = 0.0;
  56731. particle.pivot.z = 0.0;
  56732. particle.translateFromPivot = false;
  56733. particle.parentId = null;
  56734. };
  56735. /**
  56736. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  56737. * @returns the SPS.
  56738. */
  56739. SolidParticleSystem.prototype.rebuildMesh = function () {
  56740. for (var p = 0; p < this.particles.length; p++) {
  56741. this._rebuildParticle(this.particles[p]);
  56742. }
  56743. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56744. return this;
  56745. };
  56746. /**
  56747. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  56748. * This method calls `updateParticle()` for each particle of the SPS.
  56749. * For an animated SPS, it is usually called within the render loop.
  56750. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  56751. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  56752. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  56753. * @returns the SPS.
  56754. */
  56755. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  56756. if (start === void 0) { start = 0; }
  56757. if (end === void 0) { end = this.nbParticles - 1; }
  56758. if (update === void 0) { update = true; }
  56759. if (!this._updatable) {
  56760. return this;
  56761. }
  56762. // custom beforeUpdate
  56763. this.beforeUpdateParticles(start, end, update);
  56764. this._cam_axisX.x = 1.0;
  56765. this._cam_axisX.y = 0.0;
  56766. this._cam_axisX.z = 0.0;
  56767. this._cam_axisY.x = 0.0;
  56768. this._cam_axisY.y = 1.0;
  56769. this._cam_axisY.z = 0.0;
  56770. this._cam_axisZ.x = 0.0;
  56771. this._cam_axisZ.y = 0.0;
  56772. this._cam_axisZ.z = 1.0;
  56773. // cases when the World Matrix is to be computed first
  56774. if (this.billboard || this._depthSort) {
  56775. this.mesh.computeWorldMatrix(true);
  56776. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  56777. }
  56778. // if the particles will always face the camera
  56779. if (this.billboard) {
  56780. // compute the camera position and un-rotate it by the current mesh rotation
  56781. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  56782. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  56783. this._cam_axisZ.normalize();
  56784. // same for camera up vector extracted from the cam view matrix
  56785. var view = this._camera.getViewMatrix(true);
  56786. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  56787. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  56788. this._cam_axisY.normalize();
  56789. this._cam_axisX.normalize();
  56790. }
  56791. // if depthSort, compute the camera global position in the mesh local system
  56792. if (this._depthSort) {
  56793. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  56794. }
  56795. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  56796. var idx = 0; // current position index in the global array positions32
  56797. var index = 0; // position start index in the global array positions32 of the current particle
  56798. var colidx = 0; // current color index in the global array colors32
  56799. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  56800. var uvidx = 0; // current uv index in the global array uvs32
  56801. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  56802. var pt = 0; // current index in the particle model shape
  56803. if (this.mesh.isFacetDataEnabled) {
  56804. this._computeBoundingBox = true;
  56805. }
  56806. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  56807. if (this._computeBoundingBox) {
  56808. if (start == 0 && end == this.nbParticles - 1) {
  56809. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  56810. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  56811. }
  56812. else {
  56813. if (this.mesh._boundingInfo) {
  56814. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  56815. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  56816. }
  56817. }
  56818. }
  56819. // particle loop
  56820. index = this.particles[start]._pos;
  56821. var vpos = (index / 3) | 0;
  56822. colorIndex = vpos * 4;
  56823. uvIndex = vpos * 2;
  56824. for (var p = start; p <= end; p++) {
  56825. this._particle = this.particles[p];
  56826. this._shape = this._particle._model._shape;
  56827. this._shapeUV = this._particle._model._shapeUV;
  56828. // call to custom user function to update the particle properties
  56829. this.updateParticle(this._particle);
  56830. // camera-particle distance for depth sorting
  56831. if (this._depthSort && this._depthSortParticles) {
  56832. var dsp = this.depthSortedParticles[p];
  56833. dsp.ind = this._particle._ind;
  56834. dsp.indicesLength = this._particle._model._indicesLength;
  56835. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  56836. }
  56837. // skip the computations for inactive or already invisible particles
  56838. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  56839. // increment indexes for the next particle
  56840. pt = this._shape.length;
  56841. index += pt * 3;
  56842. colorIndex += pt * 4;
  56843. uvIndex += pt * 2;
  56844. continue;
  56845. }
  56846. if (this._particle.isVisible) {
  56847. this._particle._stillInvisible = false; // un-mark permanent invisibility
  56848. this._particleHasParent = (this._particle.parentId !== null);
  56849. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  56850. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  56851. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  56852. // particle rotation matrix
  56853. if (this.billboard) {
  56854. this._particle.rotation.x = 0.0;
  56855. this._particle.rotation.y = 0.0;
  56856. }
  56857. if (this._computeParticleRotation || this.billboard) {
  56858. if (this._particle.rotationQuaternion) {
  56859. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56860. }
  56861. else {
  56862. this._yaw = this._particle.rotation.y;
  56863. this._pitch = this._particle.rotation.x;
  56864. this._roll = this._particle.rotation.z;
  56865. this._quaternionRotationYPR();
  56866. }
  56867. this._quaternionToRotationMatrix();
  56868. }
  56869. if (this._particleHasParent) {
  56870. this._parent = this.particles[this._particle.parentId];
  56871. 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];
  56872. 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];
  56873. 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];
  56874. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  56875. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  56876. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  56877. if (this._computeParticleRotation || this.billboard) {
  56878. 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];
  56879. 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];
  56880. 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];
  56881. 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];
  56882. 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];
  56883. 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];
  56884. 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];
  56885. 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];
  56886. 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];
  56887. }
  56888. }
  56889. else {
  56890. this._particle._globalPosition.x = this._particle.position.x;
  56891. this._particle._globalPosition.y = this._particle.position.y;
  56892. this._particle._globalPosition.z = this._particle.position.z;
  56893. if (this._computeParticleRotation || this.billboard) {
  56894. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  56895. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  56896. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  56897. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  56898. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  56899. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  56900. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  56901. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  56902. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  56903. }
  56904. }
  56905. if (this._particle.translateFromPivot) {
  56906. this._pivotBackTranslation.x = 0.0;
  56907. this._pivotBackTranslation.y = 0.0;
  56908. this._pivotBackTranslation.z = 0.0;
  56909. }
  56910. else {
  56911. this._pivotBackTranslation.x = this._scaledPivot.x;
  56912. this._pivotBackTranslation.y = this._scaledPivot.y;
  56913. this._pivotBackTranslation.z = this._scaledPivot.z;
  56914. }
  56915. // particle vertex loop
  56916. for (pt = 0; pt < this._shape.length; pt++) {
  56917. idx = index + pt * 3;
  56918. colidx = colorIndex + pt * 4;
  56919. uvidx = uvIndex + pt * 2;
  56920. this._vertex.x = this._shape[pt].x;
  56921. this._vertex.y = this._shape[pt].y;
  56922. this._vertex.z = this._shape[pt].z;
  56923. if (this._computeParticleVertex) {
  56924. this.updateParticleVertex(this._particle, this._vertex, pt);
  56925. }
  56926. // positions
  56927. this._vertex.x *= this._particle.scaling.x;
  56928. this._vertex.y *= this._particle.scaling.y;
  56929. this._vertex.z *= this._particle.scaling.z;
  56930. this._vertex.x -= this._scaledPivot.x;
  56931. this._vertex.y -= this._scaledPivot.y;
  56932. this._vertex.z -= this._scaledPivot.z;
  56933. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  56934. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  56935. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  56936. this._rotated.x += this._pivotBackTranslation.x;
  56937. this._rotated.y += this._pivotBackTranslation.y;
  56938. this._rotated.z += this._pivotBackTranslation.z;
  56939. 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;
  56940. 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;
  56941. 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;
  56942. if (this._computeBoundingBox) {
  56943. if (this._positions32[idx] < this._minimum.x) {
  56944. this._minimum.x = this._positions32[idx];
  56945. }
  56946. if (this._positions32[idx] > this._maximum.x) {
  56947. this._maximum.x = this._positions32[idx];
  56948. }
  56949. if (this._positions32[idx + 1] < this._minimum.y) {
  56950. this._minimum.y = this._positions32[idx + 1];
  56951. }
  56952. if (this._positions32[idx + 1] > this._maximum.y) {
  56953. this._maximum.y = this._positions32[idx + 1];
  56954. }
  56955. if (this._positions32[idx + 2] < this._minimum.z) {
  56956. this._minimum.z = this._positions32[idx + 2];
  56957. }
  56958. if (this._positions32[idx + 2] > this._maximum.z) {
  56959. this._maximum.z = this._positions32[idx + 2];
  56960. }
  56961. }
  56962. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  56963. if (!this._computeParticleVertex) {
  56964. this._normal.x = this._fixedNormal32[idx];
  56965. this._normal.y = this._fixedNormal32[idx + 1];
  56966. this._normal.z = this._fixedNormal32[idx + 2];
  56967. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  56968. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  56969. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  56970. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  56971. 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;
  56972. 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;
  56973. }
  56974. if (this._computeParticleColor && this._particle.color) {
  56975. this._colors32[colidx] = this._particle.color.r;
  56976. this._colors32[colidx + 1] = this._particle.color.g;
  56977. this._colors32[colidx + 2] = this._particle.color.b;
  56978. this._colors32[colidx + 3] = this._particle.color.a;
  56979. }
  56980. if (this._computeParticleTexture) {
  56981. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  56982. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  56983. }
  56984. }
  56985. }
  56986. else {
  56987. this._particle._stillInvisible = true; // mark the particle as invisible
  56988. for (pt = 0; pt < this._shape.length; pt++) {
  56989. idx = index + pt * 3;
  56990. colidx = colorIndex + pt * 4;
  56991. uvidx = uvIndex + pt * 2;
  56992. this._positions32[idx] = 0.0;
  56993. this._positions32[idx + 1] = 0.0;
  56994. this._positions32[idx + 2] = 0.0;
  56995. this._normals32[idx] = 0.0;
  56996. this._normals32[idx + 1] = 0.0;
  56997. this._normals32[idx + 2] = 0.0;
  56998. if (this._computeParticleColor && this._particle.color) {
  56999. this._colors32[colidx] = this._particle.color.r;
  57000. this._colors32[colidx + 1] = this._particle.color.g;
  57001. this._colors32[colidx + 2] = this._particle.color.b;
  57002. this._colors32[colidx + 3] = this._particle.color.a;
  57003. }
  57004. if (this._computeParticleTexture) {
  57005. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57006. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57007. }
  57008. }
  57009. }
  57010. // if the particle intersections must be computed : update the bbInfo
  57011. if (this._particlesIntersect) {
  57012. var bInfo = this._particle._boundingInfo;
  57013. var bBox = bInfo.boundingBox;
  57014. var bSphere = bInfo.boundingSphere;
  57015. if (!this._bSphereOnly) {
  57016. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57017. for (var b = 0; b < bBox.vectors.length; b++) {
  57018. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57019. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57020. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57021. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57022. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57023. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57024. 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;
  57025. 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;
  57026. 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;
  57027. }
  57028. bBox._update(this.mesh._worldMatrix);
  57029. }
  57030. // place and scale the particle bouding sphere in the SPS local system, then update it
  57031. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57032. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57033. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57034. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57035. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57036. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57037. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57038. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57039. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57040. 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));
  57041. bSphere._update(this.mesh._worldMatrix);
  57042. }
  57043. // increment indexes for the next particle
  57044. index = idx + 3;
  57045. colorIndex = colidx + 4;
  57046. uvIndex = uvidx + 2;
  57047. }
  57048. // if the VBO must be updated
  57049. if (update) {
  57050. if (this._computeParticleColor) {
  57051. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57052. }
  57053. if (this._computeParticleTexture) {
  57054. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57055. }
  57056. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57057. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57058. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57059. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57060. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57061. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57062. for (var i = 0; i < this._normals32.length; i++) {
  57063. this._fixedNormal32[i] = this._normals32[i];
  57064. }
  57065. }
  57066. if (!this.mesh.areNormalsFrozen) {
  57067. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57068. }
  57069. }
  57070. if (this._depthSort && this._depthSortParticles) {
  57071. this.depthSortedParticles.sort(this._depthSortFunction);
  57072. var dspl = this.depthSortedParticles.length;
  57073. var sorted = 0;
  57074. var lind = 0;
  57075. var sind = 0;
  57076. var sid = 0;
  57077. for (sorted = 0; sorted < dspl; sorted++) {
  57078. lind = this.depthSortedParticles[sorted].indicesLength;
  57079. sind = this.depthSortedParticles[sorted].ind;
  57080. for (var i = 0; i < lind; i++) {
  57081. this._indices32[sid] = this._indices[sind + i];
  57082. sid++;
  57083. }
  57084. }
  57085. this.mesh.updateIndices(this._indices32);
  57086. }
  57087. }
  57088. if (this._computeBoundingBox) {
  57089. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57090. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57091. }
  57092. this.afterUpdateParticles(start, end, update);
  57093. return this;
  57094. };
  57095. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57096. this._halfroll = this._roll * 0.5;
  57097. this._halfpitch = this._pitch * 0.5;
  57098. this._halfyaw = this._yaw * 0.5;
  57099. this._sinRoll = Math.sin(this._halfroll);
  57100. this._cosRoll = Math.cos(this._halfroll);
  57101. this._sinPitch = Math.sin(this._halfpitch);
  57102. this._cosPitch = Math.cos(this._halfpitch);
  57103. this._sinYaw = Math.sin(this._halfyaw);
  57104. this._cosYaw = Math.cos(this._halfyaw);
  57105. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  57106. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  57107. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  57108. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  57109. };
  57110. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57111. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57112. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57113. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57114. this._rotMatrix.m[3] = 0;
  57115. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57116. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57117. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57118. this._rotMatrix.m[7] = 0;
  57119. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57120. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57121. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57122. this._rotMatrix.m[11] = 0;
  57123. this._rotMatrix.m[12] = 0;
  57124. this._rotMatrix.m[13] = 0;
  57125. this._rotMatrix.m[14] = 0;
  57126. this._rotMatrix.m[15] = 1.0;
  57127. };
  57128. /**
  57129. * Disposes the SPS.
  57130. */
  57131. SolidParticleSystem.prototype.dispose = function () {
  57132. this.mesh.dispose();
  57133. this.vars = null;
  57134. // drop references to internal big arrays for the GC
  57135. this._positions = null;
  57136. this._indices = null;
  57137. this._normals = null;
  57138. this._uvs = null;
  57139. this._colors = null;
  57140. this._indices32 = null;
  57141. this._positions32 = null;
  57142. this._normals32 = null;
  57143. this._fixedNormal32 = null;
  57144. this._uvs32 = null;
  57145. this._colors32 = null;
  57146. this.pickedParticles = null;
  57147. };
  57148. /**
  57149. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57150. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57151. * @returns the SPS.
  57152. */
  57153. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57154. if (!this._isVisibilityBoxLocked) {
  57155. this.mesh.refreshBoundingInfo();
  57156. }
  57157. return this;
  57158. };
  57159. /**
  57160. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57161. * @param size the size (float) of the visibility box
  57162. * note : this doesn't lock the SPS mesh bounding box.
  57163. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57164. */
  57165. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57166. var vis = size / 2;
  57167. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57168. };
  57169. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57170. /**
  57171. * Gets whether the SPS as always visible or not
  57172. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57173. */
  57174. get: function () {
  57175. return this._alwaysVisible;
  57176. },
  57177. /**
  57178. * Sets the SPS as always visible or not
  57179. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57180. */
  57181. set: function (val) {
  57182. this._alwaysVisible = val;
  57183. this.mesh.alwaysSelectAsActiveMesh = val;
  57184. },
  57185. enumerable: true,
  57186. configurable: true
  57187. });
  57188. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57189. /**
  57190. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57191. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57192. */
  57193. get: function () {
  57194. return this._isVisibilityBoxLocked;
  57195. },
  57196. /**
  57197. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57198. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57199. */
  57200. set: function (val) {
  57201. this._isVisibilityBoxLocked = val;
  57202. var boundingInfo = this.mesh.getBoundingInfo();
  57203. boundingInfo.isLocked = val;
  57204. },
  57205. enumerable: true,
  57206. configurable: true
  57207. });
  57208. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57209. /**
  57210. * Gets if `setParticles()` computes the particle rotations or not.
  57211. * Default value : true. The SPS is faster when it's set to false.
  57212. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57213. */
  57214. get: function () {
  57215. return this._computeParticleRotation;
  57216. },
  57217. /**
  57218. * Tells to `setParticles()` to compute the particle rotations or not.
  57219. * Default value : true. The SPS is faster when it's set to false.
  57220. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57221. */
  57222. set: function (val) {
  57223. this._computeParticleRotation = val;
  57224. },
  57225. enumerable: true,
  57226. configurable: true
  57227. });
  57228. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57229. /**
  57230. * Gets if `setParticles()` computes the particle colors or not.
  57231. * Default value : true. The SPS is faster when it's set to false.
  57232. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57233. */
  57234. get: function () {
  57235. return this._computeParticleColor;
  57236. },
  57237. /**
  57238. * Tells to `setParticles()` to compute the particle colors or not.
  57239. * Default value : true. The SPS is faster when it's set to false.
  57240. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57241. */
  57242. set: function (val) {
  57243. this._computeParticleColor = val;
  57244. },
  57245. enumerable: true,
  57246. configurable: true
  57247. });
  57248. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57249. /**
  57250. * Gets if `setParticles()` computes the particle textures or not.
  57251. * Default value : true. The SPS is faster when it's set to false.
  57252. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57253. */
  57254. get: function () {
  57255. return this._computeParticleTexture;
  57256. },
  57257. set: function (val) {
  57258. this._computeParticleTexture = val;
  57259. },
  57260. enumerable: true,
  57261. configurable: true
  57262. });
  57263. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57264. /**
  57265. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  57266. * Default value : false. The SPS is faster when it's set to false.
  57267. * Note : the particle custom vertex positions aren't stored values.
  57268. */
  57269. get: function () {
  57270. return this._computeParticleVertex;
  57271. },
  57272. /**
  57273. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57274. * Default value : false. The SPS is faster when it's set to false.
  57275. * Note : the particle custom vertex positions aren't stored values.
  57276. */
  57277. set: function (val) {
  57278. this._computeParticleVertex = val;
  57279. },
  57280. enumerable: true,
  57281. configurable: true
  57282. });
  57283. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57284. /**
  57285. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  57286. */
  57287. get: function () {
  57288. return this._computeBoundingBox;
  57289. },
  57290. /**
  57291. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57292. */
  57293. set: function (val) {
  57294. this._computeBoundingBox = val;
  57295. },
  57296. enumerable: true,
  57297. configurable: true
  57298. });
  57299. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  57300. /**
  57301. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  57302. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57303. * Default : `true`
  57304. */
  57305. get: function () {
  57306. return this._depthSortParticles;
  57307. },
  57308. /**
  57309. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  57310. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57311. * Default : `true`
  57312. */
  57313. set: function (val) {
  57314. this._depthSortParticles = val;
  57315. },
  57316. enumerable: true,
  57317. configurable: true
  57318. });
  57319. // =======================================================================
  57320. // Particle behavior logic
  57321. // these following methods may be overwritten by the user to fit his needs
  57322. /**
  57323. * This function does nothing. It may be overwritten to set all the particle first values.
  57324. * The SPS doesn't call this function, you may have to call it by your own.
  57325. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57326. */
  57327. SolidParticleSystem.prototype.initParticles = function () {
  57328. };
  57329. /**
  57330. * This function does nothing. It may be overwritten to recycle a particle.
  57331. * The SPS doesn't call this function, you may have to call it by your own.
  57332. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57333. * @param particle The particle to recycle
  57334. * @returns the recycled particle
  57335. */
  57336. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57337. return particle;
  57338. };
  57339. /**
  57340. * Updates a particle : this function should be overwritten by the user.
  57341. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57342. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57343. * @example : just set a particle position or velocity and recycle conditions
  57344. * @param particle The particle to update
  57345. * @returns the updated particle
  57346. */
  57347. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57348. return particle;
  57349. };
  57350. /**
  57351. * Updates a vertex of a particle : it can be overwritten by the user.
  57352. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57353. * @param particle the current particle
  57354. * @param vertex the current index of the current particle
  57355. * @param pt the index of the current vertex in the particle shape
  57356. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57357. * @example : just set a vertex particle position
  57358. * @returns the updated vertex
  57359. */
  57360. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57361. return vertex;
  57362. };
  57363. /**
  57364. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57365. * This does nothing and may be overwritten by the user.
  57366. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57367. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57368. * @param update the boolean update value actually passed to setParticles()
  57369. */
  57370. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57371. };
  57372. /**
  57373. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57374. * This will be passed three parameters.
  57375. * This does nothing and may be overwritten by the user.
  57376. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57377. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57378. * @param update the boolean update value actually passed to setParticles()
  57379. */
  57380. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57381. };
  57382. return SolidParticleSystem;
  57383. }());
  57384. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57385. })(BABYLON || (BABYLON = {}));
  57386. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  57387. "use strict";
  57388. var BABYLON;
  57389. (function (BABYLON) {
  57390. var ShaderMaterial = /** @class */ (function (_super) {
  57391. __extends(ShaderMaterial, _super);
  57392. function ShaderMaterial(name, scene, shaderPath, options) {
  57393. var _this = _super.call(this, name, scene) || this;
  57394. _this._textures = {};
  57395. _this._textureArrays = {};
  57396. _this._floats = {};
  57397. _this._ints = {};
  57398. _this._floatsArrays = {};
  57399. _this._colors3 = {};
  57400. _this._colors3Arrays = {};
  57401. _this._colors4 = {};
  57402. _this._vectors2 = {};
  57403. _this._vectors3 = {};
  57404. _this._vectors4 = {};
  57405. _this._matrices = {};
  57406. _this._matrices3x3 = {};
  57407. _this._matrices2x2 = {};
  57408. _this._vectors2Arrays = {};
  57409. _this._vectors3Arrays = {};
  57410. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57411. _this._shaderPath = shaderPath;
  57412. options.needAlphaBlending = options.needAlphaBlending || false;
  57413. options.needAlphaTesting = options.needAlphaTesting || false;
  57414. options.attributes = options.attributes || ["position", "normal", "uv"];
  57415. options.uniforms = options.uniforms || ["worldViewProjection"];
  57416. options.uniformBuffers = options.uniformBuffers || [];
  57417. options.samplers = options.samplers || [];
  57418. options.defines = options.defines || [];
  57419. _this._options = options;
  57420. return _this;
  57421. }
  57422. ShaderMaterial.prototype.getClassName = function () {
  57423. return "ShaderMaterial";
  57424. };
  57425. ShaderMaterial.prototype.needAlphaBlending = function () {
  57426. return this._options.needAlphaBlending;
  57427. };
  57428. ShaderMaterial.prototype.needAlphaTesting = function () {
  57429. return this._options.needAlphaTesting;
  57430. };
  57431. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57432. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57433. this._options.uniforms.push(uniformName);
  57434. }
  57435. };
  57436. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57437. if (this._options.samplers.indexOf(name) === -1) {
  57438. this._options.samplers.push(name);
  57439. }
  57440. this._textures[name] = texture;
  57441. return this;
  57442. };
  57443. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57444. if (this._options.samplers.indexOf(name) === -1) {
  57445. this._options.samplers.push(name);
  57446. }
  57447. this._checkUniform(name);
  57448. this._textureArrays[name] = textures;
  57449. return this;
  57450. };
  57451. ShaderMaterial.prototype.setFloat = function (name, value) {
  57452. this._checkUniform(name);
  57453. this._floats[name] = value;
  57454. return this;
  57455. };
  57456. ShaderMaterial.prototype.setInt = function (name, value) {
  57457. this._checkUniform(name);
  57458. this._ints[name] = value;
  57459. return this;
  57460. };
  57461. ShaderMaterial.prototype.setFloats = function (name, value) {
  57462. this._checkUniform(name);
  57463. this._floatsArrays[name] = value;
  57464. return this;
  57465. };
  57466. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57467. this._checkUniform(name);
  57468. this._colors3[name] = value;
  57469. return this;
  57470. };
  57471. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57472. this._checkUniform(name);
  57473. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57474. color.toArray(arr, arr.length);
  57475. return arr;
  57476. }, []);
  57477. return this;
  57478. };
  57479. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57480. this._checkUniform(name);
  57481. this._colors4[name] = value;
  57482. return this;
  57483. };
  57484. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57485. this._checkUniform(name);
  57486. this._vectors2[name] = value;
  57487. return this;
  57488. };
  57489. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57490. this._checkUniform(name);
  57491. this._vectors3[name] = value;
  57492. return this;
  57493. };
  57494. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57495. this._checkUniform(name);
  57496. this._vectors4[name] = value;
  57497. return this;
  57498. };
  57499. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57500. this._checkUniform(name);
  57501. this._matrices[name] = value;
  57502. return this;
  57503. };
  57504. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57505. this._checkUniform(name);
  57506. this._matrices3x3[name] = value;
  57507. return this;
  57508. };
  57509. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57510. this._checkUniform(name);
  57511. this._matrices2x2[name] = value;
  57512. return this;
  57513. };
  57514. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57515. this._checkUniform(name);
  57516. this._vectors2Arrays[name] = value;
  57517. return this;
  57518. };
  57519. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57520. this._checkUniform(name);
  57521. this._vectors3Arrays[name] = value;
  57522. return this;
  57523. };
  57524. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57525. if (!mesh) {
  57526. return true;
  57527. }
  57528. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57529. return false;
  57530. }
  57531. return false;
  57532. };
  57533. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57534. var scene = this.getScene();
  57535. var engine = scene.getEngine();
  57536. if (!this.checkReadyOnEveryCall) {
  57537. if (this._renderId === scene.getRenderId()) {
  57538. if (this._checkCache(scene, mesh, useInstances)) {
  57539. return true;
  57540. }
  57541. }
  57542. }
  57543. // Instances
  57544. var defines = [];
  57545. var attribs = [];
  57546. var fallbacks = new BABYLON.EffectFallbacks();
  57547. if (useInstances) {
  57548. defines.push("#define INSTANCES");
  57549. }
  57550. for (var index = 0; index < this._options.defines.length; index++) {
  57551. defines.push(this._options.defines[index]);
  57552. }
  57553. for (var index = 0; index < this._options.attributes.length; index++) {
  57554. attribs.push(this._options.attributes[index]);
  57555. }
  57556. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57557. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57558. defines.push("#define VERTEXCOLOR");
  57559. }
  57560. // Bones
  57561. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57562. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57563. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57564. if (mesh.numBoneInfluencers > 4) {
  57565. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57566. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57567. }
  57568. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57569. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57570. fallbacks.addCPUSkinningFallback(0, mesh);
  57571. if (this._options.uniforms.indexOf("mBones") === -1) {
  57572. this._options.uniforms.push("mBones");
  57573. }
  57574. }
  57575. else {
  57576. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57577. }
  57578. // Textures
  57579. for (var name in this._textures) {
  57580. if (!this._textures[name].isReady()) {
  57581. return false;
  57582. }
  57583. }
  57584. // Alpha test
  57585. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57586. defines.push("#define ALPHATEST");
  57587. }
  57588. var previousEffect = this._effect;
  57589. var join = defines.join("\n");
  57590. this._effect = engine.createEffect(this._shaderPath, {
  57591. attributes: attribs,
  57592. uniformsNames: this._options.uniforms,
  57593. uniformBuffersNames: this._options.uniformBuffers,
  57594. samplers: this._options.samplers,
  57595. defines: join,
  57596. fallbacks: fallbacks,
  57597. onCompiled: this.onCompiled,
  57598. onError: this.onError
  57599. }, engine);
  57600. if (!this._effect.isReady()) {
  57601. return false;
  57602. }
  57603. if (previousEffect !== this._effect) {
  57604. scene.resetCachedMaterial();
  57605. }
  57606. this._renderId = scene.getRenderId();
  57607. return true;
  57608. };
  57609. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57610. var scene = this.getScene();
  57611. if (!this._effect) {
  57612. return;
  57613. }
  57614. if (this._options.uniforms.indexOf("world") !== -1) {
  57615. this._effect.setMatrix("world", world);
  57616. }
  57617. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57618. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57619. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57620. }
  57621. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57622. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57623. }
  57624. };
  57625. ShaderMaterial.prototype.bind = function (world, mesh) {
  57626. // Std values
  57627. this.bindOnlyWorldMatrix(world);
  57628. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57629. if (this._options.uniforms.indexOf("view") !== -1) {
  57630. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57631. }
  57632. if (this._options.uniforms.indexOf("projection") !== -1) {
  57633. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57634. }
  57635. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57636. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57637. }
  57638. // Bones
  57639. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57640. var name;
  57641. // Texture
  57642. for (name in this._textures) {
  57643. this._effect.setTexture(name, this._textures[name]);
  57644. }
  57645. // Texture arrays
  57646. for (name in this._textureArrays) {
  57647. this._effect.setTextureArray(name, this._textureArrays[name]);
  57648. }
  57649. // Int
  57650. for (name in this._ints) {
  57651. this._effect.setInt(name, this._ints[name]);
  57652. }
  57653. // Float
  57654. for (name in this._floats) {
  57655. this._effect.setFloat(name, this._floats[name]);
  57656. }
  57657. // Floats
  57658. for (name in this._floatsArrays) {
  57659. this._effect.setArray(name, this._floatsArrays[name]);
  57660. }
  57661. // Color3
  57662. for (name in this._colors3) {
  57663. this._effect.setColor3(name, this._colors3[name]);
  57664. }
  57665. for (name in this._colors3Arrays) {
  57666. this._effect.setArray3(name, this._colors3Arrays[name]);
  57667. }
  57668. // Color4
  57669. for (name in this._colors4) {
  57670. var color = this._colors4[name];
  57671. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57672. }
  57673. // Vector2
  57674. for (name in this._vectors2) {
  57675. this._effect.setVector2(name, this._vectors2[name]);
  57676. }
  57677. // Vector3
  57678. for (name in this._vectors3) {
  57679. this._effect.setVector3(name, this._vectors3[name]);
  57680. }
  57681. // Vector4
  57682. for (name in this._vectors4) {
  57683. this._effect.setVector4(name, this._vectors4[name]);
  57684. }
  57685. // Matrix
  57686. for (name in this._matrices) {
  57687. this._effect.setMatrix(name, this._matrices[name]);
  57688. }
  57689. // Matrix 3x3
  57690. for (name in this._matrices3x3) {
  57691. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57692. }
  57693. // Matrix 2x2
  57694. for (name in this._matrices2x2) {
  57695. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57696. }
  57697. // Vector2Array
  57698. for (name in this._vectors2Arrays) {
  57699. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57700. }
  57701. // Vector3Array
  57702. for (name in this._vectors3Arrays) {
  57703. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57704. }
  57705. }
  57706. this._afterBind(mesh);
  57707. };
  57708. ShaderMaterial.prototype.getActiveTextures = function () {
  57709. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57710. for (var name in this._textures) {
  57711. activeTextures.push(this._textures[name]);
  57712. }
  57713. for (var name in this._textureArrays) {
  57714. var array = this._textureArrays[name];
  57715. for (var index = 0; index < array.length; index++) {
  57716. activeTextures.push(array[index]);
  57717. }
  57718. }
  57719. return activeTextures;
  57720. };
  57721. ShaderMaterial.prototype.hasTexture = function (texture) {
  57722. if (_super.prototype.hasTexture.call(this, texture)) {
  57723. return true;
  57724. }
  57725. for (var name in this._textures) {
  57726. if (this._textures[name] === texture) {
  57727. return true;
  57728. }
  57729. }
  57730. for (var name in this._textureArrays) {
  57731. var array = this._textureArrays[name];
  57732. for (var index = 0; index < array.length; index++) {
  57733. if (array[index] === texture) {
  57734. return true;
  57735. }
  57736. }
  57737. }
  57738. return false;
  57739. };
  57740. ShaderMaterial.prototype.clone = function (name) {
  57741. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57742. return newShaderMaterial;
  57743. };
  57744. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57745. if (forceDisposeTextures) {
  57746. var name;
  57747. for (name in this._textures) {
  57748. this._textures[name].dispose();
  57749. }
  57750. for (name in this._textureArrays) {
  57751. var array = this._textureArrays[name];
  57752. for (var index = 0; index < array.length; index++) {
  57753. array[index].dispose();
  57754. }
  57755. }
  57756. }
  57757. this._textures = {};
  57758. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57759. };
  57760. ShaderMaterial.prototype.serialize = function () {
  57761. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57762. serializationObject.customType = "BABYLON.ShaderMaterial";
  57763. serializationObject.options = this._options;
  57764. serializationObject.shaderPath = this._shaderPath;
  57765. var name;
  57766. // Texture
  57767. serializationObject.textures = {};
  57768. for (name in this._textures) {
  57769. serializationObject.textures[name] = this._textures[name].serialize();
  57770. }
  57771. // Texture arrays
  57772. serializationObject.textureArrays = {};
  57773. for (name in this._textureArrays) {
  57774. serializationObject.textureArrays[name] = [];
  57775. var array = this._textureArrays[name];
  57776. for (var index = 0; index < array.length; index++) {
  57777. serializationObject.textureArrays[name].push(array[index].serialize());
  57778. }
  57779. }
  57780. // Float
  57781. serializationObject.floats = {};
  57782. for (name in this._floats) {
  57783. serializationObject.floats[name] = this._floats[name];
  57784. }
  57785. // Float s
  57786. serializationObject.FloatArrays = {};
  57787. for (name in this._floatsArrays) {
  57788. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57789. }
  57790. // Color3
  57791. serializationObject.colors3 = {};
  57792. for (name in this._colors3) {
  57793. serializationObject.colors3[name] = this._colors3[name].asArray();
  57794. }
  57795. // Color3 array
  57796. serializationObject.colors3Arrays = {};
  57797. for (name in this._colors3Arrays) {
  57798. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57799. }
  57800. // Color4
  57801. serializationObject.colors4 = {};
  57802. for (name in this._colors4) {
  57803. serializationObject.colors4[name] = this._colors4[name].asArray();
  57804. }
  57805. // Vector2
  57806. serializationObject.vectors2 = {};
  57807. for (name in this._vectors2) {
  57808. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57809. }
  57810. // Vector3
  57811. serializationObject.vectors3 = {};
  57812. for (name in this._vectors3) {
  57813. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57814. }
  57815. // Vector4
  57816. serializationObject.vectors4 = {};
  57817. for (name in this._vectors4) {
  57818. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57819. }
  57820. // Matrix
  57821. serializationObject.matrices = {};
  57822. for (name in this._matrices) {
  57823. serializationObject.matrices[name] = this._matrices[name].asArray();
  57824. }
  57825. // Matrix 3x3
  57826. serializationObject.matrices3x3 = {};
  57827. for (name in this._matrices3x3) {
  57828. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57829. }
  57830. // Matrix 2x2
  57831. serializationObject.matrices2x2 = {};
  57832. for (name in this._matrices2x2) {
  57833. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57834. }
  57835. // Vector2Array
  57836. serializationObject.vectors2Arrays = {};
  57837. for (name in this._vectors2Arrays) {
  57838. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57839. }
  57840. // Vector3Array
  57841. serializationObject.vectors3Arrays = {};
  57842. for (name in this._vectors3Arrays) {
  57843. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57844. }
  57845. return serializationObject;
  57846. };
  57847. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57848. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57849. var name;
  57850. // Texture
  57851. for (name in source.textures) {
  57852. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57853. }
  57854. // Texture arrays
  57855. for (name in source.textureArrays) {
  57856. var array = source.textureArrays[name];
  57857. var textureArray = new Array();
  57858. for (var index = 0; index < array.length; index++) {
  57859. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57860. }
  57861. material.setTextureArray(name, textureArray);
  57862. }
  57863. // Float
  57864. for (name in source.floats) {
  57865. material.setFloat(name, source.floats[name]);
  57866. }
  57867. // Float s
  57868. for (name in source.floatsArrays) {
  57869. material.setFloats(name, source.floatsArrays[name]);
  57870. }
  57871. // Color3
  57872. for (name in source.colors3) {
  57873. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57874. }
  57875. // Color3 arrays
  57876. for (name in source.colors3Arrays) {
  57877. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57878. if (i % 3 === 0) {
  57879. arr.push([num]);
  57880. }
  57881. else {
  57882. arr[arr.length - 1].push(num);
  57883. }
  57884. return arr;
  57885. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57886. material.setColor3Array(name, colors);
  57887. }
  57888. // Color4
  57889. for (name in source.colors4) {
  57890. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57891. }
  57892. // Vector2
  57893. for (name in source.vectors2) {
  57894. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57895. }
  57896. // Vector3
  57897. for (name in source.vectors3) {
  57898. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57899. }
  57900. // Vector4
  57901. for (name in source.vectors4) {
  57902. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57903. }
  57904. // Matrix
  57905. for (name in source.matrices) {
  57906. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57907. }
  57908. // Matrix 3x3
  57909. for (name in source.matrices3x3) {
  57910. material.setMatrix3x3(name, source.matrices3x3[name]);
  57911. }
  57912. // Matrix 2x2
  57913. for (name in source.matrices2x2) {
  57914. material.setMatrix2x2(name, source.matrices2x2[name]);
  57915. }
  57916. // Vector2Array
  57917. for (name in source.vectors2Arrays) {
  57918. material.setArray2(name, source.vectors2Arrays[name]);
  57919. }
  57920. // Vector3Array
  57921. for (name in source.vectors3Arrays) {
  57922. material.setArray3(name, source.vectors3Arrays[name]);
  57923. }
  57924. return material;
  57925. };
  57926. return ShaderMaterial;
  57927. }(BABYLON.Material));
  57928. BABYLON.ShaderMaterial = ShaderMaterial;
  57929. })(BABYLON || (BABYLON = {}));
  57930. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57931. "use strict";
  57932. var BABYLON;
  57933. (function (BABYLON) {
  57934. var GroundMesh = /** @class */ (function (_super) {
  57935. __extends(GroundMesh, _super);
  57936. function GroundMesh(name, scene) {
  57937. var _this = _super.call(this, name, scene) || this;
  57938. _this.generateOctree = false;
  57939. return _this;
  57940. }
  57941. GroundMesh.prototype.getClassName = function () {
  57942. return "GroundMesh";
  57943. };
  57944. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57945. get: function () {
  57946. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57947. },
  57948. enumerable: true,
  57949. configurable: true
  57950. });
  57951. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57952. get: function () {
  57953. return this._subdivisionsX;
  57954. },
  57955. enumerable: true,
  57956. configurable: true
  57957. });
  57958. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57959. get: function () {
  57960. return this._subdivisionsY;
  57961. },
  57962. enumerable: true,
  57963. configurable: true
  57964. });
  57965. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57966. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57967. this._subdivisionsX = chunksCount;
  57968. this._subdivisionsY = chunksCount;
  57969. this.subdivide(chunksCount);
  57970. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57971. };
  57972. /**
  57973. * Returns a height (y) value in the Worl system :
  57974. * the ground altitude at the coordinates (x, z) expressed in the World system.
  57975. * Returns the ground y position if (x, z) are outside the ground surface.
  57976. */
  57977. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  57978. var world = this.getWorldMatrix();
  57979. var invMat = BABYLON.Tmp.Matrix[5];
  57980. world.invertToRef(invMat);
  57981. var tmpVect = BABYLON.Tmp.Vector3[8];
  57982. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  57983. x = tmpVect.x;
  57984. z = tmpVect.z;
  57985. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57986. return this.position.y;
  57987. }
  57988. if (!this._heightQuads || this._heightQuads.length == 0) {
  57989. this._initHeightQuads();
  57990. this._computeHeightQuads();
  57991. }
  57992. var facet = this._getFacetAt(x, z);
  57993. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  57994. // return y in the World system
  57995. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  57996. return tmpVect.y;
  57997. };
  57998. /**
  57999. * Returns a normalized vector (Vector3) orthogonal to the ground
  58000. * at the ground coordinates (x, z) expressed in the World system.
  58001. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58002. */
  58003. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58004. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58005. this.getNormalAtCoordinatesToRef(x, z, normal);
  58006. return normal;
  58007. };
  58008. /**
  58009. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58010. * at the ground coordinates (x, z) expressed in the World system.
  58011. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58012. * Returns the GroundMesh.
  58013. */
  58014. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58015. var world = this.getWorldMatrix();
  58016. var tmpMat = BABYLON.Tmp.Matrix[5];
  58017. world.invertToRef(tmpMat);
  58018. var tmpVect = BABYLON.Tmp.Vector3[8];
  58019. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58020. x = tmpVect.x;
  58021. z = tmpVect.z;
  58022. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58023. return this;
  58024. }
  58025. if (!this._heightQuads || this._heightQuads.length == 0) {
  58026. this._initHeightQuads();
  58027. this._computeHeightQuads();
  58028. }
  58029. var facet = this._getFacetAt(x, z);
  58030. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58031. return this;
  58032. };
  58033. /**
  58034. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58035. * if the ground has been updated.
  58036. * This can be used in the render loop.
  58037. * Returns the GroundMesh.
  58038. */
  58039. GroundMesh.prototype.updateCoordinateHeights = function () {
  58040. if (!this._heightQuads || this._heightQuads.length == 0) {
  58041. this._initHeightQuads();
  58042. }
  58043. this._computeHeightQuads();
  58044. return this;
  58045. };
  58046. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58047. GroundMesh.prototype._getFacetAt = function (x, z) {
  58048. // retrieve col and row from x, z coordinates in the ground local system
  58049. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58050. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58051. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58052. var facet;
  58053. if (z < quad.slope.x * x + quad.slope.y) {
  58054. facet = quad.facet1;
  58055. }
  58056. else {
  58057. facet = quad.facet2;
  58058. }
  58059. return facet;
  58060. };
  58061. // Creates and populates the heightMap array with "facet" elements :
  58062. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58063. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58064. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58065. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58066. // Returns the GroundMesh.
  58067. GroundMesh.prototype._initHeightQuads = function () {
  58068. var subdivisionsX = this._subdivisionsX;
  58069. var subdivisionsY = this._subdivisionsY;
  58070. this._heightQuads = new Array();
  58071. for (var row = 0; row < subdivisionsY; row++) {
  58072. for (var col = 0; col < subdivisionsX; col++) {
  58073. 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) };
  58074. this._heightQuads[row * subdivisionsX + col] = quad;
  58075. }
  58076. }
  58077. return this;
  58078. };
  58079. // Compute each quad element values and update the the heightMap array :
  58080. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58081. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58082. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58083. // Returns the GroundMesh.
  58084. GroundMesh.prototype._computeHeightQuads = function () {
  58085. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58086. if (!positions) {
  58087. return this;
  58088. }
  58089. var v1 = BABYLON.Tmp.Vector3[3];
  58090. var v2 = BABYLON.Tmp.Vector3[2];
  58091. var v3 = BABYLON.Tmp.Vector3[1];
  58092. var v4 = BABYLON.Tmp.Vector3[0];
  58093. var v1v2 = BABYLON.Tmp.Vector3[4];
  58094. var v1v3 = BABYLON.Tmp.Vector3[5];
  58095. var v1v4 = BABYLON.Tmp.Vector3[6];
  58096. var norm1 = BABYLON.Tmp.Vector3[7];
  58097. var norm2 = BABYLON.Tmp.Vector3[8];
  58098. var i = 0;
  58099. var j = 0;
  58100. var k = 0;
  58101. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58102. var h = 0;
  58103. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58104. var d2 = 0;
  58105. var subdivisionsX = this._subdivisionsX;
  58106. var subdivisionsY = this._subdivisionsY;
  58107. for (var row = 0; row < subdivisionsY; row++) {
  58108. for (var col = 0; col < subdivisionsX; col++) {
  58109. i = col * 3;
  58110. j = row * (subdivisionsX + 1) * 3;
  58111. k = (row + 1) * (subdivisionsX + 1) * 3;
  58112. v1.x = positions[j + i];
  58113. v1.y = positions[j + i + 1];
  58114. v1.z = positions[j + i + 2];
  58115. v2.x = positions[j + i + 3];
  58116. v2.y = positions[j + i + 4];
  58117. v2.z = positions[j + i + 5];
  58118. v3.x = positions[k + i];
  58119. v3.y = positions[k + i + 1];
  58120. v3.z = positions[k + i + 2];
  58121. v4.x = positions[k + i + 3];
  58122. v4.y = positions[k + i + 4];
  58123. v4.z = positions[k + i + 5];
  58124. // 2D slope V1V4
  58125. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58126. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58127. // facet equations :
  58128. // we compute each facet normal vector
  58129. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58130. // we compute the value d by applying the equation to v1 which belongs to the plane
  58131. // then we store the facet equation in a Vector4
  58132. v2.subtractToRef(v1, v1v2);
  58133. v3.subtractToRef(v1, v1v3);
  58134. v4.subtractToRef(v1, v1v4);
  58135. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58136. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58137. norm1.normalize();
  58138. norm2.normalize();
  58139. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58140. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58141. var quad = this._heightQuads[row * subdivisionsX + col];
  58142. quad.slope.copyFromFloats(cd, h);
  58143. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58144. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58145. }
  58146. }
  58147. return this;
  58148. };
  58149. GroundMesh.prototype.serialize = function (serializationObject) {
  58150. _super.prototype.serialize.call(this, serializationObject);
  58151. serializationObject.subdivisionsX = this._subdivisionsX;
  58152. serializationObject.subdivisionsY = this._subdivisionsY;
  58153. serializationObject.minX = this._minX;
  58154. serializationObject.maxX = this._maxX;
  58155. serializationObject.minZ = this._minZ;
  58156. serializationObject.maxZ = this._maxZ;
  58157. serializationObject.width = this._width;
  58158. serializationObject.height = this._height;
  58159. };
  58160. GroundMesh.Parse = function (parsedMesh, scene) {
  58161. var result = new GroundMesh(parsedMesh.name, scene);
  58162. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58163. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58164. result._minX = parsedMesh.minX;
  58165. result._maxX = parsedMesh.maxX;
  58166. result._minZ = parsedMesh.minZ;
  58167. result._maxZ = parsedMesh.maxZ;
  58168. result._width = parsedMesh.width;
  58169. result._height = parsedMesh.height;
  58170. return result;
  58171. };
  58172. return GroundMesh;
  58173. }(BABYLON.Mesh));
  58174. BABYLON.GroundMesh = GroundMesh;
  58175. })(BABYLON || (BABYLON = {}));
  58176. //# sourceMappingURL=babylon.groundMesh.js.map
  58177. "use strict";
  58178. var BABYLON;
  58179. (function (BABYLON) {
  58180. /**
  58181. * Creates an instance based on a source mesh.
  58182. */
  58183. var InstancedMesh = /** @class */ (function (_super) {
  58184. __extends(InstancedMesh, _super);
  58185. function InstancedMesh(name, source) {
  58186. var _this = _super.call(this, name, source.getScene()) || this;
  58187. source.instances.push(_this);
  58188. _this._sourceMesh = source;
  58189. _this.position.copyFrom(source.position);
  58190. _this.rotation.copyFrom(source.rotation);
  58191. _this.scaling.copyFrom(source.scaling);
  58192. if (source.rotationQuaternion) {
  58193. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58194. }
  58195. _this.infiniteDistance = source.infiniteDistance;
  58196. _this.setPivotMatrix(source.getPivotMatrix());
  58197. _this.refreshBoundingInfo();
  58198. _this._syncSubMeshes();
  58199. return _this;
  58200. }
  58201. /**
  58202. * Returns the string "InstancedMesh".
  58203. */
  58204. InstancedMesh.prototype.getClassName = function () {
  58205. return "InstancedMesh";
  58206. };
  58207. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58208. // Methods
  58209. get: function () {
  58210. return this._sourceMesh.receiveShadows;
  58211. },
  58212. enumerable: true,
  58213. configurable: true
  58214. });
  58215. Object.defineProperty(InstancedMesh.prototype, "material", {
  58216. get: function () {
  58217. return this._sourceMesh.material;
  58218. },
  58219. enumerable: true,
  58220. configurable: true
  58221. });
  58222. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58223. get: function () {
  58224. return this._sourceMesh.visibility;
  58225. },
  58226. enumerable: true,
  58227. configurable: true
  58228. });
  58229. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58230. get: function () {
  58231. return this._sourceMesh.skeleton;
  58232. },
  58233. enumerable: true,
  58234. configurable: true
  58235. });
  58236. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58237. get: function () {
  58238. return this._sourceMesh.renderingGroupId;
  58239. },
  58240. set: function (value) {
  58241. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58242. return;
  58243. }
  58244. //no-op with warning
  58245. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58246. },
  58247. enumerable: true,
  58248. configurable: true
  58249. });
  58250. /**
  58251. * Returns the total number of vertices (integer).
  58252. */
  58253. InstancedMesh.prototype.getTotalVertices = function () {
  58254. return this._sourceMesh.getTotalVertices();
  58255. };
  58256. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58257. get: function () {
  58258. return this._sourceMesh;
  58259. },
  58260. enumerable: true,
  58261. configurable: true
  58262. });
  58263. /**
  58264. * Is this node ready to be used/rendered
  58265. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58266. * @return {boolean} is it ready
  58267. */
  58268. InstancedMesh.prototype.isReady = function (completeCheck) {
  58269. if (completeCheck === void 0) { completeCheck = false; }
  58270. return this._sourceMesh.isReady(completeCheck, true);
  58271. };
  58272. /**
  58273. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58274. */
  58275. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58276. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58277. };
  58278. /**
  58279. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58280. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58281. * The `data` are either a numeric array either a Float32Array.
  58282. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58283. * 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).
  58284. * Note that a new underlying VertexBuffer object is created each call.
  58285. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58286. *
  58287. * Possible `kind` values :
  58288. * - BABYLON.VertexBuffer.PositionKind
  58289. * - BABYLON.VertexBuffer.UVKind
  58290. * - BABYLON.VertexBuffer.UV2Kind
  58291. * - BABYLON.VertexBuffer.UV3Kind
  58292. * - BABYLON.VertexBuffer.UV4Kind
  58293. * - BABYLON.VertexBuffer.UV5Kind
  58294. * - BABYLON.VertexBuffer.UV6Kind
  58295. * - BABYLON.VertexBuffer.ColorKind
  58296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58300. *
  58301. * Returns the Mesh.
  58302. */
  58303. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58304. if (this.sourceMesh) {
  58305. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58306. }
  58307. return this.sourceMesh;
  58308. };
  58309. /**
  58310. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58311. * If the mesh has no geometry, it is simply returned as it is.
  58312. * The `data` are either a numeric array either a Float32Array.
  58313. * No new underlying VertexBuffer object is created.
  58314. * 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.
  58315. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58316. *
  58317. * Possible `kind` values :
  58318. * - BABYLON.VertexBuffer.PositionKind
  58319. * - BABYLON.VertexBuffer.UVKind
  58320. * - BABYLON.VertexBuffer.UV2Kind
  58321. * - BABYLON.VertexBuffer.UV3Kind
  58322. * - BABYLON.VertexBuffer.UV4Kind
  58323. * - BABYLON.VertexBuffer.UV5Kind
  58324. * - BABYLON.VertexBuffer.UV6Kind
  58325. * - BABYLON.VertexBuffer.ColorKind
  58326. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58327. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58328. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58329. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58330. *
  58331. * Returns the Mesh.
  58332. */
  58333. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58334. if (this.sourceMesh) {
  58335. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58336. }
  58337. return this.sourceMesh;
  58338. };
  58339. /**
  58340. * Sets the mesh indices.
  58341. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58342. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58343. * This method creates a new index buffer each call.
  58344. * Returns the Mesh.
  58345. */
  58346. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58347. if (totalVertices === void 0) { totalVertices = null; }
  58348. if (this.sourceMesh) {
  58349. this.sourceMesh.setIndices(indices, totalVertices);
  58350. }
  58351. return this.sourceMesh;
  58352. };
  58353. /**
  58354. * Boolean : True if the mesh owns the requested kind of data.
  58355. */
  58356. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58357. return this._sourceMesh.isVerticesDataPresent(kind);
  58358. };
  58359. /**
  58360. * Returns an array of indices (IndicesArray).
  58361. */
  58362. InstancedMesh.prototype.getIndices = function () {
  58363. return this._sourceMesh.getIndices();
  58364. };
  58365. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58366. get: function () {
  58367. return this._sourceMesh._positions;
  58368. },
  58369. enumerable: true,
  58370. configurable: true
  58371. });
  58372. /**
  58373. * Sets a new updated BoundingInfo to the mesh.
  58374. * Returns the mesh.
  58375. */
  58376. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58377. var meshBB = this._sourceMesh.getBoundingInfo();
  58378. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58379. this._updateBoundingInfo();
  58380. return this;
  58381. };
  58382. InstancedMesh.prototype._preActivate = function () {
  58383. if (this._currentLOD) {
  58384. this._currentLOD._preActivate();
  58385. }
  58386. return this;
  58387. };
  58388. InstancedMesh.prototype._activate = function (renderId) {
  58389. if (this._currentLOD) {
  58390. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58391. }
  58392. return this;
  58393. };
  58394. /**
  58395. * Returns the current associated LOD AbstractMesh.
  58396. */
  58397. InstancedMesh.prototype.getLOD = function (camera) {
  58398. if (!camera) {
  58399. return this;
  58400. }
  58401. var boundingInfo = this.getBoundingInfo();
  58402. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58403. if (this._currentLOD === this.sourceMesh) {
  58404. return this;
  58405. }
  58406. return this._currentLOD;
  58407. };
  58408. InstancedMesh.prototype._syncSubMeshes = function () {
  58409. this.releaseSubMeshes();
  58410. if (this._sourceMesh.subMeshes) {
  58411. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58412. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58413. }
  58414. }
  58415. return this;
  58416. };
  58417. InstancedMesh.prototype._generatePointsArray = function () {
  58418. return this._sourceMesh._generatePointsArray();
  58419. };
  58420. /**
  58421. * Creates a new InstancedMesh from the current mesh.
  58422. * - name (string) : the cloned mesh name
  58423. * - newParent (optional Node) : the optional Node to parent the clone to.
  58424. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58425. *
  58426. * Returns the clone.
  58427. */
  58428. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58429. var result = this._sourceMesh.createInstance(name);
  58430. // Deep copy
  58431. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58432. // Bounding info
  58433. this.refreshBoundingInfo();
  58434. // Parent
  58435. if (newParent) {
  58436. result.parent = newParent;
  58437. }
  58438. if (!doNotCloneChildren) {
  58439. // Children
  58440. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58441. var mesh = this.getScene().meshes[index];
  58442. if (mesh.parent === this) {
  58443. mesh.clone(mesh.name, result);
  58444. }
  58445. }
  58446. }
  58447. result.computeWorldMatrix(true);
  58448. return result;
  58449. };
  58450. /**
  58451. * Disposes the InstancedMesh.
  58452. * Returns nothing.
  58453. */
  58454. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58455. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58456. // Remove from mesh
  58457. var index = this._sourceMesh.instances.indexOf(this);
  58458. this._sourceMesh.instances.splice(index, 1);
  58459. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58460. };
  58461. return InstancedMesh;
  58462. }(BABYLON.AbstractMesh));
  58463. BABYLON.InstancedMesh = InstancedMesh;
  58464. })(BABYLON || (BABYLON = {}));
  58465. //# sourceMappingURL=babylon.instancedMesh.js.map
  58466. "use strict";
  58467. var BABYLON;
  58468. (function (BABYLON) {
  58469. var LinesMesh = /** @class */ (function (_super) {
  58470. __extends(LinesMesh, _super);
  58471. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58472. if (scene === void 0) { scene = null; }
  58473. if (parent === void 0) { parent = null; }
  58474. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58475. _this.useVertexColor = useVertexColor;
  58476. _this.useVertexAlpha = useVertexAlpha;
  58477. _this.color = new BABYLON.Color3(1, 1, 1);
  58478. _this.alpha = 1;
  58479. if (source) {
  58480. _this.color = source.color.clone();
  58481. _this.alpha = source.alpha;
  58482. _this.useVertexColor = source.useVertexColor;
  58483. _this.useVertexAlpha = source.useVertexAlpha;
  58484. }
  58485. _this._intersectionThreshold = 0.1;
  58486. var defines = [];
  58487. var options = {
  58488. attributes: [BABYLON.VertexBuffer.PositionKind],
  58489. uniforms: ["world", "viewProjection"],
  58490. needAlphaBlending: true,
  58491. defines: defines
  58492. };
  58493. if (useVertexAlpha === false) {
  58494. options.needAlphaBlending = false;
  58495. }
  58496. if (!useVertexColor) {
  58497. options.uniforms.push("color");
  58498. }
  58499. else {
  58500. options.defines.push("#define VERTEXCOLOR");
  58501. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58502. }
  58503. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58504. return _this;
  58505. }
  58506. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58507. /**
  58508. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58509. * This margin is expressed in world space coordinates, so its value may vary.
  58510. * Default value is 0.1
  58511. * @returns the intersection Threshold value.
  58512. */
  58513. get: function () {
  58514. return this._intersectionThreshold;
  58515. },
  58516. /**
  58517. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58518. * This margin is expressed in world space coordinates, so its value may vary.
  58519. * @param value the new threshold to apply
  58520. */
  58521. set: function (value) {
  58522. if (this._intersectionThreshold === value) {
  58523. return;
  58524. }
  58525. this._intersectionThreshold = value;
  58526. if (this.geometry) {
  58527. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58528. }
  58529. },
  58530. enumerable: true,
  58531. configurable: true
  58532. });
  58533. /**
  58534. * Returns the string "LineMesh"
  58535. */
  58536. LinesMesh.prototype.getClassName = function () {
  58537. return "LinesMesh";
  58538. };
  58539. Object.defineProperty(LinesMesh.prototype, "material", {
  58540. get: function () {
  58541. return this._colorShader;
  58542. },
  58543. set: function (value) {
  58544. // Do nothing
  58545. },
  58546. enumerable: true,
  58547. configurable: true
  58548. });
  58549. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58550. get: function () {
  58551. return false;
  58552. },
  58553. enumerable: true,
  58554. configurable: true
  58555. });
  58556. LinesMesh.prototype.createInstance = function (name) {
  58557. throw new Error("LinesMeshes do not support createInstance.");
  58558. };
  58559. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58560. if (!this._geometry) {
  58561. return this;
  58562. }
  58563. // VBOs
  58564. this._geometry._bind(this._colorShader.getEffect());
  58565. // Color
  58566. if (!this.useVertexColor) {
  58567. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58568. }
  58569. return this;
  58570. };
  58571. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58572. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58573. return this;
  58574. }
  58575. var engine = this.getScene().getEngine();
  58576. // Draw order
  58577. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58578. return this;
  58579. };
  58580. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58581. this._colorShader.dispose();
  58582. _super.prototype.dispose.call(this, doNotRecurse);
  58583. };
  58584. /**
  58585. * Returns a new LineMesh object cloned from the current one.
  58586. */
  58587. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58588. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58589. };
  58590. return LinesMesh;
  58591. }(BABYLON.Mesh));
  58592. BABYLON.LinesMesh = LinesMesh;
  58593. })(BABYLON || (BABYLON = {}));
  58594. //# sourceMappingURL=babylon.linesMesh.js.map
  58595. "use strict";
  58596. var BABYLON;
  58597. (function (BABYLON) {
  58598. var MeshBuilder = /** @class */ (function () {
  58599. function MeshBuilder() {
  58600. }
  58601. MeshBuilder.updateSideOrientation = function (orientation) {
  58602. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  58603. return BABYLON.Mesh.DOUBLESIDE;
  58604. }
  58605. if (orientation === undefined || orientation === null) {
  58606. return BABYLON.Mesh.FRONTSIDE;
  58607. }
  58608. return orientation;
  58609. };
  58610. /**
  58611. * Creates a box mesh.
  58612. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  58613. * The parameter `size` sets the size (float) of each box side (default 1).
  58614. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  58615. * 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).
  58616. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  58617. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58618. * 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).
  58619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58621. */
  58622. MeshBuilder.CreateBox = function (name, options, scene) {
  58623. if (scene === void 0) { scene = null; }
  58624. var box = new BABYLON.Mesh(name, scene);
  58625. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58626. box._originalBuilderSideOrientation = options.sideOrientation;
  58627. var vertexData = BABYLON.VertexData.CreateBox(options);
  58628. vertexData.applyToMesh(box, options.updatable);
  58629. return box;
  58630. };
  58631. /**
  58632. * Creates a sphere mesh.
  58633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  58634. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  58635. * 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`).
  58636. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  58637. * 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
  58638. * 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).
  58639. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58640. * 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).
  58641. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58643. */
  58644. MeshBuilder.CreateSphere = function (name, options, scene) {
  58645. var sphere = new BABYLON.Mesh(name, scene);
  58646. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58647. sphere._originalBuilderSideOrientation = options.sideOrientation;
  58648. var vertexData = BABYLON.VertexData.CreateSphere(options);
  58649. vertexData.applyToMesh(sphere, options.updatable);
  58650. return sphere;
  58651. };
  58652. /**
  58653. * Creates a plane polygonal mesh. By default, this is a disc.
  58654. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  58655. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  58656. * 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.
  58657. * 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
  58658. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58659. * 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).
  58660. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58662. */
  58663. MeshBuilder.CreateDisc = function (name, options, scene) {
  58664. if (scene === void 0) { scene = null; }
  58665. var disc = new BABYLON.Mesh(name, scene);
  58666. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58667. disc._originalBuilderSideOrientation = options.sideOrientation;
  58668. var vertexData = BABYLON.VertexData.CreateDisc(options);
  58669. vertexData.applyToMesh(disc, options.updatable);
  58670. return disc;
  58671. };
  58672. /**
  58673. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  58674. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  58675. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  58676. * 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`).
  58677. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  58678. * 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.
  58679. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58680. * 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).
  58681. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58682. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58683. */
  58684. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  58685. var sphere = new BABYLON.Mesh(name, scene);
  58686. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58687. sphere._originalBuilderSideOrientation = options.sideOrientation;
  58688. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  58689. vertexData.applyToMesh(sphere, options.updatable);
  58690. return sphere;
  58691. };
  58692. ;
  58693. /**
  58694. * Creates a ribbon mesh.
  58695. * 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.
  58696. *
  58697. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  58698. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  58699. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  58700. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  58701. * 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.
  58702. * 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.
  58703. * 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
  58704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58705. * 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).
  58706. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58707. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  58708. * 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.
  58709. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  58710. * 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
  58711. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  58712. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  58713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58714. */
  58715. MeshBuilder.CreateRibbon = function (name, options, scene) {
  58716. if (scene === void 0) { scene = null; }
  58717. var pathArray = options.pathArray;
  58718. var closeArray = options.closeArray;
  58719. var closePath = options.closePath;
  58720. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58721. var instance = options.instance;
  58722. var updatable = options.updatable;
  58723. if (instance) {
  58724. // positionFunction : ribbon case
  58725. // only pathArray and sideOrientation parameters are taken into account for positions update
  58726. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  58727. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  58728. var positionFunction = function (positions) {
  58729. var minlg = pathArray[0].length;
  58730. var i = 0;
  58731. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  58732. for (var si = 1; si <= ns; si++) {
  58733. for (var p = 0; p < pathArray.length; p++) {
  58734. var path = pathArray[p];
  58735. var l = path.length;
  58736. minlg = (minlg < l) ? minlg : l;
  58737. var j = 0;
  58738. while (j < minlg) {
  58739. positions[i] = path[j].x;
  58740. positions[i + 1] = path[j].y;
  58741. positions[i + 2] = path[j].z;
  58742. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  58743. BABYLON.Tmp.Vector3[0].x = path[j].x;
  58744. }
  58745. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  58746. BABYLON.Tmp.Vector3[1].x = path[j].x;
  58747. }
  58748. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  58749. BABYLON.Tmp.Vector3[0].y = path[j].y;
  58750. }
  58751. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  58752. BABYLON.Tmp.Vector3[1].y = path[j].y;
  58753. }
  58754. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  58755. BABYLON.Tmp.Vector3[0].z = path[j].z;
  58756. }
  58757. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  58758. BABYLON.Tmp.Vector3[1].z = path[j].z;
  58759. }
  58760. j++;
  58761. i += 3;
  58762. }
  58763. if (instance._closePath) {
  58764. positions[i] = path[0].x;
  58765. positions[i + 1] = path[0].y;
  58766. positions[i + 2] = path[0].z;
  58767. i += 3;
  58768. }
  58769. }
  58770. }
  58771. };
  58772. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58773. positionFunction(positions);
  58774. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  58775. instance._boundingInfo.update(instance._worldMatrix);
  58776. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  58777. if (options.colors) {
  58778. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58779. for (var c = 0; c < options.colors.length; c++) {
  58780. colors[c * 4] = options.colors[c].r;
  58781. colors[c * 4 + 1] = options.colors[c].g;
  58782. colors[c * 4 + 2] = options.colors[c].b;
  58783. colors[c * 4 + 3] = options.colors[c].a;
  58784. }
  58785. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  58786. }
  58787. if (options.uvs) {
  58788. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58789. for (var i = 0; i < options.uvs.length; i++) {
  58790. uvs[i * 2] = options.uvs[i].x;
  58791. uvs[i * 2 + 1] = options.uvs[i].y;
  58792. }
  58793. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  58794. }
  58795. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  58796. var indices = instance.getIndices();
  58797. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58798. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  58799. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  58800. if (instance._closePath) {
  58801. var indexFirst = 0;
  58802. var indexLast = 0;
  58803. for (var p = 0; p < pathArray.length; p++) {
  58804. indexFirst = instance._idx[p] * 3;
  58805. if (p + 1 < pathArray.length) {
  58806. indexLast = (instance._idx[p + 1] - 1) * 3;
  58807. }
  58808. else {
  58809. indexLast = normals.length - 3;
  58810. }
  58811. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  58812. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  58813. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  58814. normals[indexLast] = normals[indexFirst];
  58815. normals[indexLast + 1] = normals[indexFirst + 1];
  58816. normals[indexLast + 2] = normals[indexFirst + 2];
  58817. }
  58818. }
  58819. if (!(instance.areNormalsFrozen)) {
  58820. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  58821. }
  58822. }
  58823. return instance;
  58824. }
  58825. else {
  58826. var ribbon = new BABYLON.Mesh(name, scene);
  58827. ribbon._originalBuilderSideOrientation = sideOrientation;
  58828. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  58829. if (closePath) {
  58830. ribbon._idx = vertexData._idx;
  58831. }
  58832. ribbon._closePath = closePath;
  58833. ribbon._closeArray = closeArray;
  58834. vertexData.applyToMesh(ribbon, updatable);
  58835. return ribbon;
  58836. }
  58837. };
  58838. /**
  58839. * Creates a cylinder or a cone mesh.
  58840. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  58841. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  58842. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  58843. * 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.
  58844. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  58845. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  58846. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  58847. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  58848. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  58849. * 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).
  58850. * 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
  58851. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  58852. * 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
  58853. * 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.
  58854. * If `enclose` is false, a ring surface is one element.
  58855. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  58856. * 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
  58857. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58858. * 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).
  58859. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58860. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58861. */
  58862. MeshBuilder.CreateCylinder = function (name, options, scene) {
  58863. var cylinder = new BABYLON.Mesh(name, scene);
  58864. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58865. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  58866. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  58867. vertexData.applyToMesh(cylinder, options.updatable);
  58868. return cylinder;
  58869. };
  58870. /**
  58871. * Creates a torus mesh.
  58872. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  58873. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  58874. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  58875. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  58876. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58877. * 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).
  58878. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58879. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58880. */
  58881. MeshBuilder.CreateTorus = function (name, options, scene) {
  58882. var torus = new BABYLON.Mesh(name, scene);
  58883. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58884. torus._originalBuilderSideOrientation = options.sideOrientation;
  58885. var vertexData = BABYLON.VertexData.CreateTorus(options);
  58886. vertexData.applyToMesh(torus, options.updatable);
  58887. return torus;
  58888. };
  58889. /**
  58890. * Creates a torus knot mesh.
  58891. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  58892. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  58893. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  58894. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  58895. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  58896. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58897. * 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).
  58898. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58899. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58900. */
  58901. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  58902. var torusKnot = new BABYLON.Mesh(name, scene);
  58903. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58904. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  58905. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  58906. vertexData.applyToMesh(torusKnot, options.updatable);
  58907. return torusKnot;
  58908. };
  58909. /**
  58910. * Creates a line system mesh.
  58911. * A line system is a pool of many lines gathered in a single mesh.
  58912. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  58913. * 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.
  58914. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  58915. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  58916. * 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
  58917. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  58918. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  58919. * 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
  58920. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  58921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58922. */
  58923. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  58924. var instance = options.instance;
  58925. var lines = options.lines;
  58926. var colors = options.colors;
  58927. if (instance) {
  58928. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58929. var vertexColor;
  58930. var lineColors;
  58931. if (colors) {
  58932. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58933. }
  58934. var i = 0;
  58935. var c = 0;
  58936. for (var l = 0; l < lines.length; l++) {
  58937. var points = lines[l];
  58938. for (var p = 0; p < points.length; p++) {
  58939. positions[i] = points[p].x;
  58940. positions[i + 1] = points[p].y;
  58941. positions[i + 2] = points[p].z;
  58942. if (colors && vertexColor) {
  58943. lineColors = colors[l];
  58944. vertexColor[c] = lineColors[p].r;
  58945. vertexColor[c + 1] = lineColors[p].g;
  58946. vertexColor[c + 2] = lineColors[p].b;
  58947. vertexColor[c + 3] = lineColors[p].a;
  58948. c += 4;
  58949. }
  58950. i += 3;
  58951. }
  58952. }
  58953. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  58954. if (colors && vertexColor) {
  58955. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  58956. }
  58957. return instance;
  58958. }
  58959. // line system creation
  58960. var useVertexColor = (colors) ? true : false;
  58961. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  58962. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  58963. vertexData.applyToMesh(lineSystem, options.updatable);
  58964. return lineSystem;
  58965. };
  58966. /**
  58967. * Creates a line mesh.
  58968. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  58969. * 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.
  58970. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  58971. * The parameter `points` is an array successive Vector3.
  58972. * 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
  58973. * The optional parameter `colors` is an array of successive Color4, one per line point.
  58974. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  58975. * When updating an instance, remember that only point positions can change, not the number of points.
  58976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58977. */
  58978. MeshBuilder.CreateLines = function (name, options, scene) {
  58979. if (scene === void 0) { scene = null; }
  58980. var colors = (options.colors) ? [options.colors] : null;
  58981. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  58982. return lines;
  58983. };
  58984. /**
  58985. * Creates a dashed line mesh.
  58986. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  58987. * 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.
  58988. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  58989. * The parameter `points` is an array successive Vector3.
  58990. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  58991. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  58992. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  58993. * 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
  58994. * When updating an instance, remember that only point positions can change, not the number of points.
  58995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58996. */
  58997. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  58998. if (scene === void 0) { scene = null; }
  58999. var points = options.points;
  59000. var instance = options.instance;
  59001. var gapSize = options.gapSize || 1;
  59002. var dashSize = options.dashSize || 3;
  59003. if (instance) {
  59004. var positionFunction = function (positions) {
  59005. var curvect = BABYLON.Vector3.Zero();
  59006. var nbSeg = positions.length / 6;
  59007. var lg = 0;
  59008. var nb = 0;
  59009. var shft = 0;
  59010. var dashshft = 0;
  59011. var curshft = 0;
  59012. var p = 0;
  59013. var i = 0;
  59014. var j = 0;
  59015. for (i = 0; i < points.length - 1; i++) {
  59016. points[i + 1].subtractToRef(points[i], curvect);
  59017. lg += curvect.length();
  59018. }
  59019. shft = lg / nbSeg;
  59020. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59021. for (i = 0; i < points.length - 1; i++) {
  59022. points[i + 1].subtractToRef(points[i], curvect);
  59023. nb = Math.floor(curvect.length() / shft);
  59024. curvect.normalize();
  59025. j = 0;
  59026. while (j < nb && p < positions.length) {
  59027. curshft = shft * j;
  59028. positions[p] = points[i].x + curshft * curvect.x;
  59029. positions[p + 1] = points[i].y + curshft * curvect.y;
  59030. positions[p + 2] = points[i].z + curshft * curvect.z;
  59031. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59032. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59033. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59034. p += 6;
  59035. j++;
  59036. }
  59037. }
  59038. while (p < positions.length) {
  59039. positions[p] = points[i].x;
  59040. positions[p + 1] = points[i].y;
  59041. positions[p + 2] = points[i].z;
  59042. p += 3;
  59043. }
  59044. };
  59045. instance.updateMeshPositions(positionFunction, false);
  59046. return instance;
  59047. }
  59048. // dashed lines creation
  59049. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59050. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59051. vertexData.applyToMesh(dashedLines, options.updatable);
  59052. dashedLines.dashSize = dashSize;
  59053. dashedLines.gapSize = gapSize;
  59054. return dashedLines;
  59055. };
  59056. /**
  59057. * Creates an extruded shape mesh.
  59058. * 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.
  59059. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  59060. *
  59061. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59062. * 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
  59063. * extruded along the Z axis.
  59064. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59065. * 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.
  59066. * The parameter `scale` (float, default 1) is the value to scale the shape.
  59067. * 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
  59068. * 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
  59069. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59071. * 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).
  59072. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59073. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59075. */
  59076. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  59077. if (scene === void 0) { scene = null; }
  59078. var path = options.path;
  59079. var shape = options.shape;
  59080. var scale = options.scale || 1;
  59081. var rotation = options.rotation || 0;
  59082. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59083. var updatable = options.updatable;
  59084. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59085. var instance = options.instance || null;
  59086. var invertUV = options.invertUV || false;
  59087. 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);
  59088. };
  59089. /**
  59090. * Creates an custom extruded shape mesh.
  59091. * 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.
  59092. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  59093. *
  59094. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59095. * 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
  59096. * extruded along the Z axis.
  59097. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59098. * 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
  59099. * and the distance of this point from the begining of the path :
  59100. * ```javascript
  59101. * var rotationFunction = function(i, distance) {
  59102. * // do things
  59103. * return rotationValue; }
  59104. * ```
  59105. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  59106. * 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
  59107. * and the distance of this point from the begining of the path :
  59108. * ```javascript
  59109. * var scaleFunction = function(i, distance) {
  59110. * // do things
  59111. * return scaleValue;}
  59112. * ```
  59113. * It must returns a float value that will be the scale value applied to the shape on each path point.
  59114. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  59115. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  59116. * 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
  59117. * 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
  59118. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59119. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59120. * 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).
  59121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59122. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59123. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59124. */
  59125. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  59126. var path = options.path;
  59127. var shape = options.shape;
  59128. var scaleFunction = options.scaleFunction || (function () { return 1; });
  59129. var rotationFunction = options.rotationFunction || (function () { return 0; });
  59130. var ribbonCloseArray = options.ribbonCloseArray || false;
  59131. var ribbonClosePath = options.ribbonClosePath || false;
  59132. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59133. var updatable = options.updatable;
  59134. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59135. var instance = options.instance;
  59136. var invertUV = options.invertUV || false;
  59137. 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);
  59138. };
  59139. /**
  59140. * Creates lathe mesh.
  59141. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  59142. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  59143. *
  59144. * 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
  59145. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  59146. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  59147. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  59148. * 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.
  59149. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  59150. * 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
  59151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59152. * 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).
  59153. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59154. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59156. */
  59157. MeshBuilder.CreateLathe = function (name, options, scene) {
  59158. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  59159. var closed = (options.closed === undefined) ? true : options.closed;
  59160. var shape = options.shape;
  59161. var radius = options.radius || 1;
  59162. var tessellation = options.tessellation || 64;
  59163. var updatable = options.updatable;
  59164. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59165. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59166. var pi2 = Math.PI * 2;
  59167. var paths = new Array();
  59168. var invertUV = options.invertUV || false;
  59169. var i = 0;
  59170. var p = 0;
  59171. var step = pi2 / tessellation * arc;
  59172. var rotated;
  59173. var path = new Array();
  59174. ;
  59175. for (i = 0; i <= tessellation; i++) {
  59176. var path = [];
  59177. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  59178. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  59179. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  59180. }
  59181. for (p = 0; p < shape.length; p++) {
  59182. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  59183. path.push(rotated);
  59184. }
  59185. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  59186. 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));
  59187. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  59188. }
  59189. paths.push(path);
  59190. }
  59191. // lathe ribbon
  59192. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59193. return lathe;
  59194. };
  59195. /**
  59196. * Creates a plane mesh.
  59197. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59198. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  59199. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  59200. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  59201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59202. * 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).
  59203. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59204. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59205. */
  59206. MeshBuilder.CreatePlane = function (name, options, scene) {
  59207. var plane = new BABYLON.Mesh(name, scene);
  59208. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59209. plane._originalBuilderSideOrientation = options.sideOrientation;
  59210. var vertexData = BABYLON.VertexData.CreatePlane(options);
  59211. vertexData.applyToMesh(plane, options.updatable);
  59212. if (options.sourcePlane) {
  59213. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  59214. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  59215. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  59216. plane.rotate(vectorProduct, product);
  59217. }
  59218. return plane;
  59219. };
  59220. /**
  59221. * Creates a ground mesh.
  59222. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59223. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  59224. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  59225. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59226. */
  59227. MeshBuilder.CreateGround = function (name, options, scene) {
  59228. var ground = new BABYLON.GroundMesh(name, scene);
  59229. ground._setReady(false);
  59230. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  59231. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  59232. ground._width = options.width || 1;
  59233. ground._height = options.height || 1;
  59234. ground._maxX = ground._width / 2;
  59235. ground._maxZ = ground._height / 2;
  59236. ground._minX = -ground._maxX;
  59237. ground._minZ = -ground._maxZ;
  59238. var vertexData = BABYLON.VertexData.CreateGround(options);
  59239. vertexData.applyToMesh(ground, options.updatable);
  59240. ground._setReady(true);
  59241. return ground;
  59242. };
  59243. /**
  59244. * Creates a tiled ground mesh.
  59245. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  59246. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  59247. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  59248. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  59249. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  59250. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  59251. * numbers of subdivisions on the ground width and height of each tile.
  59252. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59253. */
  59254. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  59255. var tiledGround = new BABYLON.Mesh(name, scene);
  59256. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  59257. vertexData.applyToMesh(tiledGround, options.updatable);
  59258. return tiledGround;
  59259. };
  59260. /**
  59261. * Creates a ground mesh from a height map.
  59262. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  59263. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  59264. * The parameter `url` sets the URL of the height map image resource.
  59265. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  59266. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  59267. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  59268. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  59269. * 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.
  59270. * 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).
  59271. * This function is passed the newly built mesh :
  59272. * ```javascript
  59273. * function(mesh) { // do things
  59274. * return; }
  59275. * ```
  59276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59277. */
  59278. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  59279. var width = options.width || 10.0;
  59280. var height = options.height || 10.0;
  59281. var subdivisions = options.subdivisions || 1 | 0;
  59282. var minHeight = options.minHeight || 0.0;
  59283. var maxHeight = options.maxHeight || 1.0;
  59284. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  59285. var updatable = options.updatable;
  59286. var onReady = options.onReady;
  59287. var ground = new BABYLON.GroundMesh(name, scene);
  59288. ground._subdivisionsX = subdivisions;
  59289. ground._subdivisionsY = subdivisions;
  59290. ground._width = width;
  59291. ground._height = height;
  59292. ground._maxX = ground._width / 2.0;
  59293. ground._maxZ = ground._height / 2.0;
  59294. ground._minX = -ground._maxX;
  59295. ground._minZ = -ground._maxZ;
  59296. ground._setReady(false);
  59297. var onload = function (img) {
  59298. // Getting height map data
  59299. var canvas = document.createElement("canvas");
  59300. var context = canvas.getContext("2d");
  59301. if (!context) {
  59302. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  59303. }
  59304. if (scene.isDisposed) {
  59305. return;
  59306. }
  59307. var bufferWidth = img.width;
  59308. var bufferHeight = img.height;
  59309. canvas.width = bufferWidth;
  59310. canvas.height = bufferHeight;
  59311. context.drawImage(img, 0, 0);
  59312. // Create VertexData from map data
  59313. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  59314. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  59315. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  59316. width: width, height: height,
  59317. subdivisions: subdivisions,
  59318. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  59319. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  59320. });
  59321. vertexData.applyToMesh(ground, updatable);
  59322. //execute ready callback, if set
  59323. if (onReady) {
  59324. onReady(ground);
  59325. }
  59326. ground._setReady(true);
  59327. };
  59328. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  59329. return ground;
  59330. };
  59331. /**
  59332. * Creates a polygon mesh.
  59333. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  59334. * 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.
  59335. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59336. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59337. * 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).
  59338. * Remember you can only change the shape positions, not their number when updating a polygon.
  59339. */
  59340. MeshBuilder.CreatePolygon = function (name, options, scene) {
  59341. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59342. var shape = options.shape;
  59343. var holes = options.holes || [];
  59344. var depth = options.depth || 0;
  59345. var contours = [];
  59346. var hole = [];
  59347. for (var i = 0; i < shape.length; i++) {
  59348. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  59349. }
  59350. var epsilon = 0.00000001;
  59351. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  59352. contours.pop();
  59353. }
  59354. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  59355. for (var hNb = 0; hNb < holes.length; hNb++) {
  59356. hole = [];
  59357. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  59358. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  59359. }
  59360. polygonTriangulation.addHole(hole);
  59361. }
  59362. var polygon = polygonTriangulation.build(options.updatable, depth);
  59363. polygon._originalBuilderSideOrientation = options.sideOrientation;
  59364. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  59365. vertexData.applyToMesh(polygon, options.updatable);
  59366. return polygon;
  59367. };
  59368. ;
  59369. /**
  59370. * Creates an extruded polygon mesh, with depth in the Y direction.
  59371. * 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).
  59372. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59373. */
  59374. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  59375. return MeshBuilder.CreatePolygon(name, options, scene);
  59376. };
  59377. ;
  59378. /**
  59379. * Creates a tube mesh.
  59380. * 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.
  59381. *
  59382. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  59383. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  59384. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  59385. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  59386. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  59387. * 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.
  59388. * It must return a radius value (positive float) :
  59389. * ```javascript
  59390. * var radiusFunction = function(i, distance) {
  59391. * // do things
  59392. * return radius; }
  59393. * ```
  59394. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  59395. * 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
  59396. * 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
  59397. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59398. * 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).
  59399. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59400. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59401. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59402. */
  59403. MeshBuilder.CreateTube = function (name, options, scene) {
  59404. var path = options.path;
  59405. var instance = options.instance;
  59406. var radius = 1.0;
  59407. if (instance) {
  59408. radius = instance.radius;
  59409. }
  59410. if (options.radius !== undefined) {
  59411. radius = options.radius;
  59412. }
  59413. ;
  59414. var tessellation = options.tessellation || 64 | 0;
  59415. var radiusFunction = options.radiusFunction || null;
  59416. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59417. var invertUV = options.invertUV || false;
  59418. var updatable = options.updatable;
  59419. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59420. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  59421. // tube geometry
  59422. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  59423. var tangents = path3D.getTangents();
  59424. var normals = path3D.getNormals();
  59425. var distances = path3D.getDistances();
  59426. var pi2 = Math.PI * 2;
  59427. var step = pi2 / tessellation * arc;
  59428. var returnRadius = function () { return radius; };
  59429. var radiusFunctionFinal = radiusFunction || returnRadius;
  59430. var circlePath;
  59431. var rad;
  59432. var normal;
  59433. var rotated;
  59434. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  59435. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  59436. for (var i = 0; i < path.length; i++) {
  59437. rad = radiusFunctionFinal(i, distances[i]); // current radius
  59438. circlePath = Array(); // current circle array
  59439. normal = normals[i]; // current normal
  59440. for (var t = 0; t < tessellation; t++) {
  59441. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  59442. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  59443. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  59444. rotated.scaleInPlace(rad).addInPlace(path[i]);
  59445. circlePath[t] = rotated;
  59446. }
  59447. circlePaths[index] = circlePath;
  59448. index++;
  59449. }
  59450. // cap
  59451. var capPath = function (nbPoints, pathIndex) {
  59452. var pointCap = Array();
  59453. for (var i = 0; i < nbPoints; i++) {
  59454. pointCap.push(path[pathIndex]);
  59455. }
  59456. return pointCap;
  59457. };
  59458. switch (cap) {
  59459. case BABYLON.Mesh.NO_CAP:
  59460. break;
  59461. case BABYLON.Mesh.CAP_START:
  59462. circlePaths[0] = capPath(tessellation, 0);
  59463. circlePaths[1] = circlePaths[2].slice(0);
  59464. break;
  59465. case BABYLON.Mesh.CAP_END:
  59466. circlePaths[index] = circlePaths[index - 1].slice(0);
  59467. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59468. break;
  59469. case BABYLON.Mesh.CAP_ALL:
  59470. circlePaths[0] = capPath(tessellation, 0);
  59471. circlePaths[1] = circlePaths[2].slice(0);
  59472. circlePaths[index] = circlePaths[index - 1].slice(0);
  59473. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59474. break;
  59475. default:
  59476. break;
  59477. }
  59478. return circlePaths;
  59479. };
  59480. var path3D;
  59481. var pathArray;
  59482. if (instance) {
  59483. var arc = options.arc || instance.arc;
  59484. path3D = (instance.path3D).update(path);
  59485. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  59486. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  59487. instance.path3D = path3D;
  59488. instance.pathArray = pathArray;
  59489. instance.arc = arc;
  59490. instance.radius = radius;
  59491. return instance;
  59492. }
  59493. // tube creation
  59494. path3D = new BABYLON.Path3D(path);
  59495. var newPathArray = new Array();
  59496. cap = (cap < 0 || cap > 3) ? 0 : cap;
  59497. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  59498. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59499. tube.pathArray = pathArray;
  59500. tube.path3D = path3D;
  59501. tube.tessellation = tessellation;
  59502. tube.cap = cap;
  59503. tube.arc = options.arc;
  59504. tube.radius = radius;
  59505. return tube;
  59506. };
  59507. /**
  59508. * Creates a polyhedron mesh.
  59509. *
  59510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  59511. * 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
  59512. * to choose the wanted type.
  59513. * The parameter `size` (positive float, default 1) sets the polygon size.
  59514. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  59515. * 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`.
  59516. * 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
  59517. * 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)`).
  59518. * 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
  59519. * 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.
  59520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59521. * 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).
  59522. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  59523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59524. */
  59525. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  59526. var polyhedron = new BABYLON.Mesh(name, scene);
  59527. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59528. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  59529. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  59530. vertexData.applyToMesh(polyhedron, options.updatable);
  59531. return polyhedron;
  59532. };
  59533. /**
  59534. * Creates a decal mesh.
  59535. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  59536. * 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.
  59537. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  59538. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  59539. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  59540. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  59541. */
  59542. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  59543. var indices = sourceMesh.getIndices();
  59544. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59545. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59546. var position = options.position || BABYLON.Vector3.Zero();
  59547. var normal = options.normal || BABYLON.Vector3.Up();
  59548. var size = options.size || BABYLON.Vector3.One();
  59549. var angle = options.angle || 0;
  59550. // Getting correct rotation
  59551. if (!normal) {
  59552. var target = new BABYLON.Vector3(0, 0, 1);
  59553. var camera = sourceMesh.getScene().activeCamera;
  59554. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  59555. normal = camera.globalPosition.subtract(cameraWorldTarget);
  59556. }
  59557. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  59558. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  59559. var pitch = Math.atan2(normal.y, len);
  59560. // Matrix
  59561. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  59562. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  59563. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  59564. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  59565. var vertexData = new BABYLON.VertexData();
  59566. vertexData.indices = [];
  59567. vertexData.positions = [];
  59568. vertexData.normals = [];
  59569. vertexData.uvs = [];
  59570. var currentVertexDataIndex = 0;
  59571. var extractDecalVector3 = function (indexId) {
  59572. var result = new BABYLON.PositionNormalVertex();
  59573. if (!indices || !positions || !normals) {
  59574. return result;
  59575. }
  59576. var vertexId = indices[indexId];
  59577. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  59578. // Send vector to decal local world
  59579. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  59580. // Get normal
  59581. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  59582. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  59583. return result;
  59584. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  59585. var clip = function (vertices, axis) {
  59586. if (vertices.length === 0) {
  59587. return vertices;
  59588. }
  59589. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  59590. var clipVertices = function (v0, v1) {
  59591. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  59592. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  59593. };
  59594. var result = new Array();
  59595. for (var index = 0; index < vertices.length; index += 3) {
  59596. var v1Out;
  59597. var v2Out;
  59598. var v3Out;
  59599. var total = 0;
  59600. var nV1 = null;
  59601. var nV2 = null;
  59602. var nV3 = null;
  59603. var nV4 = null;
  59604. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  59605. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  59606. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  59607. v1Out = d1 > 0;
  59608. v2Out = d2 > 0;
  59609. v3Out = d3 > 0;
  59610. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  59611. switch (total) {
  59612. case 0:
  59613. result.push(vertices[index]);
  59614. result.push(vertices[index + 1]);
  59615. result.push(vertices[index + 2]);
  59616. break;
  59617. case 1:
  59618. if (v1Out) {
  59619. nV1 = vertices[index + 1];
  59620. nV2 = vertices[index + 2];
  59621. nV3 = clipVertices(vertices[index], nV1);
  59622. nV4 = clipVertices(vertices[index], nV2);
  59623. }
  59624. if (v2Out) {
  59625. nV1 = vertices[index];
  59626. nV2 = vertices[index + 2];
  59627. nV3 = clipVertices(vertices[index + 1], nV1);
  59628. nV4 = clipVertices(vertices[index + 1], nV2);
  59629. result.push(nV3);
  59630. result.push(nV2.clone());
  59631. result.push(nV1.clone());
  59632. result.push(nV2.clone());
  59633. result.push(nV3.clone());
  59634. result.push(nV4);
  59635. break;
  59636. }
  59637. if (v3Out) {
  59638. nV1 = vertices[index];
  59639. nV2 = vertices[index + 1];
  59640. nV3 = clipVertices(vertices[index + 2], nV1);
  59641. nV4 = clipVertices(vertices[index + 2], nV2);
  59642. }
  59643. if (nV1 && nV2 && nV3 && nV4) {
  59644. result.push(nV1.clone());
  59645. result.push(nV2.clone());
  59646. result.push(nV3);
  59647. result.push(nV4);
  59648. result.push(nV3.clone());
  59649. result.push(nV2.clone());
  59650. }
  59651. break;
  59652. case 2:
  59653. if (!v1Out) {
  59654. nV1 = vertices[index].clone();
  59655. nV2 = clipVertices(nV1, vertices[index + 1]);
  59656. nV3 = clipVertices(nV1, vertices[index + 2]);
  59657. result.push(nV1);
  59658. result.push(nV2);
  59659. result.push(nV3);
  59660. }
  59661. if (!v2Out) {
  59662. nV1 = vertices[index + 1].clone();
  59663. nV2 = clipVertices(nV1, vertices[index + 2]);
  59664. nV3 = clipVertices(nV1, vertices[index]);
  59665. result.push(nV1);
  59666. result.push(nV2);
  59667. result.push(nV3);
  59668. }
  59669. if (!v3Out) {
  59670. nV1 = vertices[index + 2].clone();
  59671. nV2 = clipVertices(nV1, vertices[index]);
  59672. nV3 = clipVertices(nV1, vertices[index + 1]);
  59673. result.push(nV1);
  59674. result.push(nV2);
  59675. result.push(nV3);
  59676. }
  59677. break;
  59678. case 3:
  59679. break;
  59680. }
  59681. }
  59682. return result;
  59683. };
  59684. for (var index = 0; index < indices.length; index += 3) {
  59685. var faceVertices = new Array();
  59686. faceVertices.push(extractDecalVector3(index));
  59687. faceVertices.push(extractDecalVector3(index + 1));
  59688. faceVertices.push(extractDecalVector3(index + 2));
  59689. // Clip
  59690. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  59691. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  59692. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  59693. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  59694. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  59695. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  59696. if (faceVertices.length === 0) {
  59697. continue;
  59698. }
  59699. // Add UVs and get back to world
  59700. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  59701. var vertex = faceVertices[vIndex];
  59702. //TODO check for Int32Array | Uint32Array | Uint16Array
  59703. vertexData.indices.push(currentVertexDataIndex);
  59704. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  59705. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  59706. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  59707. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  59708. currentVertexDataIndex++;
  59709. }
  59710. }
  59711. // Return mesh
  59712. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  59713. vertexData.applyToMesh(decal);
  59714. decal.position = position.clone();
  59715. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  59716. return decal;
  59717. };
  59718. // Privates
  59719. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  59720. // extrusion geometry
  59721. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  59722. var tangents = path3D.getTangents();
  59723. var normals = path3D.getNormals();
  59724. var binormals = path3D.getBinormals();
  59725. var distances = path3D.getDistances();
  59726. var angle = 0;
  59727. var returnScale = function () { return scale !== null ? scale : 1; };
  59728. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  59729. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  59730. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  59731. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  59732. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  59733. for (var i = 0; i < curve.length; i++) {
  59734. var shapePath = new Array();
  59735. var angleStep = rotate(i, distances[i]);
  59736. var scaleRatio = scl(i, distances[i]);
  59737. for (var p = 0; p < shape.length; p++) {
  59738. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  59739. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  59740. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  59741. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  59742. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  59743. shapePath[p] = rotated;
  59744. }
  59745. shapePaths[index] = shapePath;
  59746. angle += angleStep;
  59747. index++;
  59748. }
  59749. // cap
  59750. var capPath = function (shapePath) {
  59751. var pointCap = Array();
  59752. var barycenter = BABYLON.Vector3.Zero();
  59753. var i;
  59754. for (i = 0; i < shapePath.length; i++) {
  59755. barycenter.addInPlace(shapePath[i]);
  59756. }
  59757. barycenter.scaleInPlace(1.0 / shapePath.length);
  59758. for (i = 0; i < shapePath.length; i++) {
  59759. pointCap.push(barycenter);
  59760. }
  59761. return pointCap;
  59762. };
  59763. switch (cap) {
  59764. case BABYLON.Mesh.NO_CAP:
  59765. break;
  59766. case BABYLON.Mesh.CAP_START:
  59767. shapePaths[0] = capPath(shapePaths[2]);
  59768. shapePaths[1] = shapePaths[2];
  59769. break;
  59770. case BABYLON.Mesh.CAP_END:
  59771. shapePaths[index] = shapePaths[index - 1];
  59772. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  59773. break;
  59774. case BABYLON.Mesh.CAP_ALL:
  59775. shapePaths[0] = capPath(shapePaths[2]);
  59776. shapePaths[1] = shapePaths[2];
  59777. shapePaths[index] = shapePaths[index - 1];
  59778. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  59779. break;
  59780. default:
  59781. break;
  59782. }
  59783. return shapePaths;
  59784. };
  59785. var path3D;
  59786. var pathArray;
  59787. if (instance) {
  59788. path3D = (instance.path3D).update(curve);
  59789. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  59790. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  59791. return instance;
  59792. }
  59793. // extruded shape creation
  59794. path3D = new BABYLON.Path3D(curve);
  59795. var newShapePaths = new Array();
  59796. cap = (cap < 0 || cap > 3) ? 0 : cap;
  59797. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  59798. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  59799. extrudedGeneric.pathArray = pathArray;
  59800. extrudedGeneric.path3D = path3D;
  59801. extrudedGeneric.cap = cap;
  59802. return extrudedGeneric;
  59803. };
  59804. return MeshBuilder;
  59805. }());
  59806. BABYLON.MeshBuilder = MeshBuilder;
  59807. })(BABYLON || (BABYLON = {}));
  59808. //# sourceMappingURL=babylon.meshBuilder.js.map
  59809. "use strict";
  59810. var BABYLON;
  59811. (function (BABYLON) {
  59812. /**
  59813. * Draco compression (https://google.github.io/draco/)
  59814. */
  59815. var DracoCompression = /** @class */ (function () {
  59816. /**
  59817. * Constructor
  59818. * @param numWorkers The number of workers for async operations
  59819. */
  59820. function DracoCompression(numWorkers) {
  59821. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  59822. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  59823. if (!workerBlobUrl || !Worker) {
  59824. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  59825. return;
  59826. }
  59827. var workers = new Array(numWorkers);
  59828. for (var i = 0; i < workers.length; i++) {
  59829. var worker = new Worker(workerBlobUrl);
  59830. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  59831. workers[i] = worker;
  59832. }
  59833. this._workerPool = new BABYLON.WorkerPool(workers);
  59834. }
  59835. /**
  59836. * Stop all async operations and release resources.
  59837. */
  59838. DracoCompression.prototype.dispose = function () {
  59839. this._workerPool.dispose();
  59840. delete this._workerPool;
  59841. };
  59842. /**
  59843. * Decode Draco compressed mesh data to vertex data.
  59844. * @param data The array buffer view for the Draco compression data
  59845. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  59846. * @returns A promise that resolves with the decoded vertex data
  59847. */
  59848. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  59849. var _this = this;
  59850. return new Promise(function (resolve, reject) {
  59851. _this._workerPool.push(function (worker, onComplete) {
  59852. var vertexData = new BABYLON.VertexData();
  59853. var onError = function (error) {
  59854. worker.removeEventListener("error", onError);
  59855. worker.removeEventListener("message", onMessage);
  59856. reject(error);
  59857. onComplete();
  59858. };
  59859. var onMessage = function (message) {
  59860. if (message.data === "done") {
  59861. worker.removeEventListener("error", onError);
  59862. worker.removeEventListener("message", onMessage);
  59863. resolve(vertexData);
  59864. onComplete();
  59865. }
  59866. else if (message.data.id === "indices") {
  59867. vertexData.indices = message.data.value;
  59868. }
  59869. else {
  59870. vertexData.set(message.data.value, message.data.id);
  59871. }
  59872. };
  59873. worker.addEventListener("error", onError);
  59874. worker.addEventListener("message", onMessage);
  59875. var dataCopy = new Uint8Array(data.byteLength);
  59876. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  59877. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  59878. });
  59879. });
  59880. };
  59881. /**
  59882. * The worker function that gets converted to a blob url to pass into a worker.
  59883. */
  59884. DracoCompression._Worker = function () {
  59885. // self is actually a DedicatedWorkerGlobalScope
  59886. var _self = self;
  59887. var decodeMesh = function (data, attributes) {
  59888. var dracoModule = new DracoDecoderModule();
  59889. var buffer = new dracoModule.DecoderBuffer();
  59890. buffer.Init(data, data.byteLength);
  59891. var decoder = new dracoModule.Decoder();
  59892. var geometry;
  59893. var status;
  59894. try {
  59895. var type = decoder.GetEncodedGeometryType(buffer);
  59896. switch (type) {
  59897. case dracoModule.TRIANGULAR_MESH:
  59898. geometry = new dracoModule.Mesh();
  59899. status = decoder.DecodeBufferToMesh(buffer, geometry);
  59900. break;
  59901. case dracoModule.POINT_CLOUD:
  59902. geometry = new dracoModule.PointCloud();
  59903. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  59904. break;
  59905. default:
  59906. throw new Error("Invalid geometry type " + type);
  59907. }
  59908. if (!status.ok() || !geometry.ptr) {
  59909. throw new Error(status.error_msg());
  59910. }
  59911. var numPoints = geometry.num_points();
  59912. if (type === dracoModule.TRIANGULAR_MESH) {
  59913. var numFaces = geometry.num_faces();
  59914. var faceIndices = new dracoModule.DracoInt32Array();
  59915. try {
  59916. var indices = new Uint32Array(numFaces * 3);
  59917. for (var i = 0; i < numFaces; i++) {
  59918. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  59919. var offset = i * 3;
  59920. indices[offset + 0] = faceIndices.GetValue(0);
  59921. indices[offset + 1] = faceIndices.GetValue(1);
  59922. indices[offset + 2] = faceIndices.GetValue(2);
  59923. }
  59924. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  59925. }
  59926. finally {
  59927. dracoModule.destroy(faceIndices);
  59928. }
  59929. }
  59930. for (var kind in attributes) {
  59931. var uniqueId = attributes[kind];
  59932. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  59933. var dracoData = new dracoModule.DracoFloat32Array();
  59934. try {
  59935. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  59936. var babylonData = new Float32Array(numPoints * attribute.num_components());
  59937. for (var i = 0; i < babylonData.length; i++) {
  59938. babylonData[i] = dracoData.GetValue(i);
  59939. }
  59940. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  59941. }
  59942. finally {
  59943. dracoModule.destroy(dracoData);
  59944. }
  59945. }
  59946. }
  59947. finally {
  59948. if (geometry) {
  59949. dracoModule.destroy(geometry);
  59950. }
  59951. dracoModule.destroy(decoder);
  59952. dracoModule.destroy(buffer);
  59953. }
  59954. _self.postMessage("done");
  59955. };
  59956. _self.onmessage = function (event) {
  59957. switch (event.data.id) {
  59958. case "initDecoder": {
  59959. importScripts(event.data.url);
  59960. break;
  59961. }
  59962. case "decodeMesh": {
  59963. decodeMesh(event.data.data, event.data.attributes);
  59964. break;
  59965. }
  59966. }
  59967. };
  59968. };
  59969. DracoCompression._GetDefaultDecoderUrl = function () {
  59970. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59971. return null;
  59972. }
  59973. for (var i = 0; i < document.scripts.length; i++) {
  59974. if (document.scripts[i].type === "text/x-draco-decoder") {
  59975. return document.scripts[i].src;
  59976. }
  59977. }
  59978. return null;
  59979. };
  59980. /**
  59981. * Gets the url to the draco decoder if available.
  59982. */
  59983. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  59984. return DracoCompression;
  59985. }());
  59986. BABYLON.DracoCompression = DracoCompression;
  59987. })(BABYLON || (BABYLON = {}));
  59988. //# sourceMappingURL=babylon.dracoCompression.js.map
  59989. "use strict";
  59990. var BABYLON;
  59991. (function (BABYLON) {
  59992. var AudioEngine = /** @class */ (function () {
  59993. function AudioEngine() {
  59994. this._audioContext = null;
  59995. this._audioContextInitialized = false;
  59996. this.canUseWebAudio = false;
  59997. this.WarnedWebAudioUnsupported = false;
  59998. this.unlocked = false;
  59999. this.isMP3supported = false;
  60000. this.isOGGsupported = false;
  60001. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60002. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60003. this.canUseWebAudio = true;
  60004. }
  60005. var audioElem = document.createElement('audio');
  60006. try {
  60007. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60008. this.isMP3supported = true;
  60009. }
  60010. }
  60011. catch (e) {
  60012. // protect error during capability check.
  60013. }
  60014. try {
  60015. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60016. this.isOGGsupported = true;
  60017. }
  60018. }
  60019. catch (e) {
  60020. // protect error during capability check.
  60021. }
  60022. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  60023. this._unlockiOSaudio();
  60024. }
  60025. else {
  60026. this.unlocked = true;
  60027. }
  60028. }
  60029. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  60030. get: function () {
  60031. if (!this._audioContextInitialized) {
  60032. this._initializeAudioContext();
  60033. }
  60034. return this._audioContext;
  60035. },
  60036. enumerable: true,
  60037. configurable: true
  60038. });
  60039. AudioEngine.prototype._unlockiOSaudio = function () {
  60040. var _this = this;
  60041. var unlockaudio = function () {
  60042. if (!_this.audioContext) {
  60043. return;
  60044. }
  60045. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  60046. var source = _this.audioContext.createBufferSource();
  60047. source.buffer = buffer;
  60048. source.connect(_this.audioContext.destination);
  60049. source.start(0);
  60050. setTimeout(function () {
  60051. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  60052. _this.unlocked = true;
  60053. window.removeEventListener('touchend', unlockaudio, false);
  60054. if (_this.onAudioUnlocked) {
  60055. _this.onAudioUnlocked();
  60056. }
  60057. }
  60058. }, 0);
  60059. };
  60060. window.addEventListener('touchend', unlockaudio, false);
  60061. };
  60062. AudioEngine.prototype._initializeAudioContext = function () {
  60063. try {
  60064. if (this.canUseWebAudio) {
  60065. this._audioContext = new AudioContext();
  60066. // create a global volume gain node
  60067. this.masterGain = this._audioContext.createGain();
  60068. this.masterGain.gain.value = 1;
  60069. this.masterGain.connect(this._audioContext.destination);
  60070. this._audioContextInitialized = true;
  60071. }
  60072. }
  60073. catch (e) {
  60074. this.canUseWebAudio = false;
  60075. BABYLON.Tools.Error("Web Audio: " + e.message);
  60076. }
  60077. };
  60078. AudioEngine.prototype.dispose = function () {
  60079. if (this.canUseWebAudio && this._audioContextInitialized) {
  60080. if (this._connectedAnalyser && this._audioContext) {
  60081. this._connectedAnalyser.stopDebugCanvas();
  60082. this._connectedAnalyser.dispose();
  60083. this.masterGain.disconnect();
  60084. this.masterGain.connect(this._audioContext.destination);
  60085. this._connectedAnalyser = null;
  60086. }
  60087. this.masterGain.gain.value = 1;
  60088. }
  60089. this.WarnedWebAudioUnsupported = false;
  60090. };
  60091. AudioEngine.prototype.getGlobalVolume = function () {
  60092. if (this.canUseWebAudio && this._audioContextInitialized) {
  60093. return this.masterGain.gain.value;
  60094. }
  60095. else {
  60096. return -1;
  60097. }
  60098. };
  60099. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  60100. if (this.canUseWebAudio && this._audioContextInitialized) {
  60101. this.masterGain.gain.value = newVolume;
  60102. }
  60103. };
  60104. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  60105. if (this._connectedAnalyser) {
  60106. this._connectedAnalyser.stopDebugCanvas();
  60107. }
  60108. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  60109. this._connectedAnalyser = analyser;
  60110. this.masterGain.disconnect();
  60111. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  60112. }
  60113. };
  60114. return AudioEngine;
  60115. }());
  60116. BABYLON.AudioEngine = AudioEngine;
  60117. })(BABYLON || (BABYLON = {}));
  60118. //# sourceMappingURL=babylon.audioEngine.js.map
  60119. "use strict";
  60120. var BABYLON;
  60121. (function (BABYLON) {
  60122. var Sound = /** @class */ (function () {
  60123. /**
  60124. * Create a sound and attach it to a scene
  60125. * @param name Name of your sound
  60126. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  60127. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  60128. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  60129. */
  60130. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  60131. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  60132. var _this = this;
  60133. this.autoplay = false;
  60134. this.loop = false;
  60135. this.useCustomAttenuation = false;
  60136. this.spatialSound = false;
  60137. this.refDistance = 1;
  60138. this.rolloffFactor = 1;
  60139. this.maxDistance = 100;
  60140. this.distanceModel = "linear";
  60141. this._panningModel = "equalpower";
  60142. this._playbackRate = 1;
  60143. this._streaming = false;
  60144. this._startTime = 0;
  60145. this._startOffset = 0;
  60146. this._position = BABYLON.Vector3.Zero();
  60147. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  60148. this._volume = 1;
  60149. this._isReadyToPlay = false;
  60150. this.isPlaying = false;
  60151. this.isPaused = false;
  60152. this._isDirectional = false;
  60153. // Used if you'd like to create a directional sound.
  60154. // If not set, the sound will be omnidirectional
  60155. this._coneInnerAngle = 360;
  60156. this._coneOuterAngle = 360;
  60157. this._coneOuterGain = 0;
  60158. this._isOutputConnected = false;
  60159. this._urlType = "Unknown";
  60160. this.name = name;
  60161. this._scene = scene;
  60162. this._readyToPlayCallback = readyToPlayCallback;
  60163. // Default custom attenuation function is a linear attenuation
  60164. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  60165. if (currentDistance < maxDistance) {
  60166. return currentVolume * (1 - currentDistance / maxDistance);
  60167. }
  60168. else {
  60169. return 0;
  60170. }
  60171. };
  60172. if (options) {
  60173. this.autoplay = options.autoplay || false;
  60174. this.loop = options.loop || false;
  60175. // if volume === 0, we need another way to check this option
  60176. if (options.volume !== undefined) {
  60177. this._volume = options.volume;
  60178. }
  60179. this.spatialSound = options.spatialSound || false;
  60180. this.maxDistance = options.maxDistance || 100;
  60181. this.useCustomAttenuation = options.useCustomAttenuation || false;
  60182. this.rolloffFactor = options.rolloffFactor || 1;
  60183. this.refDistance = options.refDistance || 1;
  60184. this.distanceModel = options.distanceModel || "linear";
  60185. this._playbackRate = options.playbackRate || 1;
  60186. this._streaming = options.streaming || false;
  60187. }
  60188. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60189. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  60190. this._soundGain.gain.value = this._volume;
  60191. this._inputAudioNode = this._soundGain;
  60192. this._ouputAudioNode = this._soundGain;
  60193. if (this.spatialSound) {
  60194. this._createSpatialParameters();
  60195. }
  60196. this._scene.mainSoundTrack.AddSound(this);
  60197. var validParameter = true;
  60198. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  60199. if (urlOrArrayBuffer) {
  60200. try {
  60201. if (typeof (urlOrArrayBuffer) === "string")
  60202. this._urlType = "String";
  60203. if (Array.isArray(urlOrArrayBuffer))
  60204. this._urlType = "Array";
  60205. if (urlOrArrayBuffer instanceof ArrayBuffer)
  60206. this._urlType = "ArrayBuffer";
  60207. var urls = [];
  60208. var codecSupportedFound = false;
  60209. switch (this._urlType) {
  60210. case "ArrayBuffer":
  60211. if (urlOrArrayBuffer.byteLength > 0) {
  60212. codecSupportedFound = true;
  60213. this._soundLoaded(urlOrArrayBuffer);
  60214. }
  60215. break;
  60216. case "String":
  60217. urls.push(urlOrArrayBuffer);
  60218. case "Array":
  60219. if (urls.length === 0)
  60220. urls = urlOrArrayBuffer;
  60221. // If we found a supported format, we load it immediately and stop the loop
  60222. for (var i = 0; i < urls.length; i++) {
  60223. var url = urls[i];
  60224. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  60225. codecSupportedFound = true;
  60226. }
  60227. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  60228. codecSupportedFound = true;
  60229. }
  60230. if (url.indexOf(".wav", url.length - 4) !== -1) {
  60231. codecSupportedFound = true;
  60232. }
  60233. if (url.indexOf("blob:") !== -1) {
  60234. codecSupportedFound = true;
  60235. }
  60236. if (codecSupportedFound) {
  60237. // Loading sound using XHR2
  60238. if (!this._streaming) {
  60239. this._scene._loadFile(url, function (data) {
  60240. _this._soundLoaded(data);
  60241. }, undefined, true, true, function (exception) {
  60242. if (exception) {
  60243. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  60244. }
  60245. BABYLON.Tools.Error("Sound creation aborted.");
  60246. _this._scene.mainSoundTrack.RemoveSound(_this);
  60247. });
  60248. }
  60249. else {
  60250. this._htmlAudioElement = new Audio(url);
  60251. this._htmlAudioElement.controls = false;
  60252. this._htmlAudioElement.loop = this.loop;
  60253. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  60254. this._htmlAudioElement.preload = "auto";
  60255. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  60256. _this._isReadyToPlay = true;
  60257. if (_this.autoplay) {
  60258. _this.play();
  60259. }
  60260. if (_this._readyToPlayCallback) {
  60261. _this._readyToPlayCallback();
  60262. }
  60263. });
  60264. document.body.appendChild(this._htmlAudioElement);
  60265. }
  60266. break;
  60267. }
  60268. }
  60269. break;
  60270. default:
  60271. validParameter = false;
  60272. break;
  60273. }
  60274. if (!validParameter) {
  60275. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  60276. }
  60277. else {
  60278. if (!codecSupportedFound) {
  60279. this._isReadyToPlay = true;
  60280. // Simulating a ready to play event to avoid breaking code path
  60281. if (this._readyToPlayCallback) {
  60282. window.setTimeout(function () {
  60283. if (_this._readyToPlayCallback) {
  60284. _this._readyToPlayCallback();
  60285. }
  60286. }, 1000);
  60287. }
  60288. }
  60289. }
  60290. }
  60291. catch (ex) {
  60292. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  60293. this._scene.mainSoundTrack.RemoveSound(this);
  60294. }
  60295. }
  60296. }
  60297. else {
  60298. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  60299. this._scene.mainSoundTrack.AddSound(this);
  60300. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  60301. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  60302. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  60303. }
  60304. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  60305. if (this._readyToPlayCallback) {
  60306. window.setTimeout(function () {
  60307. if (_this._readyToPlayCallback) {
  60308. _this._readyToPlayCallback();
  60309. }
  60310. }, 1000);
  60311. }
  60312. }
  60313. }
  60314. Sound.prototype.dispose = function () {
  60315. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60316. if (this.isPlaying) {
  60317. this.stop();
  60318. }
  60319. this._isReadyToPlay = false;
  60320. if (this.soundTrackId === -1) {
  60321. this._scene.mainSoundTrack.RemoveSound(this);
  60322. }
  60323. else {
  60324. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  60325. }
  60326. if (this._soundGain) {
  60327. this._soundGain.disconnect();
  60328. this._soundGain = null;
  60329. }
  60330. if (this._soundPanner) {
  60331. this._soundPanner.disconnect();
  60332. this._soundPanner = null;
  60333. }
  60334. if (this._soundSource) {
  60335. this._soundSource.disconnect();
  60336. this._soundSource = null;
  60337. }
  60338. this._audioBuffer = null;
  60339. if (this._htmlAudioElement) {
  60340. this._htmlAudioElement.pause();
  60341. this._htmlAudioElement.src = "";
  60342. document.body.removeChild(this._htmlAudioElement);
  60343. }
  60344. if (this._connectedMesh && this._registerFunc) {
  60345. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60346. this._connectedMesh = null;
  60347. }
  60348. }
  60349. };
  60350. Sound.prototype.isReady = function () {
  60351. return this._isReadyToPlay;
  60352. };
  60353. Sound.prototype._soundLoaded = function (audioData) {
  60354. var _this = this;
  60355. if (!BABYLON.Engine.audioEngine.audioContext) {
  60356. return;
  60357. }
  60358. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  60359. _this._audioBuffer = buffer;
  60360. _this._isReadyToPlay = true;
  60361. if (_this.autoplay) {
  60362. _this.play();
  60363. }
  60364. if (_this._readyToPlayCallback) {
  60365. _this._readyToPlayCallback();
  60366. }
  60367. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  60368. };
  60369. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  60370. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60371. this._audioBuffer = audioBuffer;
  60372. this._isReadyToPlay = true;
  60373. }
  60374. };
  60375. Sound.prototype.updateOptions = function (options) {
  60376. if (options) {
  60377. this.loop = options.loop || this.loop;
  60378. this.maxDistance = options.maxDistance || this.maxDistance;
  60379. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  60380. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  60381. this.refDistance = options.refDistance || this.refDistance;
  60382. this.distanceModel = options.distanceModel || this.distanceModel;
  60383. this._playbackRate = options.playbackRate || this._playbackRate;
  60384. this._updateSpatialParameters();
  60385. if (this.isPlaying) {
  60386. if (this._streaming) {
  60387. this._htmlAudioElement.playbackRate = this._playbackRate;
  60388. }
  60389. else {
  60390. if (this._soundSource) {
  60391. this._soundSource.playbackRate.value = this._playbackRate;
  60392. }
  60393. }
  60394. }
  60395. }
  60396. };
  60397. Sound.prototype._createSpatialParameters = function () {
  60398. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60399. if (this._scene.headphone) {
  60400. this._panningModel = "HRTF";
  60401. }
  60402. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  60403. this._updateSpatialParameters();
  60404. this._soundPanner.connect(this._ouputAudioNode);
  60405. this._inputAudioNode = this._soundPanner;
  60406. }
  60407. };
  60408. Sound.prototype._updateSpatialParameters = function () {
  60409. if (this.spatialSound && this._soundPanner) {
  60410. if (this.useCustomAttenuation) {
  60411. // Tricks to disable in a way embedded Web Audio attenuation
  60412. this._soundPanner.distanceModel = "linear";
  60413. this._soundPanner.maxDistance = Number.MAX_VALUE;
  60414. this._soundPanner.refDistance = 1;
  60415. this._soundPanner.rolloffFactor = 1;
  60416. this._soundPanner.panningModel = this._panningModel;
  60417. }
  60418. else {
  60419. this._soundPanner.distanceModel = this.distanceModel;
  60420. this._soundPanner.maxDistance = this.maxDistance;
  60421. this._soundPanner.refDistance = this.refDistance;
  60422. this._soundPanner.rolloffFactor = this.rolloffFactor;
  60423. this._soundPanner.panningModel = this._panningModel;
  60424. }
  60425. }
  60426. };
  60427. Sound.prototype.switchPanningModelToHRTF = function () {
  60428. this._panningModel = "HRTF";
  60429. this._switchPanningModel();
  60430. };
  60431. Sound.prototype.switchPanningModelToEqualPower = function () {
  60432. this._panningModel = "equalpower";
  60433. this._switchPanningModel();
  60434. };
  60435. Sound.prototype._switchPanningModel = function () {
  60436. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60437. this._soundPanner.panningModel = this._panningModel;
  60438. }
  60439. };
  60440. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  60441. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60442. if (this._isOutputConnected) {
  60443. this._ouputAudioNode.disconnect();
  60444. }
  60445. this._ouputAudioNode.connect(soundTrackAudioNode);
  60446. this._isOutputConnected = true;
  60447. }
  60448. };
  60449. /**
  60450. * Transform this sound into a directional source
  60451. * @param coneInnerAngle Size of the inner cone in degree
  60452. * @param coneOuterAngle Size of the outer cone in degree
  60453. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  60454. */
  60455. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  60456. if (coneOuterAngle < coneInnerAngle) {
  60457. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  60458. return;
  60459. }
  60460. this._coneInnerAngle = coneInnerAngle;
  60461. this._coneOuterAngle = coneOuterAngle;
  60462. this._coneOuterGain = coneOuterGain;
  60463. this._isDirectional = true;
  60464. if (this.isPlaying && this.loop) {
  60465. this.stop();
  60466. this.play();
  60467. }
  60468. };
  60469. Sound.prototype.setPosition = function (newPosition) {
  60470. this._position = newPosition;
  60471. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60472. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60473. }
  60474. };
  60475. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  60476. this._localDirection = newLocalDirection;
  60477. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  60478. this._updateDirection();
  60479. }
  60480. };
  60481. Sound.prototype._updateDirection = function () {
  60482. if (!this._connectedMesh || !this._soundPanner) {
  60483. return;
  60484. }
  60485. var mat = this._connectedMesh.getWorldMatrix();
  60486. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  60487. direction.normalize();
  60488. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  60489. };
  60490. Sound.prototype.updateDistanceFromListener = function () {
  60491. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  60492. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  60493. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  60494. }
  60495. };
  60496. Sound.prototype.setAttenuationFunction = function (callback) {
  60497. this._customAttenuationFunction = callback;
  60498. };
  60499. /**
  60500. * Play the sound
  60501. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  60502. * @param offset (optional) Start the sound setting it at a specific time
  60503. */
  60504. Sound.prototype.play = function (time, offset) {
  60505. var _this = this;
  60506. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  60507. try {
  60508. if (this._startOffset < 0) {
  60509. time = -this._startOffset;
  60510. this._startOffset = 0;
  60511. }
  60512. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  60513. if (!this._soundSource || !this._streamingSource) {
  60514. if (this.spatialSound && this._soundPanner) {
  60515. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60516. if (this._isDirectional) {
  60517. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  60518. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  60519. this._soundPanner.coneOuterGain = this._coneOuterGain;
  60520. if (this._connectedMesh) {
  60521. this._updateDirection();
  60522. }
  60523. else {
  60524. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  60525. }
  60526. }
  60527. }
  60528. }
  60529. if (this._streaming) {
  60530. if (!this._streamingSource) {
  60531. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  60532. this._htmlAudioElement.onended = function () { _this._onended(); };
  60533. this._htmlAudioElement.playbackRate = this._playbackRate;
  60534. }
  60535. this._streamingSource.disconnect();
  60536. this._streamingSource.connect(this._inputAudioNode);
  60537. this._htmlAudioElement.play();
  60538. }
  60539. else {
  60540. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  60541. this._soundSource.buffer = this._audioBuffer;
  60542. this._soundSource.connect(this._inputAudioNode);
  60543. this._soundSource.loop = this.loop;
  60544. this._soundSource.playbackRate.value = this._playbackRate;
  60545. this._soundSource.onended = function () { _this._onended(); };
  60546. if (this._soundSource.buffer) {
  60547. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  60548. }
  60549. }
  60550. this._startTime = startTime;
  60551. this.isPlaying = true;
  60552. this.isPaused = false;
  60553. }
  60554. catch (ex) {
  60555. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  60556. }
  60557. }
  60558. };
  60559. Sound.prototype._onended = function () {
  60560. this.isPlaying = false;
  60561. if (this.onended) {
  60562. this.onended();
  60563. }
  60564. };
  60565. /**
  60566. * Stop the sound
  60567. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  60568. */
  60569. Sound.prototype.stop = function (time) {
  60570. if (this.isPlaying) {
  60571. if (this._streaming) {
  60572. this._htmlAudioElement.pause();
  60573. // Test needed for Firefox or it will generate an Invalid State Error
  60574. if (this._htmlAudioElement.currentTime > 0) {
  60575. this._htmlAudioElement.currentTime = 0;
  60576. }
  60577. }
  60578. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  60579. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  60580. this._soundSource.stop(stopTime);
  60581. this._soundSource.onended = function () { };
  60582. if (!this.isPaused) {
  60583. this._startOffset = 0;
  60584. }
  60585. }
  60586. this.isPlaying = false;
  60587. }
  60588. };
  60589. Sound.prototype.pause = function () {
  60590. if (this.isPlaying) {
  60591. this.isPaused = true;
  60592. if (this._streaming) {
  60593. this._htmlAudioElement.pause();
  60594. }
  60595. else if (BABYLON.Engine.audioEngine.audioContext) {
  60596. this.stop(0);
  60597. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  60598. }
  60599. }
  60600. };
  60601. Sound.prototype.setVolume = function (newVolume, time) {
  60602. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  60603. if (time && BABYLON.Engine.audioEngine.audioContext) {
  60604. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  60605. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  60606. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  60607. }
  60608. else {
  60609. this._soundGain.gain.value = newVolume;
  60610. }
  60611. }
  60612. this._volume = newVolume;
  60613. };
  60614. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  60615. this._playbackRate = newPlaybackRate;
  60616. if (this.isPlaying) {
  60617. if (this._streaming) {
  60618. this._htmlAudioElement.playbackRate = this._playbackRate;
  60619. }
  60620. else if (this._soundSource) {
  60621. this._soundSource.playbackRate.value = this._playbackRate;
  60622. }
  60623. }
  60624. };
  60625. Sound.prototype.getVolume = function () {
  60626. return this._volume;
  60627. };
  60628. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  60629. var _this = this;
  60630. if (this._connectedMesh && this._registerFunc) {
  60631. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60632. this._registerFunc = null;
  60633. }
  60634. this._connectedMesh = meshToConnectTo;
  60635. if (!this.spatialSound) {
  60636. this.spatialSound = true;
  60637. this._createSpatialParameters();
  60638. if (this.isPlaying && this.loop) {
  60639. this.stop();
  60640. this.play();
  60641. }
  60642. }
  60643. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  60644. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  60645. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  60646. };
  60647. Sound.prototype.detachFromMesh = function () {
  60648. if (this._connectedMesh && this._registerFunc) {
  60649. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60650. this._registerFunc = null;
  60651. this._connectedMesh = null;
  60652. }
  60653. };
  60654. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  60655. if (!node.getBoundingInfo) {
  60656. return;
  60657. }
  60658. var mesh = node;
  60659. var boundingInfo = mesh.getBoundingInfo();
  60660. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  60661. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  60662. this._updateDirection();
  60663. }
  60664. };
  60665. Sound.prototype.clone = function () {
  60666. var _this = this;
  60667. if (!this._streaming) {
  60668. var setBufferAndRun = function () {
  60669. if (_this._isReadyToPlay) {
  60670. clonedSound._audioBuffer = _this.getAudioBuffer();
  60671. clonedSound._isReadyToPlay = true;
  60672. if (clonedSound.autoplay) {
  60673. clonedSound.play();
  60674. }
  60675. }
  60676. else {
  60677. window.setTimeout(setBufferAndRun, 300);
  60678. }
  60679. };
  60680. var currentOptions = {
  60681. autoplay: this.autoplay, loop: this.loop,
  60682. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  60683. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  60684. refDistance: this.refDistance, distanceModel: this.distanceModel
  60685. };
  60686. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  60687. if (this.useCustomAttenuation) {
  60688. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  60689. }
  60690. clonedSound.setPosition(this._position);
  60691. clonedSound.setPlaybackRate(this._playbackRate);
  60692. setBufferAndRun();
  60693. return clonedSound;
  60694. }
  60695. else {
  60696. return null;
  60697. }
  60698. };
  60699. Sound.prototype.getAudioBuffer = function () {
  60700. return this._audioBuffer;
  60701. };
  60702. Sound.prototype.serialize = function () {
  60703. var serializationObject = {
  60704. name: this.name,
  60705. url: this.name,
  60706. autoplay: this.autoplay,
  60707. loop: this.loop,
  60708. volume: this._volume,
  60709. spatialSound: this.spatialSound,
  60710. maxDistance: this.maxDistance,
  60711. rolloffFactor: this.rolloffFactor,
  60712. refDistance: this.refDistance,
  60713. distanceModel: this.distanceModel,
  60714. playbackRate: this._playbackRate,
  60715. panningModel: this._panningModel,
  60716. soundTrackId: this.soundTrackId
  60717. };
  60718. if (this.spatialSound) {
  60719. if (this._connectedMesh)
  60720. serializationObject.connectedMeshId = this._connectedMesh.id;
  60721. serializationObject.position = this._position.asArray();
  60722. serializationObject.refDistance = this.refDistance;
  60723. serializationObject.distanceModel = this.distanceModel;
  60724. serializationObject.isDirectional = this._isDirectional;
  60725. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  60726. serializationObject.coneInnerAngle = this._coneInnerAngle;
  60727. serializationObject.coneOuterAngle = this._coneOuterAngle;
  60728. serializationObject.coneOuterGain = this._coneOuterGain;
  60729. }
  60730. return serializationObject;
  60731. };
  60732. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  60733. var soundName = parsedSound.name;
  60734. var soundUrl;
  60735. if (parsedSound.url) {
  60736. soundUrl = rootUrl + parsedSound.url;
  60737. }
  60738. else {
  60739. soundUrl = rootUrl + soundName;
  60740. }
  60741. var options = {
  60742. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  60743. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  60744. rolloffFactor: parsedSound.rolloffFactor,
  60745. refDistance: parsedSound.refDistance,
  60746. distanceModel: parsedSound.distanceModel,
  60747. playbackRate: parsedSound.playbackRate
  60748. };
  60749. var newSound;
  60750. if (!sourceSound) {
  60751. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  60752. scene._addPendingData(newSound);
  60753. }
  60754. else {
  60755. var setBufferAndRun = function () {
  60756. if (sourceSound._isReadyToPlay) {
  60757. newSound._audioBuffer = sourceSound.getAudioBuffer();
  60758. newSound._isReadyToPlay = true;
  60759. if (newSound.autoplay) {
  60760. newSound.play();
  60761. }
  60762. }
  60763. else {
  60764. window.setTimeout(setBufferAndRun, 300);
  60765. }
  60766. };
  60767. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  60768. setBufferAndRun();
  60769. }
  60770. if (parsedSound.position) {
  60771. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  60772. newSound.setPosition(soundPosition);
  60773. }
  60774. if (parsedSound.isDirectional) {
  60775. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  60776. if (parsedSound.localDirectionToMesh) {
  60777. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  60778. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  60779. }
  60780. }
  60781. if (parsedSound.connectedMeshId) {
  60782. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  60783. if (connectedMesh) {
  60784. newSound.attachToMesh(connectedMesh);
  60785. }
  60786. }
  60787. return newSound;
  60788. };
  60789. return Sound;
  60790. }());
  60791. BABYLON.Sound = Sound;
  60792. })(BABYLON || (BABYLON = {}));
  60793. //# sourceMappingURL=babylon.sound.js.map
  60794. "use strict";
  60795. var BABYLON;
  60796. (function (BABYLON) {
  60797. var SoundTrack = /** @class */ (function () {
  60798. function SoundTrack(scene, options) {
  60799. this.id = -1;
  60800. this._isMainTrack = false;
  60801. this._isInitialized = false;
  60802. this._scene = scene;
  60803. this.soundCollection = new Array();
  60804. this._options = options;
  60805. if (!this._isMainTrack) {
  60806. this._scene.soundTracks.push(this);
  60807. this.id = this._scene.soundTracks.length - 1;
  60808. }
  60809. }
  60810. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  60811. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60812. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  60813. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  60814. if (this._options) {
  60815. if (this._options.volume) {
  60816. this._outputAudioNode.gain.value = this._options.volume;
  60817. }
  60818. if (this._options.mainTrack) {
  60819. this._isMainTrack = this._options.mainTrack;
  60820. }
  60821. }
  60822. this._isInitialized = true;
  60823. }
  60824. };
  60825. SoundTrack.prototype.dispose = function () {
  60826. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  60827. if (this._connectedAnalyser) {
  60828. this._connectedAnalyser.stopDebugCanvas();
  60829. }
  60830. while (this.soundCollection.length) {
  60831. this.soundCollection[0].dispose();
  60832. }
  60833. if (this._outputAudioNode) {
  60834. this._outputAudioNode.disconnect();
  60835. }
  60836. this._outputAudioNode = null;
  60837. }
  60838. };
  60839. SoundTrack.prototype.AddSound = function (sound) {
  60840. if (!this._isInitialized) {
  60841. this._initializeSoundTrackAudioGraph();
  60842. }
  60843. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60844. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  60845. }
  60846. if (sound.soundTrackId) {
  60847. if (sound.soundTrackId === -1) {
  60848. this._scene.mainSoundTrack.RemoveSound(sound);
  60849. }
  60850. else {
  60851. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  60852. }
  60853. }
  60854. this.soundCollection.push(sound);
  60855. sound.soundTrackId = this.id;
  60856. };
  60857. SoundTrack.prototype.RemoveSound = function (sound) {
  60858. var index = this.soundCollection.indexOf(sound);
  60859. if (index !== -1) {
  60860. this.soundCollection.splice(index, 1);
  60861. }
  60862. };
  60863. SoundTrack.prototype.setVolume = function (newVolume) {
  60864. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60865. this._outputAudioNode.gain.value = newVolume;
  60866. }
  60867. };
  60868. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  60869. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60870. for (var i = 0; i < this.soundCollection.length; i++) {
  60871. this.soundCollection[i].switchPanningModelToHRTF();
  60872. }
  60873. }
  60874. };
  60875. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  60876. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60877. for (var i = 0; i < this.soundCollection.length; i++) {
  60878. this.soundCollection[i].switchPanningModelToEqualPower();
  60879. }
  60880. }
  60881. };
  60882. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  60883. if (this._connectedAnalyser) {
  60884. this._connectedAnalyser.stopDebugCanvas();
  60885. }
  60886. this._connectedAnalyser = analyser;
  60887. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  60888. this._outputAudioNode.disconnect();
  60889. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  60890. }
  60891. };
  60892. return SoundTrack;
  60893. }());
  60894. BABYLON.SoundTrack = SoundTrack;
  60895. })(BABYLON || (BABYLON = {}));
  60896. //# sourceMappingURL=babylon.soundtrack.js.map
  60897. "use strict";
  60898. var BABYLON;
  60899. (function (BABYLON) {
  60900. var Analyser = /** @class */ (function () {
  60901. function Analyser(scene) {
  60902. this.SMOOTHING = 0.75;
  60903. this.FFT_SIZE = 512;
  60904. this.BARGRAPHAMPLITUDE = 256;
  60905. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  60906. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  60907. this._scene = scene;
  60908. this._audioEngine = BABYLON.Engine.audioEngine;
  60909. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  60910. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  60911. this._webAudioAnalyser.minDecibels = -140;
  60912. this._webAudioAnalyser.maxDecibels = 0;
  60913. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  60914. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  60915. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  60916. }
  60917. }
  60918. Analyser.prototype.getFrequencyBinCount = function () {
  60919. if (this._audioEngine.canUseWebAudio) {
  60920. return this._webAudioAnalyser.frequencyBinCount;
  60921. }
  60922. else {
  60923. return 0;
  60924. }
  60925. };
  60926. Analyser.prototype.getByteFrequencyData = function () {
  60927. if (this._audioEngine.canUseWebAudio) {
  60928. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  60929. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  60930. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  60931. }
  60932. return this._byteFreqs;
  60933. };
  60934. Analyser.prototype.getByteTimeDomainData = function () {
  60935. if (this._audioEngine.canUseWebAudio) {
  60936. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  60937. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  60938. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  60939. }
  60940. return this._byteTime;
  60941. };
  60942. Analyser.prototype.getFloatFrequencyData = function () {
  60943. if (this._audioEngine.canUseWebAudio) {
  60944. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  60945. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  60946. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  60947. }
  60948. return this._floatFreqs;
  60949. };
  60950. Analyser.prototype.drawDebugCanvas = function () {
  60951. var _this = this;
  60952. if (this._audioEngine.canUseWebAudio) {
  60953. if (!this._debugCanvas) {
  60954. this._debugCanvas = document.createElement("canvas");
  60955. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  60956. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  60957. this._debugCanvas.style.position = "absolute";
  60958. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  60959. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  60960. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  60961. document.body.appendChild(this._debugCanvas);
  60962. this._registerFunc = function () {
  60963. _this.drawDebugCanvas();
  60964. };
  60965. this._scene.registerBeforeRender(this._registerFunc);
  60966. }
  60967. if (this._registerFunc && this._debugCanvasContext) {
  60968. var workingArray = this.getByteFrequencyData();
  60969. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  60970. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  60971. // Draw the frequency domain chart.
  60972. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  60973. var value = workingArray[i];
  60974. var percent = value / this.BARGRAPHAMPLITUDE;
  60975. var height = this.DEBUGCANVASSIZE.height * percent;
  60976. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  60977. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  60978. var hue = i / this.getFrequencyBinCount() * 360;
  60979. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  60980. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  60981. }
  60982. }
  60983. }
  60984. };
  60985. Analyser.prototype.stopDebugCanvas = function () {
  60986. if (this._debugCanvas) {
  60987. if (this._registerFunc) {
  60988. this._scene.unregisterBeforeRender(this._registerFunc);
  60989. this._registerFunc = null;
  60990. }
  60991. document.body.removeChild(this._debugCanvas);
  60992. this._debugCanvas = null;
  60993. this._debugCanvasContext = null;
  60994. }
  60995. };
  60996. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  60997. if (this._audioEngine.canUseWebAudio) {
  60998. inputAudioNode.connect(this._webAudioAnalyser);
  60999. this._webAudioAnalyser.connect(outputAudioNode);
  61000. }
  61001. };
  61002. Analyser.prototype.dispose = function () {
  61003. if (this._audioEngine.canUseWebAudio) {
  61004. this._webAudioAnalyser.disconnect();
  61005. }
  61006. };
  61007. return Analyser;
  61008. }());
  61009. BABYLON.Analyser = Analyser;
  61010. })(BABYLON || (BABYLON = {}));
  61011. //# sourceMappingURL=babylon.analyser.js.map
  61012. "use strict";
  61013. var BABYLON;
  61014. (function (BABYLON) {
  61015. var CubeTexture = /** @class */ (function (_super) {
  61016. __extends(CubeTexture, _super);
  61017. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  61018. if (extensions === void 0) { extensions = null; }
  61019. if (noMipmap === void 0) { noMipmap = false; }
  61020. if (files === void 0) { files = null; }
  61021. if (onLoad === void 0) { onLoad = null; }
  61022. if (onError === void 0) { onError = null; }
  61023. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61024. if (prefiltered === void 0) { prefiltered = false; }
  61025. if (forcedExtension === void 0) { forcedExtension = null; }
  61026. var _this = _super.call(this, scene) || this;
  61027. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61028. /**
  61029. * Gets or sets the center of the bounding box associated with the cube texture
  61030. * It must define where the camera used to render the texture was set
  61031. */
  61032. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61033. _this.name = rootUrl;
  61034. _this.url = rootUrl;
  61035. _this._noMipmap = noMipmap;
  61036. _this.hasAlpha = false;
  61037. _this._format = format;
  61038. _this._prefiltered = prefiltered;
  61039. _this.isCube = true;
  61040. _this._textureMatrix = BABYLON.Matrix.Identity();
  61041. if (prefiltered) {
  61042. _this.gammaSpace = false;
  61043. }
  61044. if (!rootUrl && !files) {
  61045. return _this;
  61046. }
  61047. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  61048. var lastDot = rootUrl.lastIndexOf(".");
  61049. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  61050. var isDDS = (extension === ".dds");
  61051. if (!files) {
  61052. if (!isDDS && !extensions) {
  61053. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  61054. }
  61055. files = [];
  61056. if (extensions) {
  61057. for (var index = 0; index < extensions.length; index++) {
  61058. files.push(rootUrl + extensions[index]);
  61059. }
  61060. }
  61061. }
  61062. _this._files = files;
  61063. if (!_this._texture) {
  61064. if (!scene.useDelayedTextureLoading) {
  61065. if (prefiltered) {
  61066. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  61067. }
  61068. else {
  61069. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  61070. }
  61071. }
  61072. else {
  61073. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61074. }
  61075. }
  61076. else if (onLoad) {
  61077. if (_this._texture.isReady) {
  61078. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  61079. }
  61080. else {
  61081. _this._texture.onLoadedObservable.add(onLoad);
  61082. }
  61083. }
  61084. return _this;
  61085. }
  61086. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  61087. get: function () {
  61088. return this._boundingBoxSize;
  61089. },
  61090. /**
  61091. * Gets or sets the size of the bounding box associated with the cube texture
  61092. * When defined, the cubemap will switch to local mode
  61093. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61094. * @example https://www.babylonjs-playground.com/#RNASML
  61095. */
  61096. set: function (value) {
  61097. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61098. return;
  61099. }
  61100. this._boundingBoxSize = value;
  61101. var scene = this.getScene();
  61102. if (scene) {
  61103. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61104. }
  61105. },
  61106. enumerable: true,
  61107. configurable: true
  61108. });
  61109. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  61110. var rootUrlKey = "";
  61111. files.forEach(function (url) { return rootUrlKey += url; });
  61112. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  61113. };
  61114. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  61115. if (forcedExtension === void 0) { forcedExtension = null; }
  61116. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  61117. };
  61118. // Methods
  61119. CubeTexture.prototype.delayLoad = function () {
  61120. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61121. return;
  61122. }
  61123. var scene = this.getScene();
  61124. if (!scene) {
  61125. return;
  61126. }
  61127. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61128. this._texture = this._getFromCache(this.url, this._noMipmap);
  61129. if (!this._texture) {
  61130. if (this._prefiltered) {
  61131. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  61132. }
  61133. else {
  61134. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  61135. }
  61136. }
  61137. };
  61138. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  61139. return this._textureMatrix;
  61140. };
  61141. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61142. this._textureMatrix = value;
  61143. };
  61144. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61145. var texture = BABYLON.SerializationHelper.Parse(function () {
  61146. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  61147. }, parsedTexture, scene);
  61148. // Local Cubemaps
  61149. if (parsedTexture.boundingBoxPosition) {
  61150. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  61151. }
  61152. if (parsedTexture.boundingBoxSize) {
  61153. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  61154. }
  61155. // Animations
  61156. if (parsedTexture.animations) {
  61157. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  61158. var parsedAnimation = parsedTexture.animations[animationIndex];
  61159. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61160. }
  61161. }
  61162. return texture;
  61163. };
  61164. CubeTexture.prototype.clone = function () {
  61165. var _this = this;
  61166. return BABYLON.SerializationHelper.Clone(function () {
  61167. var scene = _this.getScene();
  61168. if (!scene) {
  61169. return _this;
  61170. }
  61171. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  61172. }, this);
  61173. };
  61174. return CubeTexture;
  61175. }(BABYLON.BaseTexture));
  61176. BABYLON.CubeTexture = CubeTexture;
  61177. })(BABYLON || (BABYLON = {}));
  61178. //# sourceMappingURL=babylon.cubeTexture.js.map
  61179. "use strict";
  61180. var BABYLON;
  61181. (function (BABYLON) {
  61182. var RenderTargetTexture = /** @class */ (function (_super) {
  61183. __extends(RenderTargetTexture, _super);
  61184. /**
  61185. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  61186. * or used a shadow, depth texture...
  61187. * @param name The friendly name of the texture
  61188. * @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)
  61189. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  61190. * @param generateMipMaps True if mip maps need to be generated after render.
  61191. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  61192. * @param type The type of the buffer in the RTT (int, half float, float...)
  61193. * @param isCube True if a cube texture needs to be created
  61194. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  61195. * @param generateDepthBuffer True to generate a depth buffer
  61196. * @param generateStencilBuffer True to generate a stencil buffer
  61197. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  61198. */
  61199. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  61200. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  61201. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61202. if (isCube === void 0) { isCube = false; }
  61203. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61204. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  61205. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  61206. if (isMulti === void 0) { isMulti = false; }
  61207. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61208. _this.isCube = isCube;
  61209. /**
  61210. * Use this list to define the list of mesh you want to render.
  61211. */
  61212. _this.renderList = new Array();
  61213. _this.renderParticles = true;
  61214. _this.renderSprites = false;
  61215. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  61216. _this.ignoreCameraViewport = false;
  61217. // Events
  61218. /**
  61219. * An event triggered when the texture is unbind.
  61220. */
  61221. _this.onBeforeBindObservable = new BABYLON.Observable();
  61222. /**
  61223. * An event triggered when the texture is unbind.
  61224. */
  61225. _this.onAfterUnbindObservable = new BABYLON.Observable();
  61226. /**
  61227. * An event triggered before rendering the texture
  61228. */
  61229. _this.onBeforeRenderObservable = new BABYLON.Observable();
  61230. /**
  61231. * An event triggered after rendering the texture
  61232. */
  61233. _this.onAfterRenderObservable = new BABYLON.Observable();
  61234. /**
  61235. * An event triggered after the texture clear
  61236. */
  61237. _this.onClearObservable = new BABYLON.Observable();
  61238. _this._currentRefreshId = -1;
  61239. _this._refreshRate = 1;
  61240. _this._samples = 1;
  61241. /**
  61242. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  61243. * It must define where the camera used to render the texture is set
  61244. */
  61245. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61246. scene = _this.getScene();
  61247. if (!scene) {
  61248. return _this;
  61249. }
  61250. _this._engine = scene.getEngine();
  61251. _this.name = name;
  61252. _this.isRenderTarget = true;
  61253. _this._initialSizeParameter = size;
  61254. _this._processSizeParameter(size);
  61255. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  61256. });
  61257. _this._generateMipMaps = generateMipMaps ? true : false;
  61258. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  61259. // Rendering groups
  61260. _this._renderingManager = new BABYLON.RenderingManager(scene);
  61261. if (isMulti) {
  61262. return _this;
  61263. }
  61264. _this._renderTargetOptions = {
  61265. generateMipMaps: generateMipMaps,
  61266. type: type,
  61267. samplingMode: samplingMode,
  61268. generateDepthBuffer: generateDepthBuffer,
  61269. generateStencilBuffer: generateStencilBuffer
  61270. };
  61271. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  61272. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61273. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61274. }
  61275. if (isCube) {
  61276. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  61277. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  61278. _this._textureMatrix = BABYLON.Matrix.Identity();
  61279. }
  61280. else {
  61281. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  61282. }
  61283. return _this;
  61284. }
  61285. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  61286. get: function () {
  61287. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  61288. },
  61289. enumerable: true,
  61290. configurable: true
  61291. });
  61292. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  61293. get: function () {
  61294. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  61295. },
  61296. enumerable: true,
  61297. configurable: true
  61298. });
  61299. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  61300. get: function () {
  61301. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  61302. },
  61303. enumerable: true,
  61304. configurable: true
  61305. });
  61306. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  61307. set: function (callback) {
  61308. if (this._onAfterUnbindObserver) {
  61309. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  61310. }
  61311. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  61312. },
  61313. enumerable: true,
  61314. configurable: true
  61315. });
  61316. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  61317. set: function (callback) {
  61318. if (this._onBeforeRenderObserver) {
  61319. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61320. }
  61321. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61322. },
  61323. enumerable: true,
  61324. configurable: true
  61325. });
  61326. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  61327. set: function (callback) {
  61328. if (this._onAfterRenderObserver) {
  61329. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61330. }
  61331. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61332. },
  61333. enumerable: true,
  61334. configurable: true
  61335. });
  61336. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  61337. set: function (callback) {
  61338. if (this._onClearObserver) {
  61339. this.onClearObservable.remove(this._onClearObserver);
  61340. }
  61341. this._onClearObserver = this.onClearObservable.add(callback);
  61342. },
  61343. enumerable: true,
  61344. configurable: true
  61345. });
  61346. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  61347. get: function () {
  61348. return this._renderTargetOptions;
  61349. },
  61350. enumerable: true,
  61351. configurable: true
  61352. });
  61353. RenderTargetTexture.prototype._onRatioRescale = function () {
  61354. if (this._sizeRatio) {
  61355. this.resize(this._initialSizeParameter);
  61356. }
  61357. };
  61358. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  61359. get: function () {
  61360. return this._boundingBoxSize;
  61361. },
  61362. /**
  61363. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  61364. * When defined, the cubemap will switch to local mode
  61365. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61366. * @example https://www.babylonjs-playground.com/#RNASML
  61367. */
  61368. set: function (value) {
  61369. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61370. return;
  61371. }
  61372. this._boundingBoxSize = value;
  61373. var scene = this.getScene();
  61374. if (scene) {
  61375. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61376. }
  61377. },
  61378. enumerable: true,
  61379. configurable: true
  61380. });
  61381. /**
  61382. * Creates a depth stencil texture.
  61383. * This is only available in WebGL 2 or with the depth texture extension available.
  61384. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  61385. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  61386. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  61387. */
  61388. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  61389. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  61390. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  61391. if (generateStencil === void 0) { generateStencil = false; }
  61392. if (!this.getScene()) {
  61393. return;
  61394. }
  61395. var engine = this.getScene().getEngine();
  61396. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  61397. bilinearFiltering: bilinearFiltering,
  61398. comparisonFunction: comparisonFunction,
  61399. generateStencil: generateStencil,
  61400. isCube: this.isCube
  61401. });
  61402. engine.setFrameBufferDepthStencilTexture(this);
  61403. };
  61404. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  61405. if (size.ratio) {
  61406. this._sizeRatio = size.ratio;
  61407. this._size = {
  61408. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  61409. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  61410. };
  61411. }
  61412. else {
  61413. this._size = size;
  61414. }
  61415. };
  61416. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  61417. get: function () {
  61418. return this._samples;
  61419. },
  61420. set: function (value) {
  61421. if (this._samples === value) {
  61422. return;
  61423. }
  61424. var scene = this.getScene();
  61425. if (!scene) {
  61426. return;
  61427. }
  61428. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  61429. },
  61430. enumerable: true,
  61431. configurable: true
  61432. });
  61433. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  61434. this._currentRefreshId = -1;
  61435. };
  61436. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  61437. get: function () {
  61438. return this._refreshRate;
  61439. },
  61440. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61441. set: function (value) {
  61442. this._refreshRate = value;
  61443. this.resetRefreshCounter();
  61444. },
  61445. enumerable: true,
  61446. configurable: true
  61447. });
  61448. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  61449. if (!this._postProcessManager) {
  61450. var scene = this.getScene();
  61451. if (!scene) {
  61452. return;
  61453. }
  61454. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  61455. this._postProcesses = new Array();
  61456. }
  61457. this._postProcesses.push(postProcess);
  61458. this._postProcesses[0].autoClear = false;
  61459. };
  61460. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  61461. if (!this._postProcesses) {
  61462. return;
  61463. }
  61464. if (dispose) {
  61465. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  61466. var postProcess = _a[_i];
  61467. postProcess.dispose();
  61468. }
  61469. }
  61470. this._postProcesses = [];
  61471. };
  61472. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  61473. if (!this._postProcesses) {
  61474. return;
  61475. }
  61476. var index = this._postProcesses.indexOf(postProcess);
  61477. if (index === -1) {
  61478. return;
  61479. }
  61480. this._postProcesses.splice(index, 1);
  61481. if (this._postProcesses.length > 0) {
  61482. this._postProcesses[0].autoClear = false;
  61483. }
  61484. };
  61485. RenderTargetTexture.prototype._shouldRender = function () {
  61486. if (this._currentRefreshId === -1) {
  61487. this._currentRefreshId = 1;
  61488. return true;
  61489. }
  61490. if (this.refreshRate === this._currentRefreshId) {
  61491. this._currentRefreshId = 1;
  61492. return true;
  61493. }
  61494. this._currentRefreshId++;
  61495. return false;
  61496. };
  61497. RenderTargetTexture.prototype.getRenderSize = function () {
  61498. if (this._size.width) {
  61499. return this._size.width;
  61500. }
  61501. return this._size;
  61502. };
  61503. RenderTargetTexture.prototype.getRenderWidth = function () {
  61504. if (this._size.width) {
  61505. return this._size.width;
  61506. }
  61507. return this._size;
  61508. };
  61509. RenderTargetTexture.prototype.getRenderHeight = function () {
  61510. if (this._size.width) {
  61511. return this._size.height;
  61512. }
  61513. return this._size;
  61514. };
  61515. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  61516. get: function () {
  61517. return true;
  61518. },
  61519. enumerable: true,
  61520. configurable: true
  61521. });
  61522. RenderTargetTexture.prototype.scale = function (ratio) {
  61523. var newSize = this.getRenderSize() * ratio;
  61524. this.resize(newSize);
  61525. };
  61526. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  61527. if (this.isCube) {
  61528. return this._textureMatrix;
  61529. }
  61530. return _super.prototype.getReflectionTextureMatrix.call(this);
  61531. };
  61532. RenderTargetTexture.prototype.resize = function (size) {
  61533. this.releaseInternalTexture();
  61534. var scene = this.getScene();
  61535. if (!scene) {
  61536. return;
  61537. }
  61538. this._processSizeParameter(size);
  61539. if (this.isCube) {
  61540. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  61541. }
  61542. else {
  61543. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  61544. }
  61545. };
  61546. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  61547. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  61548. if (dumpForDebug === void 0) { dumpForDebug = false; }
  61549. var scene = this.getScene();
  61550. if (!scene) {
  61551. return;
  61552. }
  61553. var engine = scene.getEngine();
  61554. if (this.useCameraPostProcesses !== undefined) {
  61555. useCameraPostProcess = this.useCameraPostProcesses;
  61556. }
  61557. if (this._waitingRenderList) {
  61558. this.renderList = [];
  61559. for (var index = 0; index < this._waitingRenderList.length; index++) {
  61560. var id = this._waitingRenderList[index];
  61561. var mesh_1 = scene.getMeshByID(id);
  61562. if (mesh_1) {
  61563. this.renderList.push(mesh_1);
  61564. }
  61565. }
  61566. delete this._waitingRenderList;
  61567. }
  61568. // Is predicate defined?
  61569. if (this.renderListPredicate) {
  61570. if (this.renderList) {
  61571. this.renderList.splice(0); // Clear previous renderList
  61572. }
  61573. else {
  61574. this.renderList = [];
  61575. }
  61576. var scene = this.getScene();
  61577. if (!scene) {
  61578. return;
  61579. }
  61580. var sceneMeshes = scene.meshes;
  61581. for (var index = 0; index < sceneMeshes.length; index++) {
  61582. var mesh = sceneMeshes[index];
  61583. if (this.renderListPredicate(mesh)) {
  61584. this.renderList.push(mesh);
  61585. }
  61586. }
  61587. }
  61588. this.onBeforeBindObservable.notifyObservers(this);
  61589. // Set custom projection.
  61590. // Needs to be before binding to prevent changing the aspect ratio.
  61591. var camera;
  61592. if (this.activeCamera) {
  61593. camera = this.activeCamera;
  61594. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  61595. if (this.activeCamera !== scene.activeCamera) {
  61596. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  61597. }
  61598. }
  61599. else {
  61600. camera = scene.activeCamera;
  61601. if (camera) {
  61602. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  61603. }
  61604. }
  61605. // Prepare renderingManager
  61606. this._renderingManager.reset();
  61607. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  61608. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  61609. var sceneRenderId = scene.getRenderId();
  61610. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  61611. var mesh = currentRenderList[meshIndex];
  61612. if (mesh) {
  61613. if (!mesh.isReady(this.refreshRate === 0)) {
  61614. this.resetRefreshCounter();
  61615. continue;
  61616. }
  61617. mesh._preActivateForIntermediateRendering(sceneRenderId);
  61618. var isMasked = void 0;
  61619. if (!this.renderList && camera) {
  61620. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  61621. }
  61622. else {
  61623. isMasked = false;
  61624. }
  61625. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  61626. mesh._activate(sceneRenderId);
  61627. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  61628. var subMesh = mesh.subMeshes[subIndex];
  61629. scene._activeIndices.addCount(subMesh.indexCount, false);
  61630. this._renderingManager.dispatch(subMesh, mesh);
  61631. }
  61632. }
  61633. }
  61634. }
  61635. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  61636. var particleSystem = scene.particleSystems[particleIndex];
  61637. var emitter = particleSystem.emitter;
  61638. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  61639. continue;
  61640. }
  61641. if (currentRenderList.indexOf(emitter) >= 0) {
  61642. this._renderingManager.dispatchParticles(particleSystem);
  61643. }
  61644. }
  61645. if (this.isCube) {
  61646. for (var face = 0; face < 6; face++) {
  61647. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  61648. scene.incrementRenderId();
  61649. scene.resetCachedMaterial();
  61650. }
  61651. }
  61652. else {
  61653. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  61654. }
  61655. this.onAfterUnbindObservable.notifyObservers(this);
  61656. if (scene.activeCamera) {
  61657. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  61658. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  61659. }
  61660. engine.setViewport(scene.activeCamera.viewport);
  61661. }
  61662. scene.resetCachedMaterial();
  61663. };
  61664. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  61665. var minimum = 128;
  61666. var x = renderDimension * scale;
  61667. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  61668. // Ensure we don't exceed the render dimension (while staying POT)
  61669. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  61670. };
  61671. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  61672. var _this = this;
  61673. if (!this._texture) {
  61674. return;
  61675. }
  61676. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  61677. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  61678. });
  61679. };
  61680. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  61681. var scene = this.getScene();
  61682. if (!scene) {
  61683. return;
  61684. }
  61685. var engine = scene.getEngine();
  61686. if (!this._texture) {
  61687. return;
  61688. }
  61689. // Bind
  61690. if (this._postProcessManager) {
  61691. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  61692. }
  61693. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  61694. if (this._texture) {
  61695. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  61696. }
  61697. }
  61698. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  61699. // Clear
  61700. if (this.onClearObservable.hasObservers()) {
  61701. this.onClearObservable.notifyObservers(engine);
  61702. }
  61703. else {
  61704. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  61705. }
  61706. if (!this._doNotChangeAspectRatio) {
  61707. scene.updateTransformMatrix(true);
  61708. }
  61709. // Render
  61710. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  61711. if (this._postProcessManager) {
  61712. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  61713. }
  61714. else if (useCameraPostProcess) {
  61715. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  61716. }
  61717. if (!this._doNotChangeAspectRatio) {
  61718. scene.updateTransformMatrix(true);
  61719. }
  61720. // Dump ?
  61721. if (dumpForDebug) {
  61722. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  61723. }
  61724. // Unbind
  61725. if (!this.isCube || faceIndex === 5) {
  61726. if (this.isCube) {
  61727. if (faceIndex === 5) {
  61728. engine.generateMipMapsForCubemap(this._texture);
  61729. }
  61730. }
  61731. this.unbindFrameBuffer(engine, faceIndex);
  61732. }
  61733. else {
  61734. this.onAfterRenderObservable.notifyObservers(faceIndex);
  61735. }
  61736. };
  61737. /**
  61738. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  61739. * This allowed control for front to back rendering or reversly depending of the special needs.
  61740. *
  61741. * @param renderingGroupId The rendering group id corresponding to its index
  61742. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  61743. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  61744. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  61745. */
  61746. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  61747. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  61748. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  61749. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  61750. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  61751. };
  61752. /**
  61753. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  61754. *
  61755. * @param renderingGroupId The rendering group id corresponding to its index
  61756. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  61757. */
  61758. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  61759. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  61760. };
  61761. RenderTargetTexture.prototype.clone = function () {
  61762. var textureSize = this.getSize();
  61763. 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);
  61764. // Base texture
  61765. newTexture.hasAlpha = this.hasAlpha;
  61766. newTexture.level = this.level;
  61767. // RenderTarget Texture
  61768. newTexture.coordinatesMode = this.coordinatesMode;
  61769. if (this.renderList) {
  61770. newTexture.renderList = this.renderList.slice(0);
  61771. }
  61772. return newTexture;
  61773. };
  61774. RenderTargetTexture.prototype.serialize = function () {
  61775. if (!this.name) {
  61776. return null;
  61777. }
  61778. var serializationObject = _super.prototype.serialize.call(this);
  61779. serializationObject.renderTargetSize = this.getRenderSize();
  61780. serializationObject.renderList = [];
  61781. if (this.renderList) {
  61782. for (var index = 0; index < this.renderList.length; index++) {
  61783. serializationObject.renderList.push(this.renderList[index].id);
  61784. }
  61785. }
  61786. return serializationObject;
  61787. };
  61788. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  61789. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  61790. var objBuffer = this.getInternalTexture();
  61791. var scene = this.getScene();
  61792. if (objBuffer && scene) {
  61793. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  61794. }
  61795. };
  61796. RenderTargetTexture.prototype.dispose = function () {
  61797. if (this._postProcessManager) {
  61798. this._postProcessManager.dispose();
  61799. this._postProcessManager = null;
  61800. }
  61801. this.clearPostProcesses(true);
  61802. if (this._resizeObserver) {
  61803. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  61804. this._resizeObserver = null;
  61805. }
  61806. this.renderList = null;
  61807. // Remove from custom render targets
  61808. var scene = this.getScene();
  61809. if (!scene) {
  61810. return;
  61811. }
  61812. var index = scene.customRenderTargets.indexOf(this);
  61813. if (index >= 0) {
  61814. scene.customRenderTargets.splice(index, 1);
  61815. }
  61816. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  61817. var camera = _a[_i];
  61818. index = camera.customRenderTargets.indexOf(this);
  61819. if (index >= 0) {
  61820. camera.customRenderTargets.splice(index, 1);
  61821. }
  61822. }
  61823. _super.prototype.dispose.call(this);
  61824. };
  61825. RenderTargetTexture.prototype._rebuild = function () {
  61826. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61827. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61828. }
  61829. if (this._postProcessManager) {
  61830. this._postProcessManager._rebuild();
  61831. }
  61832. };
  61833. /**
  61834. * Clear the info related to rendering groups preventing retention point in material dispose.
  61835. */
  61836. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  61837. if (this._renderingManager) {
  61838. this._renderingManager.freeRenderingGroups();
  61839. }
  61840. };
  61841. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  61842. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  61843. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  61844. return RenderTargetTexture;
  61845. }(BABYLON.Texture));
  61846. BABYLON.RenderTargetTexture = RenderTargetTexture;
  61847. })(BABYLON || (BABYLON = {}));
  61848. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  61849. "use strict";
  61850. var BABYLON;
  61851. (function (BABYLON) {
  61852. ;
  61853. var MultiRenderTarget = /** @class */ (function (_super) {
  61854. __extends(MultiRenderTarget, _super);
  61855. function MultiRenderTarget(name, size, count, scene, options) {
  61856. var _this = this;
  61857. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  61858. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  61859. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  61860. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  61861. _this._engine = scene.getEngine();
  61862. if (!_this.isSupported) {
  61863. _this.dispose();
  61864. return;
  61865. }
  61866. var types = [];
  61867. var samplingModes = [];
  61868. for (var i = 0; i < count; i++) {
  61869. if (options && options.types && options.types[i] !== undefined) {
  61870. types.push(options.types[i]);
  61871. }
  61872. else {
  61873. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61874. }
  61875. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  61876. samplingModes.push(options.samplingModes[i]);
  61877. }
  61878. else {
  61879. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61880. }
  61881. }
  61882. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  61883. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  61884. _this._size = size;
  61885. _this._multiRenderTargetOptions = {
  61886. samplingModes: samplingModes,
  61887. generateMipMaps: generateMipMaps,
  61888. generateDepthBuffer: generateDepthBuffer,
  61889. generateStencilBuffer: generateStencilBuffer,
  61890. generateDepthTexture: generateDepthTexture,
  61891. types: types,
  61892. textureCount: count
  61893. };
  61894. _this._createInternalTextures();
  61895. _this._createTextures();
  61896. return _this;
  61897. }
  61898. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  61899. get: function () {
  61900. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  61901. },
  61902. enumerable: true,
  61903. configurable: true
  61904. });
  61905. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  61906. get: function () {
  61907. return this._textures;
  61908. },
  61909. enumerable: true,
  61910. configurable: true
  61911. });
  61912. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  61913. get: function () {
  61914. return this._textures[this._textures.length - 1];
  61915. },
  61916. enumerable: true,
  61917. configurable: true
  61918. });
  61919. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  61920. set: function (wrap) {
  61921. if (this._textures) {
  61922. for (var i = 0; i < this._textures.length; i++) {
  61923. this._textures[i].wrapU = wrap;
  61924. }
  61925. }
  61926. },
  61927. enumerable: true,
  61928. configurable: true
  61929. });
  61930. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  61931. set: function (wrap) {
  61932. if (this._textures) {
  61933. for (var i = 0; i < this._textures.length; i++) {
  61934. this._textures[i].wrapV = wrap;
  61935. }
  61936. }
  61937. },
  61938. enumerable: true,
  61939. configurable: true
  61940. });
  61941. MultiRenderTarget.prototype._rebuild = function () {
  61942. this.releaseInternalTextures();
  61943. this._createInternalTextures();
  61944. for (var i = 0; i < this._internalTextures.length; i++) {
  61945. var texture = this._textures[i];
  61946. texture._texture = this._internalTextures[i];
  61947. }
  61948. // Keeps references to frame buffer and stencil/depth buffer
  61949. this._texture = this._internalTextures[0];
  61950. };
  61951. MultiRenderTarget.prototype._createInternalTextures = function () {
  61952. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  61953. };
  61954. MultiRenderTarget.prototype._createTextures = function () {
  61955. this._textures = [];
  61956. for (var i = 0; i < this._internalTextures.length; i++) {
  61957. var texture = new BABYLON.Texture(null, this.getScene());
  61958. texture._texture = this._internalTextures[i];
  61959. this._textures.push(texture);
  61960. }
  61961. // Keeps references to frame buffer and stencil/depth buffer
  61962. this._texture = this._internalTextures[0];
  61963. };
  61964. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  61965. get: function () {
  61966. return this._samples;
  61967. },
  61968. set: function (value) {
  61969. if (this._samples === value) {
  61970. return;
  61971. }
  61972. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  61973. },
  61974. enumerable: true,
  61975. configurable: true
  61976. });
  61977. MultiRenderTarget.prototype.resize = function (size) {
  61978. this.releaseInternalTextures();
  61979. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  61980. this._createInternalTextures();
  61981. };
  61982. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  61983. var _this = this;
  61984. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  61985. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  61986. });
  61987. };
  61988. MultiRenderTarget.prototype.dispose = function () {
  61989. this.releaseInternalTextures();
  61990. _super.prototype.dispose.call(this);
  61991. };
  61992. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  61993. if (!this._internalTextures) {
  61994. return;
  61995. }
  61996. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  61997. if (this._internalTextures[i] !== undefined) {
  61998. this._internalTextures[i].dispose();
  61999. this._internalTextures.splice(i, 1);
  62000. }
  62001. }
  62002. };
  62003. return MultiRenderTarget;
  62004. }(BABYLON.RenderTargetTexture));
  62005. BABYLON.MultiRenderTarget = MultiRenderTarget;
  62006. })(BABYLON || (BABYLON = {}));
  62007. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  62008. "use strict";
  62009. var BABYLON;
  62010. (function (BABYLON) {
  62011. var MirrorTexture = /** @class */ (function (_super) {
  62012. __extends(MirrorTexture, _super);
  62013. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  62014. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62015. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62016. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62017. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  62018. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  62019. _this._transformMatrix = BABYLON.Matrix.Zero();
  62020. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  62021. _this._adaptiveBlurKernel = 0;
  62022. _this._blurKernelX = 0;
  62023. _this._blurKernelY = 0;
  62024. _this._blurRatio = 1.0;
  62025. _this.ignoreCameraViewport = true;
  62026. _this.onBeforeRenderObservable.add(function () {
  62027. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  62028. _this._savedViewMatrix = scene.getViewMatrix();
  62029. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  62030. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  62031. scene.clipPlane = _this.mirrorPlane;
  62032. scene.getEngine().cullBackFaces = false;
  62033. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  62034. });
  62035. _this.onAfterRenderObservable.add(function () {
  62036. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  62037. scene.getEngine().cullBackFaces = true;
  62038. scene._mirroredCameraPosition = null;
  62039. delete scene.clipPlane;
  62040. });
  62041. return _this;
  62042. }
  62043. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  62044. get: function () {
  62045. return this._blurRatio;
  62046. },
  62047. set: function (value) {
  62048. if (this._blurRatio === value) {
  62049. return;
  62050. }
  62051. this._blurRatio = value;
  62052. this._preparePostProcesses();
  62053. },
  62054. enumerable: true,
  62055. configurable: true
  62056. });
  62057. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  62058. set: function (value) {
  62059. this._adaptiveBlurKernel = value;
  62060. this._autoComputeBlurKernel();
  62061. },
  62062. enumerable: true,
  62063. configurable: true
  62064. });
  62065. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  62066. set: function (value) {
  62067. this.blurKernelX = value;
  62068. this.blurKernelY = value;
  62069. },
  62070. enumerable: true,
  62071. configurable: true
  62072. });
  62073. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  62074. get: function () {
  62075. return this._blurKernelX;
  62076. },
  62077. set: function (value) {
  62078. if (this._blurKernelX === value) {
  62079. return;
  62080. }
  62081. this._blurKernelX = value;
  62082. this._preparePostProcesses();
  62083. },
  62084. enumerable: true,
  62085. configurable: true
  62086. });
  62087. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  62088. get: function () {
  62089. return this._blurKernelY;
  62090. },
  62091. set: function (value) {
  62092. if (this._blurKernelY === value) {
  62093. return;
  62094. }
  62095. this._blurKernelY = value;
  62096. this._preparePostProcesses();
  62097. },
  62098. enumerable: true,
  62099. configurable: true
  62100. });
  62101. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  62102. var engine = this.getScene().getEngine();
  62103. var dw = this.getRenderWidth() / engine.getRenderWidth();
  62104. var dh = this.getRenderHeight() / engine.getRenderHeight();
  62105. this.blurKernelX = this._adaptiveBlurKernel * dw;
  62106. this.blurKernelY = this._adaptiveBlurKernel * dh;
  62107. };
  62108. MirrorTexture.prototype._onRatioRescale = function () {
  62109. if (this._sizeRatio) {
  62110. this.resize(this._initialSizeParameter);
  62111. if (!this._adaptiveBlurKernel) {
  62112. this._preparePostProcesses();
  62113. }
  62114. }
  62115. if (this._adaptiveBlurKernel) {
  62116. this._autoComputeBlurKernel();
  62117. }
  62118. };
  62119. MirrorTexture.prototype._preparePostProcesses = function () {
  62120. this.clearPostProcesses(true);
  62121. if (this._blurKernelX && this._blurKernelY) {
  62122. var engine = this.getScene().getEngine();
  62123. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62124. 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);
  62125. this._blurX.autoClear = false;
  62126. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  62127. this._blurX.inputTexture = this._texture;
  62128. }
  62129. else {
  62130. this._blurX.alwaysForcePOT = true;
  62131. }
  62132. 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);
  62133. this._blurY.autoClear = false;
  62134. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  62135. this.addPostProcess(this._blurX);
  62136. this.addPostProcess(this._blurY);
  62137. }
  62138. else {
  62139. if (this._blurY) {
  62140. this.removePostProcess(this._blurY);
  62141. this._blurY.dispose();
  62142. this._blurY = null;
  62143. }
  62144. if (this._blurX) {
  62145. this.removePostProcess(this._blurX);
  62146. this._blurX.dispose();
  62147. this._blurX = null;
  62148. }
  62149. }
  62150. };
  62151. MirrorTexture.prototype.clone = function () {
  62152. var scene = this.getScene();
  62153. if (!scene) {
  62154. return this;
  62155. }
  62156. var textureSize = this.getSize();
  62157. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  62158. // Base texture
  62159. newTexture.hasAlpha = this.hasAlpha;
  62160. newTexture.level = this.level;
  62161. // Mirror Texture
  62162. newTexture.mirrorPlane = this.mirrorPlane.clone();
  62163. if (this.renderList) {
  62164. newTexture.renderList = this.renderList.slice(0);
  62165. }
  62166. return newTexture;
  62167. };
  62168. MirrorTexture.prototype.serialize = function () {
  62169. if (!this.name) {
  62170. return null;
  62171. }
  62172. var serializationObject = _super.prototype.serialize.call(this);
  62173. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  62174. return serializationObject;
  62175. };
  62176. return MirrorTexture;
  62177. }(BABYLON.RenderTargetTexture));
  62178. BABYLON.MirrorTexture = MirrorTexture;
  62179. })(BABYLON || (BABYLON = {}));
  62180. //# sourceMappingURL=babylon.mirrorTexture.js.map
  62181. "use strict";
  62182. var BABYLON;
  62183. (function (BABYLON) {
  62184. /**
  62185. * Creates a refraction texture used by refraction channel of the standard material.
  62186. * @param name the texture name
  62187. * @param size size of the underlying texture
  62188. * @param scene root scene
  62189. */
  62190. var RefractionTexture = /** @class */ (function (_super) {
  62191. __extends(RefractionTexture, _super);
  62192. function RefractionTexture(name, size, scene, generateMipMaps) {
  62193. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  62194. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  62195. _this.depth = 2.0;
  62196. _this.onBeforeRenderObservable.add(function () {
  62197. scene.clipPlane = _this.refractionPlane;
  62198. });
  62199. _this.onAfterRenderObservable.add(function () {
  62200. delete scene.clipPlane;
  62201. });
  62202. return _this;
  62203. }
  62204. RefractionTexture.prototype.clone = function () {
  62205. var scene = this.getScene();
  62206. if (!scene) {
  62207. return this;
  62208. }
  62209. var textureSize = this.getSize();
  62210. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  62211. // Base texture
  62212. newTexture.hasAlpha = this.hasAlpha;
  62213. newTexture.level = this.level;
  62214. // Refraction Texture
  62215. newTexture.refractionPlane = this.refractionPlane.clone();
  62216. if (this.renderList) {
  62217. newTexture.renderList = this.renderList.slice(0);
  62218. }
  62219. newTexture.depth = this.depth;
  62220. return newTexture;
  62221. };
  62222. RefractionTexture.prototype.serialize = function () {
  62223. if (!this.name) {
  62224. return null;
  62225. }
  62226. var serializationObject = _super.prototype.serialize.call(this);
  62227. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  62228. serializationObject.depth = this.depth;
  62229. return serializationObject;
  62230. };
  62231. return RefractionTexture;
  62232. }(BABYLON.RenderTargetTexture));
  62233. BABYLON.RefractionTexture = RefractionTexture;
  62234. })(BABYLON || (BABYLON = {}));
  62235. //# sourceMappingURL=babylon.refractionTexture.js.map
  62236. "use strict";
  62237. var BABYLON;
  62238. (function (BABYLON) {
  62239. /**
  62240. * A class extending {BABYLON.Texture} allowing drawing on a texture
  62241. * @see http://doc.babylonjs.com/how_to/dynamictexture
  62242. */
  62243. var DynamicTexture = /** @class */ (function (_super) {
  62244. __extends(DynamicTexture, _super);
  62245. /**
  62246. * Creates a {BABYLON.DynamicTexture}
  62247. * @param name defines the name of the texture
  62248. * @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
  62249. * @param scene defines the scene where you want the texture
  62250. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  62251. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  62252. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  62253. */
  62254. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  62255. if (scene === void 0) { scene = null; }
  62256. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62257. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62258. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  62259. _this.name = name;
  62260. _this._engine = _this.getScene().getEngine();
  62261. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62262. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62263. _this._generateMipMaps = generateMipMaps;
  62264. if (options.getContext) {
  62265. _this._canvas = options;
  62266. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62267. }
  62268. else {
  62269. _this._canvas = document.createElement("canvas");
  62270. if (options.width) {
  62271. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62272. }
  62273. else {
  62274. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  62275. }
  62276. }
  62277. var textureSize = _this.getSize();
  62278. _this._canvas.width = textureSize.width;
  62279. _this._canvas.height = textureSize.height;
  62280. _this._context = _this._canvas.getContext("2d");
  62281. return _this;
  62282. }
  62283. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  62284. /**
  62285. * Gets the current state of canRescale
  62286. */
  62287. get: function () {
  62288. return true;
  62289. },
  62290. enumerable: true,
  62291. configurable: true
  62292. });
  62293. DynamicTexture.prototype._recreate = function (textureSize) {
  62294. this._canvas.width = textureSize.width;
  62295. this._canvas.height = textureSize.height;
  62296. this.releaseInternalTexture();
  62297. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  62298. };
  62299. /**
  62300. * Scales the texture
  62301. * @param ratio the scale factor to apply to both width and height
  62302. */
  62303. DynamicTexture.prototype.scale = function (ratio) {
  62304. var textureSize = this.getSize();
  62305. textureSize.width *= ratio;
  62306. textureSize.height *= ratio;
  62307. this._recreate(textureSize);
  62308. };
  62309. /**
  62310. * Resizes the texture
  62311. * @param width the new width
  62312. * @param height the new height
  62313. */
  62314. DynamicTexture.prototype.scaleTo = function (width, height) {
  62315. var textureSize = this.getSize();
  62316. textureSize.width = width;
  62317. textureSize.height = height;
  62318. this._recreate(textureSize);
  62319. };
  62320. /**
  62321. * Gets the context of the canvas used by the texture
  62322. * @returns the canvas context of the dynamic texture
  62323. */
  62324. DynamicTexture.prototype.getContext = function () {
  62325. return this._context;
  62326. };
  62327. /**
  62328. * Clears the texture
  62329. */
  62330. DynamicTexture.prototype.clear = function () {
  62331. var size = this.getSize();
  62332. this._context.fillRect(0, 0, size.width, size.height);
  62333. };
  62334. /**
  62335. * Updates the texture
  62336. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62337. */
  62338. DynamicTexture.prototype.update = function (invertY) {
  62339. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  62340. };
  62341. /**
  62342. * Draws text onto the texture
  62343. * @param text defines the text to be drawn
  62344. * @param x defines the placement of the text from the left
  62345. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  62346. * @param font defines the font to be used with font-style, font-size, font-name
  62347. * @param color defines the color used for the text
  62348. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  62349. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62350. * @param update defines whether texture is immediately update (default is true)
  62351. */
  62352. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  62353. if (update === void 0) { update = true; }
  62354. var size = this.getSize();
  62355. if (clearColor) {
  62356. this._context.fillStyle = clearColor;
  62357. this._context.fillRect(0, 0, size.width, size.height);
  62358. }
  62359. this._context.font = font;
  62360. if (x === null || x === undefined) {
  62361. var textSize = this._context.measureText(text);
  62362. x = (size.width - textSize.width) / 2;
  62363. }
  62364. if (y === null || y === undefined) {
  62365. var fontSize = parseInt((font.replace(/\D/g, '')));
  62366. ;
  62367. y = (size.height / 2) + (fontSize / 3.65);
  62368. }
  62369. this._context.fillStyle = color;
  62370. this._context.fillText(text, x, y);
  62371. if (update) {
  62372. this.update(invertY);
  62373. }
  62374. };
  62375. /**
  62376. * Clones the texture
  62377. * @returns the clone of the texture.
  62378. */
  62379. DynamicTexture.prototype.clone = function () {
  62380. var scene = this.getScene();
  62381. if (!scene) {
  62382. return this;
  62383. }
  62384. var textureSize = this.getSize();
  62385. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  62386. // Base texture
  62387. newTexture.hasAlpha = this.hasAlpha;
  62388. newTexture.level = this.level;
  62389. // Dynamic Texture
  62390. newTexture.wrapU = this.wrapU;
  62391. newTexture.wrapV = this.wrapV;
  62392. return newTexture;
  62393. };
  62394. /** @ignore */
  62395. DynamicTexture.prototype._rebuild = function () {
  62396. this.update();
  62397. };
  62398. return DynamicTexture;
  62399. }(BABYLON.Texture));
  62400. BABYLON.DynamicTexture = DynamicTexture;
  62401. })(BABYLON || (BABYLON = {}));
  62402. //# sourceMappingURL=babylon.dynamicTexture.js.map
  62403. "use strict";
  62404. var BABYLON;
  62405. (function (BABYLON) {
  62406. var VideoTexture = /** @class */ (function (_super) {
  62407. __extends(VideoTexture, _super);
  62408. /**
  62409. * Creates a video texture.
  62410. * Sample : https://doc.babylonjs.com/how_to/video_texture
  62411. * @param {string | null} name optional name, will detect from video source, if not defined
  62412. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  62413. * @param {BABYLON.Scene} scene is obviously the current scene.
  62414. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  62415. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  62416. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  62417. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  62418. */
  62419. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  62420. if (generateMipMaps === void 0) { generateMipMaps = false; }
  62421. if (invertY === void 0) { invertY = false; }
  62422. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62423. if (settings === void 0) { settings = {
  62424. autoPlay: true,
  62425. loop: true,
  62426. autoUpdateTexture: true,
  62427. }; }
  62428. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  62429. _this._createInternalTexture = function () {
  62430. if (_this._texture != null) {
  62431. return;
  62432. }
  62433. if (!_this._engine.needPOTTextures ||
  62434. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  62435. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62436. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62437. }
  62438. else {
  62439. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62440. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62441. _this._generateMipMaps = false;
  62442. }
  62443. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  62444. _this._texture.isReady = true;
  62445. _this._updateInternalTexture();
  62446. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  62447. _this.onLoadObservable.notifyObservers(_this);
  62448. }
  62449. };
  62450. _this.reset = function () {
  62451. if (_this._texture == null) {
  62452. return;
  62453. }
  62454. _this._texture.dispose();
  62455. _this._texture = null;
  62456. };
  62457. _this._updateInternalTexture = function (e) {
  62458. if (_this._texture == null || !_this._texture.isReady) {
  62459. return;
  62460. }
  62461. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  62462. return;
  62463. }
  62464. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  62465. };
  62466. _this._engine = _this.getScene().getEngine();
  62467. _this._generateMipMaps = generateMipMaps;
  62468. _this._samplingMode = samplingMode;
  62469. _this.autoUpdateTexture = settings.autoUpdateTexture;
  62470. _this.name = name || _this._getName(src);
  62471. _this.video = _this._getVideo(src);
  62472. if (settings.autoPlay !== undefined) {
  62473. _this.video.autoplay = settings.autoPlay;
  62474. }
  62475. if (settings.loop !== undefined) {
  62476. _this.video.loop = settings.loop;
  62477. }
  62478. _this.video.addEventListener("canplay", _this._createInternalTexture);
  62479. _this.video.addEventListener("paused", _this._updateInternalTexture);
  62480. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  62481. _this.video.addEventListener("emptied", _this.reset);
  62482. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  62483. _this._createInternalTexture();
  62484. }
  62485. return _this;
  62486. }
  62487. VideoTexture.prototype._getName = function (src) {
  62488. if (src instanceof HTMLVideoElement) {
  62489. return src.currentSrc;
  62490. }
  62491. if (typeof src === "object") {
  62492. return src.toString();
  62493. }
  62494. return src;
  62495. };
  62496. ;
  62497. VideoTexture.prototype._getVideo = function (src) {
  62498. if (src instanceof HTMLVideoElement) {
  62499. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  62500. return src;
  62501. }
  62502. var video = document.createElement("video");
  62503. if (typeof src === "string") {
  62504. BABYLON.Tools.SetCorsBehavior(src, video);
  62505. video.src = src;
  62506. }
  62507. else {
  62508. BABYLON.Tools.SetCorsBehavior(src[0], video);
  62509. src.forEach(function (url) {
  62510. var source = document.createElement("source");
  62511. source.src = url;
  62512. video.appendChild(source);
  62513. });
  62514. }
  62515. return video;
  62516. };
  62517. ;
  62518. /**
  62519. * Internal method to initiate `update`.
  62520. */
  62521. VideoTexture.prototype._rebuild = function () {
  62522. this.update();
  62523. };
  62524. /**
  62525. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  62526. */
  62527. VideoTexture.prototype.update = function () {
  62528. if (!this.autoUpdateTexture) {
  62529. // Expecting user to call `updateTexture` manually
  62530. return;
  62531. }
  62532. this.updateTexture(true);
  62533. };
  62534. /**
  62535. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  62536. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  62537. */
  62538. VideoTexture.prototype.updateTexture = function (isVisible) {
  62539. if (!isVisible) {
  62540. return;
  62541. }
  62542. if (this.video.paused) {
  62543. return;
  62544. }
  62545. this._updateInternalTexture();
  62546. };
  62547. /**
  62548. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  62549. * @param url New url.
  62550. */
  62551. VideoTexture.prototype.updateURL = function (url) {
  62552. this.video.src = url;
  62553. };
  62554. VideoTexture.prototype.dispose = function () {
  62555. _super.prototype.dispose.call(this);
  62556. this.video.removeEventListener("canplay", this._createInternalTexture);
  62557. this.video.removeEventListener("paused", this._updateInternalTexture);
  62558. this.video.removeEventListener("seeked", this._updateInternalTexture);
  62559. this.video.removeEventListener("emptied", this.reset);
  62560. this.video.pause();
  62561. };
  62562. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  62563. var video = document.createElement("video");
  62564. var constraintsDeviceId;
  62565. if (constraints && constraints.deviceId) {
  62566. constraintsDeviceId = {
  62567. exact: constraints.deviceId,
  62568. };
  62569. }
  62570. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  62571. if (navigator.mediaDevices) {
  62572. navigator.mediaDevices.getUserMedia({ video: constraints })
  62573. .then(function (stream) {
  62574. if (video.mozSrcObject !== undefined) {
  62575. // hack for Firefox < 19
  62576. video.mozSrcObject = stream;
  62577. }
  62578. else {
  62579. video.srcObject = stream;
  62580. }
  62581. var onPlaying = function () {
  62582. if (onReady) {
  62583. onReady(new VideoTexture("video", video, scene, true, true));
  62584. }
  62585. video.removeEventListener("playing", onPlaying);
  62586. };
  62587. video.addEventListener("playing", onPlaying);
  62588. video.play();
  62589. })
  62590. .catch(function (err) {
  62591. BABYLON.Tools.Error(err.name);
  62592. });
  62593. }
  62594. else {
  62595. navigator.getUserMedia =
  62596. navigator.getUserMedia ||
  62597. navigator.webkitGetUserMedia ||
  62598. navigator.mozGetUserMedia ||
  62599. navigator.msGetUserMedia;
  62600. if (navigator.getUserMedia) {
  62601. navigator.getUserMedia({
  62602. video: {
  62603. deviceId: constraintsDeviceId,
  62604. width: {
  62605. min: (constraints && constraints.minWidth) || 256,
  62606. max: (constraints && constraints.maxWidth) || 640,
  62607. },
  62608. height: {
  62609. min: (constraints && constraints.minHeight) || 256,
  62610. max: (constraints && constraints.maxHeight) || 480,
  62611. },
  62612. },
  62613. }, function (stream) {
  62614. if (video.mozSrcObject !== undefined) {
  62615. // hack for Firefox < 19
  62616. video.mozSrcObject = stream;
  62617. }
  62618. else {
  62619. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  62620. }
  62621. video.play();
  62622. if (onReady) {
  62623. onReady(new VideoTexture("video", video, scene, true, true));
  62624. }
  62625. }, function (e) {
  62626. BABYLON.Tools.Error(e.name);
  62627. });
  62628. }
  62629. }
  62630. };
  62631. return VideoTexture;
  62632. }(BABYLON.Texture));
  62633. BABYLON.VideoTexture = VideoTexture;
  62634. })(BABYLON || (BABYLON = {}));
  62635. //# sourceMappingURL=babylon.videoTexture.js.map
  62636. "use strict";
  62637. var BABYLON;
  62638. (function (BABYLON) {
  62639. var RawTexture = /** @class */ (function (_super) {
  62640. __extends(RawTexture, _super);
  62641. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  62642. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62643. if (invertY === void 0) { invertY = false; }
  62644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62645. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62646. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  62647. _this.format = format;
  62648. _this._engine = scene.getEngine();
  62649. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  62650. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62651. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62652. return _this;
  62653. }
  62654. RawTexture.prototype.update = function (data) {
  62655. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  62656. };
  62657. // Statics
  62658. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62659. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62660. if (invertY === void 0) { invertY = false; }
  62661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62662. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  62663. };
  62664. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62665. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62666. if (invertY === void 0) { invertY = false; }
  62667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62668. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  62669. };
  62670. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  62671. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62672. if (invertY === void 0) { invertY = false; }
  62673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62674. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  62675. };
  62676. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  62677. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62678. if (invertY === void 0) { invertY = false; }
  62679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62680. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62681. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  62682. };
  62683. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  62684. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62685. if (invertY === void 0) { invertY = false; }
  62686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62687. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62688. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  62689. };
  62690. return RawTexture;
  62691. }(BABYLON.Texture));
  62692. BABYLON.RawTexture = RawTexture;
  62693. })(BABYLON || (BABYLON = {}));
  62694. //# sourceMappingURL=babylon.rawTexture.js.map
  62695. "use strict";
  62696. var BABYLON;
  62697. (function (BABYLON) {
  62698. /**
  62699. * PostProcess can be used to apply a shader to a texture after it has been rendered
  62700. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  62701. */
  62702. var PostProcess = /** @class */ (function () {
  62703. /**
  62704. * Creates a new instance PostProcess
  62705. * @param name The name of the PostProcess.
  62706. * @param fragmentUrl The url of the fragment shader to be used.
  62707. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  62708. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  62709. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  62710. * @param camera The camera to apply the render pass to.
  62711. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  62712. * @param engine The engine which the post process will be applied. (default: current engine)
  62713. * @param reusable If the post process can be reused on the same frame. (default: false)
  62714. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  62715. * @param textureType Type of textures used when performing the post process. (default: 0)
  62716. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  62717. * @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
  62718. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  62719. */
  62720. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  62721. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  62722. if (defines === void 0) { defines = null; }
  62723. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62724. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  62725. if (blockCompilation === void 0) { blockCompilation = false; }
  62726. this.name = name;
  62727. /**
  62728. * Width of the texture to apply the post process on
  62729. */
  62730. this.width = -1;
  62731. /**
  62732. * Height of the texture to apply the post process on
  62733. */
  62734. this.height = -1;
  62735. /**
  62736. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  62737. */
  62738. this._outputTexture = null;
  62739. /**
  62740. * If the buffer needs to be cleared before applying the post process. (default: true)
  62741. * Should be set to false if shader will overwrite all previous pixels.
  62742. */
  62743. this.autoClear = true;
  62744. /**
  62745. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  62746. */
  62747. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  62748. /**
  62749. * Animations to be used for the post processing
  62750. */
  62751. this.animations = new Array();
  62752. /**
  62753. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  62754. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  62755. */
  62756. this.enablePixelPerfectMode = false;
  62757. /**
  62758. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  62759. */
  62760. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  62761. /**
  62762. * Force textures to be a power of two (default: false)
  62763. */
  62764. this.alwaysForcePOT = false;
  62765. /**
  62766. * Number of sample textures (default: 1)
  62767. */
  62768. this.samples = 1;
  62769. /**
  62770. * Modify the scale of the post process to be the same as the viewport (default: false)
  62771. */
  62772. this.adaptScaleToCurrentViewport = false;
  62773. this._reusable = false;
  62774. /**
  62775. * Smart array of input and output textures for the post process.
  62776. */
  62777. this._textures = new BABYLON.SmartArray(2);
  62778. /**
  62779. * The index in _textures that corresponds to the output texture.
  62780. */
  62781. this._currentRenderTextureInd = 0;
  62782. this._scaleRatio = new BABYLON.Vector2(1, 1);
  62783. this._texelSize = BABYLON.Vector2.Zero();
  62784. // Events
  62785. /**
  62786. * An event triggered when the postprocess is activated.
  62787. */
  62788. this.onActivateObservable = new BABYLON.Observable();
  62789. /**
  62790. * An event triggered when the postprocess changes its size.
  62791. */
  62792. this.onSizeChangedObservable = new BABYLON.Observable();
  62793. /**
  62794. * An event triggered when the postprocess applies its effect.
  62795. */
  62796. this.onApplyObservable = new BABYLON.Observable();
  62797. /**
  62798. * An event triggered before rendering the postprocess
  62799. */
  62800. this.onBeforeRenderObservable = new BABYLON.Observable();
  62801. /**
  62802. * An event triggered after rendering the postprocess
  62803. */
  62804. this.onAfterRenderObservable = new BABYLON.Observable();
  62805. if (camera != null) {
  62806. this._camera = camera;
  62807. this._scene = camera.getScene();
  62808. camera.attachPostProcess(this);
  62809. this._engine = this._scene.getEngine();
  62810. this._scene.postProcesses.push(this);
  62811. }
  62812. else if (engine) {
  62813. this._engine = engine;
  62814. this._engine.postProcesses.push(this);
  62815. }
  62816. this._options = options;
  62817. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  62818. this._reusable = reusable || false;
  62819. this._textureType = textureType;
  62820. this._samplers = samplers || [];
  62821. this._samplers.push("textureSampler");
  62822. this._fragmentUrl = fragmentUrl;
  62823. this._vertexUrl = vertexUrl;
  62824. this._parameters = parameters || [];
  62825. this._parameters.push("scale");
  62826. this._indexParameters = indexParameters;
  62827. if (!blockCompilation) {
  62828. this.updateEffect(defines);
  62829. }
  62830. }
  62831. Object.defineProperty(PostProcess.prototype, "onActivate", {
  62832. /**
  62833. * A function that is added to the onActivateObservable
  62834. */
  62835. set: function (callback) {
  62836. if (this._onActivateObserver) {
  62837. this.onActivateObservable.remove(this._onActivateObserver);
  62838. }
  62839. if (callback) {
  62840. this._onActivateObserver = this.onActivateObservable.add(callback);
  62841. }
  62842. },
  62843. enumerable: true,
  62844. configurable: true
  62845. });
  62846. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  62847. /**
  62848. * A function that is added to the onSizeChangedObservable
  62849. */
  62850. set: function (callback) {
  62851. if (this._onSizeChangedObserver) {
  62852. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  62853. }
  62854. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  62855. },
  62856. enumerable: true,
  62857. configurable: true
  62858. });
  62859. Object.defineProperty(PostProcess.prototype, "onApply", {
  62860. /**
  62861. * A function that is added to the onApplyObservable
  62862. */
  62863. set: function (callback) {
  62864. if (this._onApplyObserver) {
  62865. this.onApplyObservable.remove(this._onApplyObserver);
  62866. }
  62867. this._onApplyObserver = this.onApplyObservable.add(callback);
  62868. },
  62869. enumerable: true,
  62870. configurable: true
  62871. });
  62872. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  62873. /**
  62874. * A function that is added to the onBeforeRenderObservable
  62875. */
  62876. set: function (callback) {
  62877. if (this._onBeforeRenderObserver) {
  62878. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62879. }
  62880. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62881. },
  62882. enumerable: true,
  62883. configurable: true
  62884. });
  62885. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  62886. /**
  62887. * A function that is added to the onAfterRenderObservable
  62888. */
  62889. set: function (callback) {
  62890. if (this._onAfterRenderObserver) {
  62891. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62892. }
  62893. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62894. },
  62895. enumerable: true,
  62896. configurable: true
  62897. });
  62898. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  62899. /**
  62900. * 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
  62901. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  62902. */
  62903. get: function () {
  62904. return this._textures.data[this._currentRenderTextureInd];
  62905. },
  62906. set: function (value) {
  62907. this._forcedOutputTexture = value;
  62908. },
  62909. enumerable: true,
  62910. configurable: true
  62911. });
  62912. /**
  62913. * Gets the camera which post process is applied to.
  62914. * @returns The camera the post process is applied to.
  62915. */
  62916. PostProcess.prototype.getCamera = function () {
  62917. return this._camera;
  62918. };
  62919. Object.defineProperty(PostProcess.prototype, "texelSize", {
  62920. /**
  62921. * Gets the texel size of the postprocess.
  62922. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  62923. */
  62924. get: function () {
  62925. if (this._shareOutputWithPostProcess) {
  62926. return this._shareOutputWithPostProcess.texelSize;
  62927. }
  62928. if (this._forcedOutputTexture) {
  62929. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  62930. }
  62931. return this._texelSize;
  62932. },
  62933. enumerable: true,
  62934. configurable: true
  62935. });
  62936. /**
  62937. * Gets the engine which this post process belongs to.
  62938. * @returns The engine the post process was enabled with.
  62939. */
  62940. PostProcess.prototype.getEngine = function () {
  62941. return this._engine;
  62942. };
  62943. /**
  62944. * The effect that is created when initializing the post process.
  62945. * @returns The created effect corrisponding the the postprocess.
  62946. */
  62947. PostProcess.prototype.getEffect = function () {
  62948. return this._effect;
  62949. };
  62950. /**
  62951. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  62952. * @param postProcess The post process to share the output with.
  62953. * @returns This post process.
  62954. */
  62955. PostProcess.prototype.shareOutputWith = function (postProcess) {
  62956. this._disposeTextures();
  62957. this._shareOutputWithPostProcess = postProcess;
  62958. return this;
  62959. };
  62960. /**
  62961. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  62962. * This should be called if the post process that shares output with this post process is disabled/disposed.
  62963. */
  62964. PostProcess.prototype.useOwnOutput = function () {
  62965. if (this._textures.length == 0) {
  62966. this._textures = new BABYLON.SmartArray(2);
  62967. }
  62968. this._shareOutputWithPostProcess = null;
  62969. };
  62970. /**
  62971. * Updates the effect with the current post process compile time values and recompiles the shader.
  62972. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  62973. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  62974. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  62975. * @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
  62976. * @param onCompiled Called when the shader has been compiled.
  62977. * @param onError Called if there is an error when compiling a shader.
  62978. */
  62979. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  62980. if (defines === void 0) { defines = null; }
  62981. if (uniforms === void 0) { uniforms = null; }
  62982. if (samplers === void 0) { samplers = null; }
  62983. 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);
  62984. };
  62985. /**
  62986. * The post process is reusable if it can be used multiple times within one frame.
  62987. * @returns If the post process is reusable
  62988. */
  62989. PostProcess.prototype.isReusable = function () {
  62990. return this._reusable;
  62991. };
  62992. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  62993. PostProcess.prototype.markTextureDirty = function () {
  62994. this.width = -1;
  62995. };
  62996. /**
  62997. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  62998. * 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.
  62999. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  63000. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  63001. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  63002. * @returns The target texture that was bound to be written to.
  63003. */
  63004. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  63005. var _this = this;
  63006. if (sourceTexture === void 0) { sourceTexture = null; }
  63007. camera = camera || this._camera;
  63008. var scene = camera.getScene();
  63009. var engine = scene.getEngine();
  63010. var maxSize = engine.getCaps().maxTextureSize;
  63011. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  63012. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  63013. // 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
  63014. var webVRCamera = camera.parent;
  63015. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  63016. requiredWidth /= 2;
  63017. }
  63018. var desiredWidth = (this._options.width || requiredWidth);
  63019. var desiredHeight = this._options.height || requiredHeight;
  63020. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  63021. if (this.adaptScaleToCurrentViewport) {
  63022. var currentViewport = engine.currentViewport;
  63023. if (currentViewport) {
  63024. desiredWidth *= currentViewport.width;
  63025. desiredHeight *= currentViewport.height;
  63026. }
  63027. }
  63028. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  63029. if (!this._options.width) {
  63030. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  63031. }
  63032. if (!this._options.height) {
  63033. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  63034. }
  63035. }
  63036. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  63037. if (this._textures.length > 0) {
  63038. for (var i = 0; i < this._textures.length; i++) {
  63039. this._engine._releaseTexture(this._textures.data[i]);
  63040. }
  63041. this._textures.reset();
  63042. }
  63043. this.width = desiredWidth;
  63044. this.height = desiredHeight;
  63045. var textureSize = { width: this.width, height: this.height };
  63046. var textureOptions = {
  63047. generateMipMaps: false,
  63048. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  63049. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  63050. samplingMode: this.renderTargetSamplingMode,
  63051. type: this._textureType
  63052. };
  63053. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63054. if (this._reusable) {
  63055. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63056. }
  63057. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  63058. this.onSizeChangedObservable.notifyObservers(this);
  63059. }
  63060. this._textures.forEach(function (texture) {
  63061. if (texture.samples !== _this.samples) {
  63062. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  63063. }
  63064. });
  63065. }
  63066. var target;
  63067. if (this._shareOutputWithPostProcess) {
  63068. target = this._shareOutputWithPostProcess.inputTexture;
  63069. }
  63070. else if (this._forcedOutputTexture) {
  63071. target = this._forcedOutputTexture;
  63072. this.width = this._forcedOutputTexture.width;
  63073. this.height = this._forcedOutputTexture.height;
  63074. }
  63075. else {
  63076. target = this.inputTexture;
  63077. }
  63078. // Bind the input of this post process to be used as the output of the previous post process.
  63079. if (this.enablePixelPerfectMode) {
  63080. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  63081. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  63082. }
  63083. else {
  63084. this._scaleRatio.copyFromFloats(1, 1);
  63085. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  63086. }
  63087. this.onActivateObservable.notifyObservers(camera);
  63088. // Clear
  63089. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  63090. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  63091. }
  63092. if (this._reusable) {
  63093. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  63094. }
  63095. return target;
  63096. };
  63097. Object.defineProperty(PostProcess.prototype, "isSupported", {
  63098. /**
  63099. * If the post process is supported.
  63100. */
  63101. get: function () {
  63102. return this._effect.isSupported;
  63103. },
  63104. enumerable: true,
  63105. configurable: true
  63106. });
  63107. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  63108. /**
  63109. * The aspect ratio of the output texture.
  63110. */
  63111. get: function () {
  63112. if (this._shareOutputWithPostProcess) {
  63113. return this._shareOutputWithPostProcess.aspectRatio;
  63114. }
  63115. if (this._forcedOutputTexture) {
  63116. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  63117. }
  63118. return this.width / this.height;
  63119. },
  63120. enumerable: true,
  63121. configurable: true
  63122. });
  63123. /**
  63124. * Get a value indicating if the post-process is ready to be used
  63125. * @returns true if the post-process is ready (shader is compiled)
  63126. */
  63127. PostProcess.prototype.isReady = function () {
  63128. return this._effect && this._effect.isReady();
  63129. };
  63130. /**
  63131. * Binds all textures and uniforms to the shader, this will be run on every pass.
  63132. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  63133. */
  63134. PostProcess.prototype.apply = function () {
  63135. // Check
  63136. if (!this._effect || !this._effect.isReady())
  63137. return null;
  63138. // States
  63139. this._engine.enableEffect(this._effect);
  63140. this._engine.setState(false);
  63141. this._engine.setDepthBuffer(false);
  63142. this._engine.setDepthWrite(false);
  63143. // Alpha
  63144. this._engine.setAlphaMode(this.alphaMode);
  63145. if (this.alphaConstants) {
  63146. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  63147. }
  63148. // Bind the output texture of the preivous post process as the input to this post process.
  63149. var source;
  63150. if (this._shareOutputWithPostProcess) {
  63151. source = this._shareOutputWithPostProcess.inputTexture;
  63152. }
  63153. else if (this._forcedOutputTexture) {
  63154. source = this._forcedOutputTexture;
  63155. }
  63156. else {
  63157. source = this.inputTexture;
  63158. }
  63159. this._effect._bindTexture("textureSampler", source);
  63160. // Parameters
  63161. this._effect.setVector2("scale", this._scaleRatio);
  63162. this.onApplyObservable.notifyObservers(this._effect);
  63163. return this._effect;
  63164. };
  63165. PostProcess.prototype._disposeTextures = function () {
  63166. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  63167. return;
  63168. }
  63169. if (this._textures.length > 0) {
  63170. for (var i = 0; i < this._textures.length; i++) {
  63171. this._engine._releaseTexture(this._textures.data[i]);
  63172. }
  63173. }
  63174. this._textures.dispose();
  63175. };
  63176. /**
  63177. * Disposes the post process.
  63178. * @param camera The camera to dispose the post process on.
  63179. */
  63180. PostProcess.prototype.dispose = function (camera) {
  63181. camera = camera || this._camera;
  63182. this._disposeTextures();
  63183. if (this._scene) {
  63184. var index_1 = this._scene.postProcesses.indexOf(this);
  63185. if (index_1 !== -1) {
  63186. this._scene.postProcesses.splice(index_1, 1);
  63187. }
  63188. }
  63189. else {
  63190. var index_2 = this._engine.postProcesses.indexOf(this);
  63191. if (index_2 !== -1) {
  63192. this._engine.postProcesses.splice(index_2, 1);
  63193. }
  63194. }
  63195. if (!camera) {
  63196. return;
  63197. }
  63198. camera.detachPostProcess(this);
  63199. var index = camera._postProcesses.indexOf(this);
  63200. if (index === 0 && camera._postProcesses.length > 0) {
  63201. var firstPostProcess = this._camera._getFirstPostProcess();
  63202. if (firstPostProcess) {
  63203. firstPostProcess.markTextureDirty();
  63204. }
  63205. }
  63206. this.onActivateObservable.clear();
  63207. this.onAfterRenderObservable.clear();
  63208. this.onApplyObservable.clear();
  63209. this.onBeforeRenderObservable.clear();
  63210. this.onSizeChangedObservable.clear();
  63211. };
  63212. return PostProcess;
  63213. }());
  63214. BABYLON.PostProcess = PostProcess;
  63215. })(BABYLON || (BABYLON = {}));
  63216. //# sourceMappingURL=babylon.postProcess.js.map
  63217. "use strict";
  63218. var BABYLON;
  63219. (function (BABYLON) {
  63220. var PassPostProcess = /** @class */ (function (_super) {
  63221. __extends(PassPostProcess, _super);
  63222. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  63223. if (camera === void 0) { camera = null; }
  63224. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63225. if (blockCompilation === void 0) { blockCompilation = false; }
  63226. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  63227. }
  63228. return PassPostProcess;
  63229. }(BABYLON.PostProcess));
  63230. BABYLON.PassPostProcess = PassPostProcess;
  63231. })(BABYLON || (BABYLON = {}));
  63232. //# sourceMappingURL=babylon.passPostProcess.js.map
  63233. "use strict";
  63234. var __assign = (this && this.__assign) || Object.assign || function(t) {
  63235. for (var s, i = 1, n = arguments.length; i < n; i++) {
  63236. s = arguments[i];
  63237. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  63238. t[p] = s[p];
  63239. }
  63240. return t;
  63241. };
  63242. var BABYLON;
  63243. (function (BABYLON) {
  63244. /**
  63245. * Default implementation IShadowGenerator.
  63246. * This is the main object responsible of generating shadows in the framework.
  63247. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  63248. */
  63249. var ShadowGenerator = /** @class */ (function () {
  63250. /**
  63251. * Creates a ShadowGenerator object.
  63252. * A ShadowGenerator is the required tool to use the shadows.
  63253. * Each light casting shadows needs to use its own ShadowGenerator.
  63254. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  63255. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  63256. * @param light The light object generating the shadows.
  63257. * @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.
  63258. */
  63259. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  63260. this._bias = 0.00005;
  63261. this._normalBias = 0;
  63262. this._blurBoxOffset = 1;
  63263. this._blurScale = 2;
  63264. this._blurKernel = 1;
  63265. this._useKernelBlur = false;
  63266. this._filter = ShadowGenerator.FILTER_NONE;
  63267. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  63268. this._contactHardeningLightSizeUVRatio = 0.1;
  63269. this._darkness = 0;
  63270. this._transparencyShadow = false;
  63271. /**
  63272. * Controls the extent to which the shadows fade out at the edge of the frustum
  63273. * Used only by directionals and spots
  63274. */
  63275. this.frustumEdgeFalloff = 0;
  63276. /**
  63277. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  63278. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  63279. * It might on the other hand introduce peter panning.
  63280. */
  63281. this.forceBackFacesOnly = false;
  63282. this._lightDirection = BABYLON.Vector3.Zero();
  63283. this._viewMatrix = BABYLON.Matrix.Zero();
  63284. this._projectionMatrix = BABYLON.Matrix.Zero();
  63285. this._transformMatrix = BABYLON.Matrix.Zero();
  63286. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63287. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63288. this._currentFaceIndex = 0;
  63289. this._currentFaceIndexCache = 0;
  63290. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  63291. this._mapSize = mapSize;
  63292. this._light = light;
  63293. this._scene = light.getScene();
  63294. light._shadowGenerator = this;
  63295. // Texture type fallback from float to int if not supported.
  63296. var caps = this._scene.getEngine().getCaps();
  63297. if (!useFullFloatFirst) {
  63298. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63299. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63300. }
  63301. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63302. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63303. }
  63304. else {
  63305. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63306. }
  63307. }
  63308. else {
  63309. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63310. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63311. }
  63312. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63313. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63314. }
  63315. else {
  63316. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63317. }
  63318. }
  63319. this._initializeGenerator();
  63320. this._applyFilterValues();
  63321. }
  63322. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  63323. /**
  63324. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  63325. */
  63326. get: function () {
  63327. return this._bias;
  63328. },
  63329. /**
  63330. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  63331. */
  63332. set: function (bias) {
  63333. this._bias = bias;
  63334. },
  63335. enumerable: true,
  63336. configurable: true
  63337. });
  63338. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  63339. /**
  63340. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63341. */
  63342. get: function () {
  63343. return this._normalBias;
  63344. },
  63345. /**
  63346. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63347. */
  63348. set: function (normalBias) {
  63349. this._normalBias = normalBias;
  63350. },
  63351. enumerable: true,
  63352. configurable: true
  63353. });
  63354. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  63355. /**
  63356. * Gets the blur box offset: offset applied during the blur pass.
  63357. * Only usefull if useKernelBlur = false
  63358. */
  63359. get: function () {
  63360. return this._blurBoxOffset;
  63361. },
  63362. /**
  63363. * Sets the blur box offset: offset applied during the blur pass.
  63364. * Only usefull if useKernelBlur = false
  63365. */
  63366. set: function (value) {
  63367. if (this._blurBoxOffset === value) {
  63368. return;
  63369. }
  63370. this._blurBoxOffset = value;
  63371. this._disposeBlurPostProcesses();
  63372. },
  63373. enumerable: true,
  63374. configurable: true
  63375. });
  63376. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  63377. /**
  63378. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  63379. * 2 means half of the size.
  63380. */
  63381. get: function () {
  63382. return this._blurScale;
  63383. },
  63384. /**
  63385. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  63386. * 2 means half of the size.
  63387. */
  63388. set: function (value) {
  63389. if (this._blurScale === value) {
  63390. return;
  63391. }
  63392. this._blurScale = value;
  63393. this._disposeBlurPostProcesses();
  63394. },
  63395. enumerable: true,
  63396. configurable: true
  63397. });
  63398. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  63399. /**
  63400. * Gets the blur kernel: kernel size of the blur pass.
  63401. * Only usefull if useKernelBlur = true
  63402. */
  63403. get: function () {
  63404. return this._blurKernel;
  63405. },
  63406. /**
  63407. * Sets the blur kernel: kernel size of the blur pass.
  63408. * Only usefull if useKernelBlur = true
  63409. */
  63410. set: function (value) {
  63411. if (this._blurKernel === value) {
  63412. return;
  63413. }
  63414. this._blurKernel = value;
  63415. this._disposeBlurPostProcesses();
  63416. },
  63417. enumerable: true,
  63418. configurable: true
  63419. });
  63420. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  63421. /**
  63422. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  63423. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63424. */
  63425. get: function () {
  63426. return this._useKernelBlur;
  63427. },
  63428. /**
  63429. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  63430. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63431. */
  63432. set: function (value) {
  63433. if (this._useKernelBlur === value) {
  63434. return;
  63435. }
  63436. this._useKernelBlur = value;
  63437. this._disposeBlurPostProcesses();
  63438. },
  63439. enumerable: true,
  63440. configurable: true
  63441. });
  63442. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  63443. /**
  63444. * Gets the depth scale used in ESM mode.
  63445. */
  63446. get: function () {
  63447. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  63448. },
  63449. /**
  63450. * Sets the depth scale used in ESM mode.
  63451. * This can override the scale stored on the light.
  63452. */
  63453. set: function (value) {
  63454. this._depthScale = value;
  63455. },
  63456. enumerable: true,
  63457. configurable: true
  63458. });
  63459. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  63460. /**
  63461. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  63462. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63463. */
  63464. get: function () {
  63465. return this._filter;
  63466. },
  63467. /**
  63468. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  63469. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63470. */
  63471. set: function (value) {
  63472. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  63473. if (this._light.needCube()) {
  63474. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  63475. this.useExponentialShadowMap = true;
  63476. return;
  63477. }
  63478. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  63479. this.useCloseExponentialShadowMap = true;
  63480. return;
  63481. }
  63482. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  63483. this.usePoissonSampling = true;
  63484. return;
  63485. }
  63486. }
  63487. // Weblg1 fallback for PCF.
  63488. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  63489. if (this._scene.getEngine().webGLVersion === 1) {
  63490. this.usePoissonSampling = true;
  63491. return;
  63492. }
  63493. }
  63494. if (this._filter === value) {
  63495. return;
  63496. }
  63497. this._filter = value;
  63498. this._disposeBlurPostProcesses();
  63499. this._applyFilterValues();
  63500. this._light._markMeshesAsLightDirty();
  63501. },
  63502. enumerable: true,
  63503. configurable: true
  63504. });
  63505. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  63506. /**
  63507. * Gets if the current filter is set to Poisson Sampling.
  63508. */
  63509. get: function () {
  63510. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  63511. },
  63512. /**
  63513. * Sets the current filter to Poisson Sampling.
  63514. */
  63515. set: function (value) {
  63516. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  63517. return;
  63518. }
  63519. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  63520. },
  63521. enumerable: true,
  63522. configurable: true
  63523. });
  63524. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  63525. /**
  63526. * Gets if the current filter is set to VSM.
  63527. * DEPRECATED. Should use useExponentialShadowMap instead.
  63528. */
  63529. get: function () {
  63530. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  63531. return this.useExponentialShadowMap;
  63532. },
  63533. /**
  63534. * Sets the current filter is to VSM.
  63535. * DEPRECATED. Should use useExponentialShadowMap instead.
  63536. */
  63537. set: function (value) {
  63538. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  63539. this.useExponentialShadowMap = value;
  63540. },
  63541. enumerable: true,
  63542. configurable: true
  63543. });
  63544. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  63545. /**
  63546. * Gets if the current filter is set to blurred VSM.
  63547. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  63548. */
  63549. get: function () {
  63550. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  63551. return this.useBlurExponentialShadowMap;
  63552. },
  63553. /**
  63554. * Sets the current filter is to blurred VSM.
  63555. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  63556. */
  63557. set: function (value) {
  63558. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  63559. this.useBlurExponentialShadowMap = value;
  63560. },
  63561. enumerable: true,
  63562. configurable: true
  63563. });
  63564. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  63565. /**
  63566. * Gets if the current filter is set to ESM.
  63567. */
  63568. get: function () {
  63569. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  63570. },
  63571. /**
  63572. * Sets the current filter is to ESM.
  63573. */
  63574. set: function (value) {
  63575. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  63576. return;
  63577. }
  63578. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63579. },
  63580. enumerable: true,
  63581. configurable: true
  63582. });
  63583. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  63584. /**
  63585. * Gets if the current filter is set to filtered ESM.
  63586. */
  63587. get: function () {
  63588. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  63589. },
  63590. /**
  63591. * Gets if the current filter is set to filtered ESM.
  63592. */
  63593. set: function (value) {
  63594. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  63595. return;
  63596. }
  63597. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63598. },
  63599. enumerable: true,
  63600. configurable: true
  63601. });
  63602. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  63603. /**
  63604. * Gets if the current filter is set to "close ESM" (using the inverse of the
  63605. * exponential to prevent steep falloff artifacts).
  63606. */
  63607. get: function () {
  63608. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  63609. },
  63610. /**
  63611. * Sets the current filter to "close ESM" (using the inverse of the
  63612. * exponential to prevent steep falloff artifacts).
  63613. */
  63614. set: function (value) {
  63615. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  63616. return;
  63617. }
  63618. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63619. },
  63620. enumerable: true,
  63621. configurable: true
  63622. });
  63623. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  63624. /**
  63625. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  63626. * exponential to prevent steep falloff artifacts).
  63627. */
  63628. get: function () {
  63629. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  63630. },
  63631. /**
  63632. * Sets the current filter to filtered "close ESM" (using the inverse of the
  63633. * exponential to prevent steep falloff artifacts).
  63634. */
  63635. set: function (value) {
  63636. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  63637. return;
  63638. }
  63639. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  63640. },
  63641. enumerable: true,
  63642. configurable: true
  63643. });
  63644. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  63645. /**
  63646. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  63647. */
  63648. get: function () {
  63649. return this.filter === ShadowGenerator.FILTER_PCF;
  63650. },
  63651. /**
  63652. * Sets the current filter to "PCF" (percentage closer filtering).
  63653. */
  63654. set: function (value) {
  63655. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  63656. return;
  63657. }
  63658. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  63659. },
  63660. enumerable: true,
  63661. configurable: true
  63662. });
  63663. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  63664. /**
  63665. * Gets the PCF or PCSS Quality.
  63666. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  63667. */
  63668. get: function () {
  63669. return this._filteringQuality;
  63670. },
  63671. /**
  63672. * Sets the PCF or PCSS Quality.
  63673. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  63674. */
  63675. set: function (filteringQuality) {
  63676. this._filteringQuality = filteringQuality;
  63677. },
  63678. enumerable: true,
  63679. configurable: true
  63680. });
  63681. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  63682. /**
  63683. * Gets if the current filter is set to "PCSS" (contact hardening).
  63684. */
  63685. get: function () {
  63686. return this.filter === ShadowGenerator.FILTER_PCSS;
  63687. },
  63688. /**
  63689. * Sets the current filter to "PCSS" (contact hardening).
  63690. */
  63691. set: function (value) {
  63692. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  63693. return;
  63694. }
  63695. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  63696. },
  63697. enumerable: true,
  63698. configurable: true
  63699. });
  63700. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  63701. /**
  63702. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  63703. * Using a ratio helps keeping shape stability independently of the map size.
  63704. *
  63705. * It does not account for the light projection as it was having too much
  63706. * instability during the light setup or during light position changes.
  63707. *
  63708. * Only valid if useContactHardeningShadow is true.
  63709. */
  63710. get: function () {
  63711. return this._contactHardeningLightSizeUVRatio;
  63712. },
  63713. /**
  63714. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  63715. * Using a ratio helps keeping shape stability independently of the map size.
  63716. *
  63717. * It does not account for the light projection as it was having too much
  63718. * instability during the light setup or during light position changes.
  63719. *
  63720. * Only valid if useContactHardeningShadow is true.
  63721. */
  63722. set: function (contactHardeningLightSizeUVRatio) {
  63723. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  63724. },
  63725. enumerable: true,
  63726. configurable: true
  63727. });
  63728. /**
  63729. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  63730. * 0 means strongest and 1 would means no shadow.
  63731. * @returns the darkness.
  63732. */
  63733. ShadowGenerator.prototype.getDarkness = function () {
  63734. return this._darkness;
  63735. };
  63736. /**
  63737. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  63738. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  63739. * @returns the shadow generator allowing fluent coding.
  63740. */
  63741. ShadowGenerator.prototype.setDarkness = function (darkness) {
  63742. if (darkness >= 1.0)
  63743. this._darkness = 1.0;
  63744. else if (darkness <= 0.0)
  63745. this._darkness = 0.0;
  63746. else
  63747. this._darkness = darkness;
  63748. return this;
  63749. };
  63750. /**
  63751. * Sets the ability to have transparent shadow (boolean).
  63752. * @param transparent True if transparent else False
  63753. * @returns the shadow generator allowing fluent coding
  63754. */
  63755. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  63756. this._transparencyShadow = transparent;
  63757. return this;
  63758. };
  63759. /**
  63760. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  63761. * @returns The render target texture if present otherwise, null
  63762. */
  63763. ShadowGenerator.prototype.getShadowMap = function () {
  63764. return this._shadowMap;
  63765. };
  63766. /**
  63767. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  63768. * @returns The render target texture if the shadow map is present otherwise, null
  63769. */
  63770. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  63771. if (this._shadowMap2) {
  63772. return this._shadowMap2;
  63773. }
  63774. return this._shadowMap;
  63775. };
  63776. /**
  63777. * Helper function to add a mesh and its descendants to the list of shadow casters.
  63778. * @param mesh Mesh to add
  63779. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  63780. * @returns the Shadow Generator itself
  63781. */
  63782. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  63783. if (includeDescendants === void 0) { includeDescendants = true; }
  63784. if (!this._shadowMap) {
  63785. return this;
  63786. }
  63787. if (!this._shadowMap.renderList) {
  63788. this._shadowMap.renderList = [];
  63789. }
  63790. this._shadowMap.renderList.push(mesh);
  63791. if (includeDescendants) {
  63792. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  63793. }
  63794. return this;
  63795. var _a;
  63796. };
  63797. /**
  63798. * Helper function to remove a mesh and its descendants from the list of shadow casters
  63799. * @param mesh Mesh to remove
  63800. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  63801. * @returns the Shadow Generator itself
  63802. */
  63803. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  63804. if (includeDescendants === void 0) { includeDescendants = true; }
  63805. if (!this._shadowMap || !this._shadowMap.renderList) {
  63806. return this;
  63807. }
  63808. var index = this._shadowMap.renderList.indexOf(mesh);
  63809. if (index !== -1) {
  63810. this._shadowMap.renderList.splice(index, 1);
  63811. }
  63812. if (includeDescendants) {
  63813. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  63814. var child = _a[_i];
  63815. this.removeShadowCaster(child);
  63816. }
  63817. }
  63818. return this;
  63819. };
  63820. /**
  63821. * Returns the associated light object.
  63822. * @returns the light generating the shadow
  63823. */
  63824. ShadowGenerator.prototype.getLight = function () {
  63825. return this._light;
  63826. };
  63827. ShadowGenerator.prototype._initializeGenerator = function () {
  63828. this._light._markMeshesAsLightDirty();
  63829. this._initializeShadowMap();
  63830. };
  63831. ShadowGenerator.prototype._initializeShadowMap = function () {
  63832. var _this = this;
  63833. // Render target
  63834. var engine = this._scene.getEngine();
  63835. if (engine.webGLVersion > 1) {
  63836. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  63837. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  63838. }
  63839. else {
  63840. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  63841. }
  63842. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63843. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63844. this._shadowMap.anisotropicFilteringLevel = 1;
  63845. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63846. this._shadowMap.renderParticles = false;
  63847. this._shadowMap.ignoreCameraViewport = true;
  63848. // Record Face Index before render.
  63849. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  63850. _this._currentFaceIndex = faceIndex;
  63851. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63852. engine.setColorWrite(false);
  63853. }
  63854. });
  63855. // Custom render function.
  63856. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  63857. // Blur if required afer render.
  63858. this._shadowMap.onAfterUnbindObservable.add(function () {
  63859. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63860. engine.setColorWrite(true);
  63861. }
  63862. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  63863. return;
  63864. }
  63865. var shadowMap = _this.getShadowMapForRendering();
  63866. if (shadowMap) {
  63867. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  63868. }
  63869. });
  63870. // Clear according to the chosen filter.
  63871. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  63872. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  63873. this._shadowMap.onClearObservable.add(function (engine) {
  63874. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  63875. engine.clear(clearOne, false, true, false);
  63876. }
  63877. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  63878. engine.clear(clearZero, true, true, false);
  63879. }
  63880. else {
  63881. engine.clear(clearOne, true, true, false);
  63882. }
  63883. });
  63884. };
  63885. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  63886. var _this = this;
  63887. var engine = this._scene.getEngine();
  63888. var targetSize = this._mapSize / this.blurScale;
  63889. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  63890. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  63891. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63892. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63893. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63894. }
  63895. if (this.useKernelBlur) {
  63896. 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);
  63897. this._kernelBlurXPostprocess.width = targetSize;
  63898. this._kernelBlurXPostprocess.height = targetSize;
  63899. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  63900. effect.setTexture("textureSampler", _this._shadowMap);
  63901. });
  63902. 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);
  63903. this._kernelBlurXPostprocess.autoClear = false;
  63904. this._kernelBlurYPostprocess.autoClear = false;
  63905. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63906. this._kernelBlurXPostprocess.packedFloat = true;
  63907. this._kernelBlurYPostprocess.packedFloat = true;
  63908. }
  63909. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  63910. }
  63911. else {
  63912. 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);
  63913. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  63914. effect.setFloat2("screenSize", targetSize, targetSize);
  63915. effect.setTexture("textureSampler", _this._shadowMap);
  63916. });
  63917. this._boxBlurPostprocess.autoClear = false;
  63918. this._blurPostProcesses = [this._boxBlurPostprocess];
  63919. }
  63920. };
  63921. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63922. var index;
  63923. var engine = this._scene.getEngine();
  63924. if (depthOnlySubMeshes.length) {
  63925. engine.setColorWrite(false);
  63926. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63927. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  63928. }
  63929. engine.setColorWrite(true);
  63930. }
  63931. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63932. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  63933. }
  63934. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63935. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  63936. }
  63937. if (this._transparencyShadow) {
  63938. for (index = 0; index < transparentSubMeshes.length; index++) {
  63939. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  63940. }
  63941. }
  63942. };
  63943. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  63944. var _this = this;
  63945. var mesh = subMesh.getRenderingMesh();
  63946. var scene = this._scene;
  63947. var engine = scene.getEngine();
  63948. var material = subMesh.getMaterial();
  63949. if (!material) {
  63950. return;
  63951. }
  63952. // Culling
  63953. engine.setState(material.backFaceCulling);
  63954. // Managing instances
  63955. var batch = mesh._getInstancesRenderList(subMesh._id);
  63956. if (batch.mustReturn) {
  63957. return;
  63958. }
  63959. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  63960. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  63961. engine.enableEffect(this._effect);
  63962. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  63963. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  63964. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  63965. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  63966. this._effect.setVector3("lightData", this._cachedDirection);
  63967. }
  63968. else {
  63969. this._effect.setVector3("lightData", this._cachedPosition);
  63970. }
  63971. if (scene.activeCamera) {
  63972. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  63973. }
  63974. // Alpha test
  63975. if (material && material.needAlphaTesting()) {
  63976. var alphaTexture = material.getAlphaTestTexture();
  63977. if (alphaTexture) {
  63978. this._effect.setTexture("diffuseSampler", alphaTexture);
  63979. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  63980. }
  63981. }
  63982. // Bones
  63983. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63984. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  63985. }
  63986. // Morph targets
  63987. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  63988. if (this.forceBackFacesOnly) {
  63989. engine.setState(true, 0, false, true);
  63990. }
  63991. // Draw
  63992. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  63993. if (this.forceBackFacesOnly) {
  63994. engine.setState(true, 0, false, false);
  63995. }
  63996. }
  63997. else {
  63998. // Need to reset refresh rate of the shadowMap
  63999. if (this._shadowMap) {
  64000. this._shadowMap.resetRefreshCounter();
  64001. }
  64002. }
  64003. };
  64004. ShadowGenerator.prototype._applyFilterValues = function () {
  64005. if (!this._shadowMap) {
  64006. return;
  64007. }
  64008. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  64009. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64010. }
  64011. else {
  64012. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64013. }
  64014. };
  64015. /**
  64016. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64017. * @param onCompiled Callback triggered at the and of the effects compilation
  64018. * @param options Sets of optional options forcing the compilation with different modes
  64019. */
  64020. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  64021. var _this = this;
  64022. var localOptions = __assign({ useInstances: false }, options);
  64023. var shadowMap = this.getShadowMap();
  64024. if (!shadowMap) {
  64025. if (onCompiled) {
  64026. onCompiled(this);
  64027. }
  64028. return;
  64029. }
  64030. var renderList = shadowMap.renderList;
  64031. if (!renderList) {
  64032. if (onCompiled) {
  64033. onCompiled(this);
  64034. }
  64035. return;
  64036. }
  64037. var subMeshes = new Array();
  64038. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  64039. var mesh = renderList_1[_i];
  64040. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  64041. }
  64042. if (subMeshes.length === 0) {
  64043. if (onCompiled) {
  64044. onCompiled(this);
  64045. }
  64046. return;
  64047. }
  64048. var currentIndex = 0;
  64049. var checkReady = function () {
  64050. if (!_this._scene || !_this._scene.getEngine()) {
  64051. return;
  64052. }
  64053. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  64054. currentIndex++;
  64055. if (currentIndex >= subMeshes.length) {
  64056. if (onCompiled) {
  64057. onCompiled(_this);
  64058. }
  64059. return;
  64060. }
  64061. }
  64062. setTimeout(checkReady, 16);
  64063. };
  64064. checkReady();
  64065. };
  64066. /**
  64067. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64068. * @param options Sets of optional options forcing the compilation with different modes
  64069. * @returns A promise that resolves when the compilation completes
  64070. */
  64071. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  64072. var _this = this;
  64073. return new Promise(function (resolve) {
  64074. _this.forceCompilation(function () {
  64075. resolve();
  64076. }, options);
  64077. });
  64078. };
  64079. /**
  64080. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  64081. * @param subMesh The submesh we want to render in the shadow map
  64082. * @param useInstances Defines wether will draw in the map using instances
  64083. * @returns true if ready otherwise, false
  64084. */
  64085. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  64086. var defines = [];
  64087. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64088. defines.push("#define FLOAT");
  64089. }
  64090. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64091. defines.push("#define ESM");
  64092. }
  64093. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  64094. defines.push("#define DEPTHTEXTURE");
  64095. }
  64096. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64097. var mesh = subMesh.getMesh();
  64098. var material = subMesh.getMaterial();
  64099. // Normal bias.
  64100. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64101. attribs.push(BABYLON.VertexBuffer.NormalKind);
  64102. defines.push("#define NORMAL");
  64103. if (mesh.nonUniformScaling) {
  64104. defines.push("#define NONUNIFORMSCALING");
  64105. }
  64106. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64107. defines.push("#define DIRECTIONINLIGHTDATA");
  64108. }
  64109. }
  64110. // Alpha test
  64111. if (material && material.needAlphaTesting()) {
  64112. var alphaTexture = material.getAlphaTestTexture();
  64113. if (alphaTexture) {
  64114. defines.push("#define ALPHATEST");
  64115. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64116. attribs.push(BABYLON.VertexBuffer.UVKind);
  64117. defines.push("#define UV1");
  64118. }
  64119. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64120. if (alphaTexture.coordinatesIndex === 1) {
  64121. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64122. defines.push("#define UV2");
  64123. }
  64124. }
  64125. }
  64126. }
  64127. // Bones
  64128. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64129. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64130. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64131. if (mesh.numBoneInfluencers > 4) {
  64132. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64133. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64134. }
  64135. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64136. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64137. }
  64138. else {
  64139. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64140. }
  64141. // Morph targets
  64142. var manager = mesh.morphTargetManager;
  64143. var morphInfluencers = 0;
  64144. if (manager) {
  64145. if (manager.numInfluencers > 0) {
  64146. defines.push("#define MORPHTARGETS");
  64147. morphInfluencers = manager.numInfluencers;
  64148. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  64149. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  64150. }
  64151. }
  64152. // Instances
  64153. if (useInstances) {
  64154. defines.push("#define INSTANCES");
  64155. attribs.push("world0");
  64156. attribs.push("world1");
  64157. attribs.push("world2");
  64158. attribs.push("world3");
  64159. }
  64160. // Get correct effect
  64161. var join = defines.join("\n");
  64162. if (this._cachedDefines !== join) {
  64163. this._cachedDefines = join;
  64164. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  64165. }
  64166. if (!this._effect.isReady()) {
  64167. return false;
  64168. }
  64169. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64170. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  64171. this._initializeBlurRTTAndPostProcesses();
  64172. }
  64173. }
  64174. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  64175. return false;
  64176. }
  64177. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  64178. return false;
  64179. }
  64180. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  64181. return false;
  64182. }
  64183. return true;
  64184. };
  64185. /**
  64186. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  64187. * @param defines Defines of the material we want to update
  64188. * @param lightIndex Index of the light in the enabled light list of the material
  64189. */
  64190. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  64191. var scene = this._scene;
  64192. var light = this._light;
  64193. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64194. return;
  64195. }
  64196. defines["SHADOW" + lightIndex] = true;
  64197. if (this.useContactHardeningShadow) {
  64198. defines["SHADOWPCSS" + lightIndex] = true;
  64199. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64200. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64201. }
  64202. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64203. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64204. }
  64205. // else default to high.
  64206. }
  64207. if (this.usePercentageCloserFiltering) {
  64208. defines["SHADOWPCF" + lightIndex] = true;
  64209. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64210. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64211. }
  64212. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64213. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64214. }
  64215. // else default to high.
  64216. }
  64217. else if (this.usePoissonSampling) {
  64218. defines["SHADOWPOISSON" + lightIndex] = true;
  64219. }
  64220. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64221. defines["SHADOWESM" + lightIndex] = true;
  64222. }
  64223. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64224. defines["SHADOWCLOSEESM" + lightIndex] = true;
  64225. }
  64226. if (light.needCube()) {
  64227. defines["SHADOWCUBE" + lightIndex] = true;
  64228. }
  64229. };
  64230. /**
  64231. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  64232. * defined in the generator but impacting the effect).
  64233. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  64234. * @param effect The effect we are binfing the information for
  64235. */
  64236. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  64237. var light = this._light;
  64238. var scene = this._scene;
  64239. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64240. return;
  64241. }
  64242. var camera = scene.activeCamera;
  64243. if (!camera) {
  64244. return;
  64245. }
  64246. var shadowMap = this.getShadowMap();
  64247. if (!shadowMap) {
  64248. return;
  64249. }
  64250. if (!light.needCube()) {
  64251. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  64252. }
  64253. // Only PCF uses depth stencil texture.
  64254. if (this._filter === ShadowGenerator.FILTER_PCF) {
  64255. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64256. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64257. }
  64258. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  64259. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64260. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  64261. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64262. }
  64263. else {
  64264. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64265. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  64266. }
  64267. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  64268. };
  64269. /**
  64270. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  64271. * (eq to shadow prjection matrix * light transform matrix)
  64272. * @returns The transform matrix used to create the shadow map
  64273. */
  64274. ShadowGenerator.prototype.getTransformMatrix = function () {
  64275. var scene = this._scene;
  64276. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  64277. return this._transformMatrix;
  64278. }
  64279. this._currentRenderID = scene.getRenderId();
  64280. this._currentFaceIndexCache = this._currentFaceIndex;
  64281. var lightPosition = this._light.position;
  64282. if (this._light.computeTransformedInformation()) {
  64283. lightPosition = this._light.transformedPosition;
  64284. }
  64285. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  64286. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  64287. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  64288. }
  64289. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  64290. this._cachedPosition.copyFrom(lightPosition);
  64291. this._cachedDirection.copyFrom(this._lightDirection);
  64292. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  64293. var shadowMap = this.getShadowMap();
  64294. if (shadowMap) {
  64295. var renderList = shadowMap.renderList;
  64296. if (renderList) {
  64297. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  64298. }
  64299. }
  64300. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  64301. }
  64302. return this._transformMatrix;
  64303. };
  64304. /**
  64305. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  64306. * Cube and 2D textures for instance.
  64307. */
  64308. ShadowGenerator.prototype.recreateShadowMap = function () {
  64309. var shadowMap = this._shadowMap;
  64310. if (!shadowMap) {
  64311. return;
  64312. }
  64313. // Track render list.
  64314. var renderList = shadowMap.renderList;
  64315. // Clean up existing data.
  64316. this._disposeRTTandPostProcesses();
  64317. // Reinitializes.
  64318. this._initializeGenerator();
  64319. // Reaffect the filter to ensure a correct fallback if necessary.
  64320. this.filter = this.filter;
  64321. // Reaffect the filter.
  64322. this._applyFilterValues();
  64323. // Reaffect Render List.
  64324. this._shadowMap.renderList = renderList;
  64325. };
  64326. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  64327. if (this._shadowMap2) {
  64328. this._shadowMap2.dispose();
  64329. this._shadowMap2 = null;
  64330. }
  64331. if (this._boxBlurPostprocess) {
  64332. this._boxBlurPostprocess.dispose();
  64333. this._boxBlurPostprocess = null;
  64334. }
  64335. if (this._kernelBlurXPostprocess) {
  64336. this._kernelBlurXPostprocess.dispose();
  64337. this._kernelBlurXPostprocess = null;
  64338. }
  64339. if (this._kernelBlurYPostprocess) {
  64340. this._kernelBlurYPostprocess.dispose();
  64341. this._kernelBlurYPostprocess = null;
  64342. }
  64343. this._blurPostProcesses = [];
  64344. };
  64345. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  64346. if (this._shadowMap) {
  64347. this._shadowMap.dispose();
  64348. this._shadowMap = null;
  64349. }
  64350. this._disposeBlurPostProcesses();
  64351. };
  64352. /**
  64353. * Disposes the ShadowGenerator.
  64354. * Returns nothing.
  64355. */
  64356. ShadowGenerator.prototype.dispose = function () {
  64357. this._disposeRTTandPostProcesses();
  64358. if (this._light) {
  64359. this._light._shadowGenerator = null;
  64360. this._light._markMeshesAsLightDirty();
  64361. }
  64362. };
  64363. /**
  64364. * Serializes the shadow generator setup to a json object.
  64365. * @returns The serialized JSON object
  64366. */
  64367. ShadowGenerator.prototype.serialize = function () {
  64368. var serializationObject = {};
  64369. var shadowMap = this.getShadowMap();
  64370. if (!shadowMap) {
  64371. return serializationObject;
  64372. }
  64373. serializationObject.lightId = this._light.id;
  64374. serializationObject.mapSize = shadowMap.getRenderSize();
  64375. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  64376. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  64377. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64378. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64379. serializationObject.usePoissonSampling = this.usePoissonSampling;
  64380. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  64381. serializationObject.depthScale = this.depthScale;
  64382. serializationObject.darkness = this.getDarkness();
  64383. serializationObject.blurBoxOffset = this.blurBoxOffset;
  64384. serializationObject.blurKernel = this.blurKernel;
  64385. serializationObject.blurScale = this.blurScale;
  64386. serializationObject.useKernelBlur = this.useKernelBlur;
  64387. serializationObject.transparencyShadow = this._transparencyShadow;
  64388. serializationObject.bias = this.bias;
  64389. serializationObject.normalBias = this.normalBias;
  64390. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  64391. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  64392. serializationObject.filteringQuality = this.filteringQuality;
  64393. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  64394. serializationObject.renderList = [];
  64395. if (shadowMap.renderList) {
  64396. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  64397. var mesh = shadowMap.renderList[meshIndex];
  64398. serializationObject.renderList.push(mesh.id);
  64399. }
  64400. }
  64401. return serializationObject;
  64402. };
  64403. /**
  64404. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  64405. * @param parsedShadowGenerator The JSON object to parse
  64406. * @param scene The scene to create the shadow map for
  64407. * @returns The parsed shadow generator
  64408. */
  64409. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  64410. //casting to point light, as light is missing the position attr and typescript complains.
  64411. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  64412. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  64413. var shadowMap = shadowGenerator.getShadowMap();
  64414. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  64415. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  64416. meshes.forEach(function (mesh) {
  64417. if (!shadowMap) {
  64418. return;
  64419. }
  64420. if (!shadowMap.renderList) {
  64421. shadowMap.renderList = [];
  64422. }
  64423. shadowMap.renderList.push(mesh);
  64424. });
  64425. }
  64426. if (parsedShadowGenerator.usePoissonSampling) {
  64427. shadowGenerator.usePoissonSampling = true;
  64428. }
  64429. else if (parsedShadowGenerator.useExponentialShadowMap) {
  64430. shadowGenerator.useExponentialShadowMap = true;
  64431. }
  64432. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  64433. shadowGenerator.useBlurExponentialShadowMap = true;
  64434. }
  64435. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  64436. shadowGenerator.useCloseExponentialShadowMap = true;
  64437. }
  64438. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  64439. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  64440. }
  64441. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  64442. shadowGenerator.usePercentageCloserFiltering = true;
  64443. }
  64444. else if (parsedShadowGenerator.useContactHardeningShadow) {
  64445. shadowGenerator.useContactHardeningShadow = true;
  64446. }
  64447. if (parsedShadowGenerator.filteringQuality) {
  64448. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  64449. }
  64450. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  64451. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  64452. }
  64453. else if (parsedShadowGenerator.useVarianceShadowMap) {
  64454. shadowGenerator.useExponentialShadowMap = true;
  64455. }
  64456. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  64457. shadowGenerator.useBlurExponentialShadowMap = true;
  64458. }
  64459. if (parsedShadowGenerator.depthScale) {
  64460. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  64461. }
  64462. if (parsedShadowGenerator.blurScale) {
  64463. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  64464. }
  64465. if (parsedShadowGenerator.blurBoxOffset) {
  64466. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  64467. }
  64468. if (parsedShadowGenerator.useKernelBlur) {
  64469. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  64470. }
  64471. if (parsedShadowGenerator.blurKernel) {
  64472. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  64473. }
  64474. if (parsedShadowGenerator.bias !== undefined) {
  64475. shadowGenerator.bias = parsedShadowGenerator.bias;
  64476. }
  64477. if (parsedShadowGenerator.normalBias !== undefined) {
  64478. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  64479. }
  64480. if (parsedShadowGenerator.darkness) {
  64481. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  64482. }
  64483. if (parsedShadowGenerator.transparencyShadow) {
  64484. shadowGenerator.setTransparencyShadow(true);
  64485. }
  64486. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  64487. return shadowGenerator;
  64488. };
  64489. /**
  64490. * Shadow generator mode None: no filtering applied.
  64491. */
  64492. ShadowGenerator.FILTER_NONE = 0;
  64493. /**
  64494. * Shadow generator mode ESM: Exponential Shadow Mapping.
  64495. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64496. */
  64497. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  64498. /**
  64499. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  64500. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  64501. */
  64502. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  64503. /**
  64504. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  64505. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64506. */
  64507. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  64508. /**
  64509. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  64510. * edge artifacts on steep falloff.
  64511. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64512. */
  64513. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  64514. /**
  64515. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  64516. * edge artifacts on steep falloff.
  64517. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  64518. */
  64519. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  64520. /**
  64521. * Shadow generator mode PCF: Percentage Closer Filtering
  64522. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  64523. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  64524. */
  64525. ShadowGenerator.FILTER_PCF = 6;
  64526. /**
  64527. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  64528. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  64529. * Contact Hardening
  64530. */
  64531. ShadowGenerator.FILTER_PCSS = 7;
  64532. /**
  64533. * Reserved for PCF and PCSS
  64534. * Highest Quality.
  64535. *
  64536. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  64537. *
  64538. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  64539. */
  64540. ShadowGenerator.QUALITY_HIGH = 0;
  64541. /**
  64542. * Reserved for PCF and PCSS
  64543. * Good tradeoff for quality/perf cross devices
  64544. *
  64545. * Execute PCF on a 3*3 kernel.
  64546. *
  64547. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  64548. */
  64549. ShadowGenerator.QUALITY_MEDIUM = 1;
  64550. /**
  64551. * Reserved for PCF and PCSS
  64552. * The lowest quality but the fastest.
  64553. *
  64554. * Execute PCF on a 1*1 kernel.
  64555. *
  64556. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  64557. */
  64558. ShadowGenerator.QUALITY_LOW = 2;
  64559. return ShadowGenerator;
  64560. }());
  64561. BABYLON.ShadowGenerator = ShadowGenerator;
  64562. })(BABYLON || (BABYLON = {}));
  64563. //# sourceMappingURL=babylon.shadowGenerator.js.map
  64564. "use strict";
  64565. var BABYLON;
  64566. (function (BABYLON) {
  64567. var DefaultLoadingScreen = /** @class */ (function () {
  64568. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  64569. if (_loadingText === void 0) { _loadingText = ""; }
  64570. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  64571. var _this = this;
  64572. this._renderingCanvas = _renderingCanvas;
  64573. this._loadingText = _loadingText;
  64574. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  64575. // Resize
  64576. this._resizeLoadingUI = function () {
  64577. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  64578. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  64579. if (!_this._loadingDiv) {
  64580. return;
  64581. }
  64582. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  64583. _this._loadingDiv.style.left = canvasRect.left + "px";
  64584. _this._loadingDiv.style.top = canvasRect.top + "px";
  64585. _this._loadingDiv.style.width = canvasRect.width + "px";
  64586. _this._loadingDiv.style.height = canvasRect.height + "px";
  64587. };
  64588. }
  64589. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  64590. if (this._loadingDiv) {
  64591. // Do not add a loading screen if there is already one
  64592. return;
  64593. }
  64594. this._loadingDiv = document.createElement("div");
  64595. this._loadingDiv.id = "babylonjsLoadingDiv";
  64596. this._loadingDiv.style.opacity = "0";
  64597. this._loadingDiv.style.transition = "opacity 1.5s ease";
  64598. this._loadingDiv.style.pointerEvents = "none";
  64599. // Loading text
  64600. this._loadingTextDiv = document.createElement("div");
  64601. this._loadingTextDiv.style.position = "absolute";
  64602. this._loadingTextDiv.style.left = "0";
  64603. this._loadingTextDiv.style.top = "50%";
  64604. this._loadingTextDiv.style.marginTop = "80px";
  64605. this._loadingTextDiv.style.width = "100%";
  64606. this._loadingTextDiv.style.height = "20px";
  64607. this._loadingTextDiv.style.fontFamily = "Arial";
  64608. this._loadingTextDiv.style.fontSize = "14px";
  64609. this._loadingTextDiv.style.color = "white";
  64610. this._loadingTextDiv.style.textAlign = "center";
  64611. this._loadingTextDiv.innerHTML = "Loading";
  64612. this._loadingDiv.appendChild(this._loadingTextDiv);
  64613. //set the predefined text
  64614. this._loadingTextDiv.innerHTML = this._loadingText;
  64615. // Generating keyframes
  64616. var style = document.createElement('style');
  64617. style.type = 'text/css';
  64618. 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 }";
  64619. style.innerHTML = keyFrames;
  64620. document.getElementsByTagName('head')[0].appendChild(style);
  64621. // Loading img
  64622. var imgBack = new Image();
  64623. 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";
  64624. imgBack.style.position = "absolute";
  64625. imgBack.style.left = "50%";
  64626. imgBack.style.top = "50%";
  64627. imgBack.style.marginLeft = "-60px";
  64628. imgBack.style.marginTop = "-60px";
  64629. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  64630. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  64631. imgBack.style.transformOrigin = "50% 50%";
  64632. imgBack.style.webkitTransformOrigin = "50% 50%";
  64633. this._loadingDiv.appendChild(imgBack);
  64634. this._resizeLoadingUI();
  64635. window.addEventListener("resize", this._resizeLoadingUI);
  64636. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  64637. document.body.appendChild(this._loadingDiv);
  64638. this._loadingDiv.style.opacity = "1";
  64639. };
  64640. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  64641. var _this = this;
  64642. if (!this._loadingDiv) {
  64643. return;
  64644. }
  64645. var onTransitionEnd = function () {
  64646. if (!_this._loadingDiv) {
  64647. return;
  64648. }
  64649. document.body.removeChild(_this._loadingDiv);
  64650. window.removeEventListener("resize", _this._resizeLoadingUI);
  64651. _this._loadingDiv = null;
  64652. };
  64653. this._loadingDiv.style.opacity = "0";
  64654. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  64655. };
  64656. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  64657. set: function (text) {
  64658. this._loadingText = text;
  64659. if (this._loadingTextDiv) {
  64660. this._loadingTextDiv.innerHTML = this._loadingText;
  64661. }
  64662. },
  64663. enumerable: true,
  64664. configurable: true
  64665. });
  64666. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  64667. get: function () {
  64668. return this._loadingDivBackgroundColor;
  64669. },
  64670. set: function (color) {
  64671. this._loadingDivBackgroundColor = color;
  64672. if (!this._loadingDiv) {
  64673. return;
  64674. }
  64675. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  64676. },
  64677. enumerable: true,
  64678. configurable: true
  64679. });
  64680. return DefaultLoadingScreen;
  64681. }());
  64682. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  64683. })(BABYLON || (BABYLON = {}));
  64684. //# sourceMappingURL=babylon.loadingScreen.js.map
  64685. "use strict";
  64686. var BABYLON;
  64687. (function (BABYLON) {
  64688. var SceneLoaderProgressEvent = /** @class */ (function () {
  64689. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  64690. this.lengthComputable = lengthComputable;
  64691. this.loaded = loaded;
  64692. this.total = total;
  64693. }
  64694. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  64695. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  64696. };
  64697. return SceneLoaderProgressEvent;
  64698. }());
  64699. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  64700. var SceneLoader = /** @class */ (function () {
  64701. function SceneLoader() {
  64702. }
  64703. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  64704. get: function () {
  64705. return 0;
  64706. },
  64707. enumerable: true,
  64708. configurable: true
  64709. });
  64710. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  64711. get: function () {
  64712. return 1;
  64713. },
  64714. enumerable: true,
  64715. configurable: true
  64716. });
  64717. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  64718. get: function () {
  64719. return 2;
  64720. },
  64721. enumerable: true,
  64722. configurable: true
  64723. });
  64724. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  64725. get: function () {
  64726. return 3;
  64727. },
  64728. enumerable: true,
  64729. configurable: true
  64730. });
  64731. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  64732. get: function () {
  64733. return SceneLoader._ForceFullSceneLoadingForIncremental;
  64734. },
  64735. set: function (value) {
  64736. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  64737. },
  64738. enumerable: true,
  64739. configurable: true
  64740. });
  64741. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  64742. get: function () {
  64743. return SceneLoader._ShowLoadingScreen;
  64744. },
  64745. set: function (value) {
  64746. SceneLoader._ShowLoadingScreen = value;
  64747. },
  64748. enumerable: true,
  64749. configurable: true
  64750. });
  64751. Object.defineProperty(SceneLoader, "loggingLevel", {
  64752. get: function () {
  64753. return SceneLoader._loggingLevel;
  64754. },
  64755. set: function (value) {
  64756. SceneLoader._loggingLevel = value;
  64757. },
  64758. enumerable: true,
  64759. configurable: true
  64760. });
  64761. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  64762. get: function () {
  64763. return SceneLoader._CleanBoneMatrixWeights;
  64764. },
  64765. set: function (value) {
  64766. SceneLoader._CleanBoneMatrixWeights = value;
  64767. },
  64768. enumerable: true,
  64769. configurable: true
  64770. });
  64771. SceneLoader._getDefaultPlugin = function () {
  64772. return SceneLoader._registeredPlugins[".babylon"];
  64773. };
  64774. SceneLoader._getPluginForExtension = function (extension) {
  64775. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  64776. if (registeredPlugin) {
  64777. return registeredPlugin;
  64778. }
  64779. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  64780. return SceneLoader._getDefaultPlugin();
  64781. };
  64782. SceneLoader._getPluginForDirectLoad = function (data) {
  64783. for (var extension in SceneLoader._registeredPlugins) {
  64784. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  64785. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  64786. return SceneLoader._registeredPlugins[extension];
  64787. }
  64788. }
  64789. return SceneLoader._getDefaultPlugin();
  64790. };
  64791. SceneLoader._getPluginForFilename = function (sceneFilename) {
  64792. if (sceneFilename.name) {
  64793. sceneFilename = sceneFilename.name;
  64794. }
  64795. var queryStringPosition = sceneFilename.indexOf("?");
  64796. if (queryStringPosition !== -1) {
  64797. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  64798. }
  64799. var dotPosition = sceneFilename.lastIndexOf(".");
  64800. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  64801. return SceneLoader._getPluginForExtension(extension);
  64802. };
  64803. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  64804. SceneLoader._getDirectLoad = function (sceneFilename) {
  64805. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  64806. return sceneFilename.substr(5);
  64807. }
  64808. return null;
  64809. };
  64810. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  64811. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  64812. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  64813. var plugin;
  64814. if (registeredPlugin.plugin.createPlugin) {
  64815. plugin = registeredPlugin.plugin.createPlugin();
  64816. }
  64817. else {
  64818. plugin = registeredPlugin.plugin;
  64819. }
  64820. var useArrayBuffer = registeredPlugin.isBinary;
  64821. var database;
  64822. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  64823. var dataCallback = function (data, responseURL) {
  64824. if (scene.isDisposed) {
  64825. onError("Scene has been disposed");
  64826. return;
  64827. }
  64828. scene.database = database;
  64829. onSuccess(plugin, data, responseURL);
  64830. };
  64831. var request = null;
  64832. var pluginDisposed = false;
  64833. var onDisposeObservable = plugin.onDisposeObservable;
  64834. if (onDisposeObservable) {
  64835. onDisposeObservable.add(function () {
  64836. pluginDisposed = true;
  64837. if (request) {
  64838. request.abort();
  64839. request = null;
  64840. }
  64841. onDispose();
  64842. });
  64843. }
  64844. var manifestChecked = function () {
  64845. if (pluginDisposed) {
  64846. return;
  64847. }
  64848. var url = rootUrl + sceneFilename;
  64849. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  64850. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  64851. } : undefined, database, useArrayBuffer, function (request, exception) {
  64852. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  64853. });
  64854. };
  64855. if (directLoad) {
  64856. dataCallback(directLoad);
  64857. return plugin;
  64858. }
  64859. if (rootUrl.indexOf("file:") === -1) {
  64860. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  64861. if (canUseOfflineSupport) {
  64862. // Also check for exceptions
  64863. var exceptionFound = false;
  64864. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  64865. var regex = _a[_i];
  64866. if (regex.test(rootUrl + sceneFilename)) {
  64867. exceptionFound = true;
  64868. break;
  64869. }
  64870. }
  64871. canUseOfflineSupport = !exceptionFound;
  64872. }
  64873. if (canUseOfflineSupport) {
  64874. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  64875. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  64876. }
  64877. else {
  64878. manifestChecked();
  64879. }
  64880. }
  64881. else {
  64882. var fileOrString = sceneFilename;
  64883. if (fileOrString.name) {
  64884. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  64885. }
  64886. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  64887. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  64888. }
  64889. else {
  64890. onError("Unable to find file named " + sceneFilename);
  64891. }
  64892. }
  64893. return plugin;
  64894. };
  64895. // Public functions
  64896. SceneLoader.GetPluginForExtension = function (extension) {
  64897. return SceneLoader._getPluginForExtension(extension).plugin;
  64898. };
  64899. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  64900. return !!SceneLoader._registeredPlugins[extension];
  64901. };
  64902. SceneLoader.RegisterPlugin = function (plugin) {
  64903. if (typeof plugin.extensions === "string") {
  64904. var extension = plugin.extensions;
  64905. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  64906. plugin: plugin,
  64907. isBinary: false
  64908. };
  64909. }
  64910. else {
  64911. var extensions = plugin.extensions;
  64912. Object.keys(extensions).forEach(function (extension) {
  64913. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  64914. plugin: plugin,
  64915. isBinary: extensions[extension].isBinary
  64916. };
  64917. });
  64918. }
  64919. };
  64920. /**
  64921. * Import meshes into a scene
  64922. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  64923. * @param rootUrl a string that defines the root url for scene and resources
  64924. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  64925. * @param scene the instance of BABYLON.Scene to append to
  64926. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  64927. * @param onProgress a callback with a progress event for each file being loaded
  64928. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  64929. * @param pluginExtension the extension used to determine the plugin
  64930. * @returns The loaded plugin
  64931. */
  64932. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  64933. if (onSuccess === void 0) { onSuccess = null; }
  64934. if (onProgress === void 0) { onProgress = null; }
  64935. if (onError === void 0) { onError = null; }
  64936. if (pluginExtension === void 0) { pluginExtension = null; }
  64937. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  64938. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  64939. return null;
  64940. }
  64941. var loadingToken = {};
  64942. scene._addPendingData(loadingToken);
  64943. var disposeHandler = function () {
  64944. scene._removePendingData(loadingToken);
  64945. };
  64946. var errorHandler = function (message, exception) {
  64947. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  64948. if (onError) {
  64949. onError(scene, errorMessage, exception);
  64950. }
  64951. else {
  64952. BABYLON.Tools.Error(errorMessage);
  64953. // should the exception be thrown?
  64954. }
  64955. disposeHandler();
  64956. };
  64957. var progressHandler = onProgress ? function (event) {
  64958. try {
  64959. onProgress(event);
  64960. }
  64961. catch (e) {
  64962. errorHandler("Error in onProgress callback", e);
  64963. }
  64964. } : undefined;
  64965. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  64966. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  64967. if (onSuccess) {
  64968. try {
  64969. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  64970. }
  64971. catch (e) {
  64972. errorHandler("Error in onSuccess callback", e);
  64973. }
  64974. }
  64975. scene._removePendingData(loadingToken);
  64976. };
  64977. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  64978. if (plugin.rewriteRootURL) {
  64979. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  64980. }
  64981. if (sceneFilename === "") {
  64982. if (sceneFilename === "") {
  64983. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  64984. }
  64985. }
  64986. if (plugin.importMesh) {
  64987. var syncedPlugin = plugin;
  64988. var meshes = new Array();
  64989. var particleSystems = new Array();
  64990. var skeletons = new Array();
  64991. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  64992. return;
  64993. }
  64994. scene.loadingPluginName = plugin.name;
  64995. successHandler(meshes, particleSystems, skeletons, []);
  64996. }
  64997. else {
  64998. var asyncedPlugin = plugin;
  64999. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  65000. scene.loadingPluginName = plugin.name;
  65001. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  65002. }).catch(function (error) {
  65003. errorHandler(error.message, error);
  65004. });
  65005. }
  65006. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65007. };
  65008. /**
  65009. * Import meshes into a scene
  65010. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65011. * @param rootUrl a string that defines the root url for scene and resources
  65012. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65013. * @param scene the instance of BABYLON.Scene to append to
  65014. * @param onProgress a callback with a progress event for each file being loaded
  65015. * @param pluginExtension the extension used to determine the plugin
  65016. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  65017. */
  65018. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65019. if (onProgress === void 0) { onProgress = null; }
  65020. if (pluginExtension === void 0) { pluginExtension = null; }
  65021. return new Promise(function (resolve, reject) {
  65022. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  65023. resolve({
  65024. meshes: meshes,
  65025. particleSystems: particleSystems,
  65026. skeletons: skeletons,
  65027. animationGroups: animationGroups
  65028. });
  65029. }, onProgress, function (scene, message, exception) {
  65030. reject(exception || new Error(message));
  65031. });
  65032. });
  65033. };
  65034. /**
  65035. * Load a scene
  65036. * @param rootUrl a string that defines the root url for scene and resources
  65037. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65038. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65039. * @param onSuccess a callback with the scene when import succeeds
  65040. * @param onProgress a callback with a progress event for each file being loaded
  65041. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65042. * @param pluginExtension the extension used to determine the plugin
  65043. * @returns The loaded plugin
  65044. */
  65045. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  65046. if (onSuccess === void 0) { onSuccess = null; }
  65047. if (onProgress === void 0) { onProgress = null; }
  65048. if (onError === void 0) { onError = null; }
  65049. if (pluginExtension === void 0) { pluginExtension = null; }
  65050. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  65051. };
  65052. /**
  65053. * Load a scene
  65054. * @param rootUrl a string that defines the root url for scene and resources
  65055. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65056. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65057. * @param onProgress a callback with a progress event for each file being loaded
  65058. * @param pluginExtension the extension used to determine the plugin
  65059. * @returns The loaded scene
  65060. */
  65061. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  65062. if (onProgress === void 0) { onProgress = null; }
  65063. if (pluginExtension === void 0) { pluginExtension = null; }
  65064. return new Promise(function (resolve, reject) {
  65065. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  65066. resolve(scene);
  65067. }, onProgress, function (scene, message, exception) {
  65068. reject(exception || new Error(message));
  65069. }, pluginExtension);
  65070. });
  65071. };
  65072. /**
  65073. * Append a scene
  65074. * @param rootUrl a string that defines the root url for scene and resources
  65075. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65076. * @param scene is the instance of BABYLON.Scene to append to
  65077. * @param onSuccess a callback with the scene when import succeeds
  65078. * @param onProgress a callback with a progress event for each file being loaded
  65079. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65080. * @param pluginExtension the extension used to determine the plugin
  65081. * @returns The loaded plugin
  65082. */
  65083. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65084. if (onSuccess === void 0) { onSuccess = null; }
  65085. if (onProgress === void 0) { onProgress = null; }
  65086. if (onError === void 0) { onError = null; }
  65087. if (pluginExtension === void 0) { pluginExtension = null; }
  65088. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65089. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65090. return null;
  65091. }
  65092. if (SceneLoader.ShowLoadingScreen) {
  65093. scene.getEngine().displayLoadingUI();
  65094. }
  65095. var loadingToken = {};
  65096. scene._addPendingData(loadingToken);
  65097. var disposeHandler = function () {
  65098. scene._removePendingData(loadingToken);
  65099. scene.getEngine().hideLoadingUI();
  65100. };
  65101. var errorHandler = function (message, exception) {
  65102. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65103. if (onError) {
  65104. onError(scene, errorMessage, exception);
  65105. }
  65106. else {
  65107. BABYLON.Tools.Error(errorMessage);
  65108. // should the exception be thrown?
  65109. }
  65110. disposeHandler();
  65111. };
  65112. var progressHandler = onProgress ? function (event) {
  65113. try {
  65114. onProgress(event);
  65115. }
  65116. catch (e) {
  65117. errorHandler("Error in onProgress callback", e);
  65118. }
  65119. } : undefined;
  65120. var successHandler = function () {
  65121. if (onSuccess) {
  65122. try {
  65123. onSuccess(scene);
  65124. }
  65125. catch (e) {
  65126. errorHandler("Error in onSuccess callback", e);
  65127. }
  65128. }
  65129. scene._removePendingData(loadingToken);
  65130. };
  65131. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65132. if (sceneFilename === "") {
  65133. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65134. }
  65135. if (plugin.load) {
  65136. var syncedPlugin = plugin;
  65137. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  65138. return;
  65139. }
  65140. scene.loadingPluginName = plugin.name;
  65141. successHandler();
  65142. }
  65143. else {
  65144. var asyncedPlugin = plugin;
  65145. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  65146. scene.loadingPluginName = plugin.name;
  65147. successHandler();
  65148. }).catch(function (error) {
  65149. errorHandler(error.message, error);
  65150. });
  65151. }
  65152. if (SceneLoader.ShowLoadingScreen) {
  65153. scene.executeWhenReady(function () {
  65154. scene.getEngine().hideLoadingUI();
  65155. });
  65156. }
  65157. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65158. };
  65159. /**
  65160. * Append a scene
  65161. * @param rootUrl a string that defines the root url for scene and resources
  65162. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65163. * @param scene is the instance of BABYLON.Scene to append to
  65164. * @param onProgress a callback with a progress event for each file being loaded
  65165. * @param pluginExtension the extension used to determine the plugin
  65166. * @returns The given scene
  65167. */
  65168. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65169. if (onProgress === void 0) { onProgress = null; }
  65170. if (pluginExtension === void 0) { pluginExtension = null; }
  65171. return new Promise(function (resolve, reject) {
  65172. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  65173. resolve(scene);
  65174. }, onProgress, function (scene, message, exception) {
  65175. reject(exception || new Error(message));
  65176. }, pluginExtension);
  65177. });
  65178. };
  65179. /**
  65180. * Load a scene into an asset container
  65181. * @param rootUrl a string that defines the root url for scene and resources
  65182. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65183. * @param scene is the instance of BABYLON.Scene to append to
  65184. * @param onSuccess a callback with the scene when import succeeds
  65185. * @param onProgress a callback with a progress event for each file being loaded
  65186. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65187. * @param pluginExtension the extension used to determine the plugin
  65188. * @returns The loaded plugin
  65189. */
  65190. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65191. if (onSuccess === void 0) { onSuccess = null; }
  65192. if (onProgress === void 0) { onProgress = null; }
  65193. if (onError === void 0) { onError = null; }
  65194. if (pluginExtension === void 0) { pluginExtension = null; }
  65195. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65196. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65197. return null;
  65198. }
  65199. var loadingToken = {};
  65200. scene._addPendingData(loadingToken);
  65201. var disposeHandler = function () {
  65202. scene._removePendingData(loadingToken);
  65203. };
  65204. var errorHandler = function (message, exception) {
  65205. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65206. if (onError) {
  65207. onError(scene, errorMessage, exception);
  65208. }
  65209. else {
  65210. BABYLON.Tools.Error(errorMessage);
  65211. // should the exception be thrown?
  65212. }
  65213. disposeHandler();
  65214. };
  65215. var progressHandler = onProgress ? function (event) {
  65216. try {
  65217. onProgress(event);
  65218. }
  65219. catch (e) {
  65220. errorHandler("Error in onProgress callback", e);
  65221. }
  65222. } : undefined;
  65223. var successHandler = function (assets) {
  65224. if (onSuccess) {
  65225. try {
  65226. onSuccess(assets);
  65227. }
  65228. catch (e) {
  65229. errorHandler("Error in onSuccess callback", e);
  65230. }
  65231. }
  65232. scene._removePendingData(loadingToken);
  65233. };
  65234. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65235. if (plugin.loadAssetContainer) {
  65236. var syncedPlugin = plugin;
  65237. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  65238. if (!assetContainer) {
  65239. return;
  65240. }
  65241. scene.loadingPluginName = plugin.name;
  65242. successHandler(assetContainer);
  65243. }
  65244. else if (plugin.loadAssetContainerAsync) {
  65245. var asyncedPlugin = plugin;
  65246. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  65247. scene.loadingPluginName = plugin.name;
  65248. successHandler(assetContainer);
  65249. }).catch(function (error) {
  65250. errorHandler(error.message, error);
  65251. });
  65252. }
  65253. else {
  65254. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  65255. }
  65256. if (SceneLoader.ShowLoadingScreen) {
  65257. scene.executeWhenReady(function () {
  65258. scene.getEngine().hideLoadingUI();
  65259. });
  65260. }
  65261. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65262. };
  65263. /**
  65264. * Load a scene into an asset container
  65265. * @param rootUrl a string that defines the root url for scene and resources
  65266. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65267. * @param scene is the instance of BABYLON.Scene to append to
  65268. * @param onProgress a callback with a progress event for each file being loaded
  65269. * @param pluginExtension the extension used to determine the plugin
  65270. * @returns The loaded asset container
  65271. */
  65272. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65273. if (onProgress === void 0) { onProgress = null; }
  65274. if (pluginExtension === void 0) { pluginExtension = null; }
  65275. return new Promise(function (resolve, reject) {
  65276. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  65277. resolve(assetContainer);
  65278. }, onProgress, function (scene, message, exception) {
  65279. reject(exception || new Error(message));
  65280. }, pluginExtension);
  65281. });
  65282. };
  65283. // Flags
  65284. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  65285. SceneLoader._ShowLoadingScreen = true;
  65286. SceneLoader._CleanBoneMatrixWeights = false;
  65287. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  65288. // Members
  65289. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  65290. SceneLoader._registeredPlugins = {};
  65291. return SceneLoader;
  65292. }());
  65293. BABYLON.SceneLoader = SceneLoader;
  65294. ;
  65295. })(BABYLON || (BABYLON = {}));
  65296. //# sourceMappingURL=babylon.sceneLoader.js.map
  65297. "use strict";
  65298. var BABYLON;
  65299. (function (BABYLON) {
  65300. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  65301. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65302. var parsedMaterial = parsedData.materials[index];
  65303. if (parsedMaterial.id === id) {
  65304. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65305. }
  65306. }
  65307. return null;
  65308. };
  65309. var isDescendantOf = function (mesh, names, hierarchyIds) {
  65310. for (var i in names) {
  65311. if (mesh.name === names[i]) {
  65312. hierarchyIds.push(mesh.id);
  65313. return true;
  65314. }
  65315. }
  65316. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  65317. hierarchyIds.push(mesh.id);
  65318. return true;
  65319. }
  65320. return false;
  65321. };
  65322. var logOperation = function (operation, producer) {
  65323. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  65324. };
  65325. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  65326. if (addToScene === void 0) { addToScene = false; }
  65327. var container = new BABYLON.AssetContainer(scene);
  65328. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65329. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65330. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65331. // and avoid problems with multiple concurrent .babylon loads.
  65332. var log = "importScene has failed JSON parse";
  65333. try {
  65334. var parsedData = JSON.parse(data);
  65335. log = "";
  65336. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  65337. var index;
  65338. var cache;
  65339. // Lights
  65340. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  65341. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  65342. var parsedLight = parsedData.lights[index];
  65343. var light = BABYLON.Light.Parse(parsedLight, scene);
  65344. if (light) {
  65345. container.lights.push(light);
  65346. log += (index === 0 ? "\n\tLights:" : "");
  65347. log += "\n\t\t" + light.toString(fullDetails);
  65348. }
  65349. }
  65350. }
  65351. // Animations
  65352. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  65353. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  65354. var parsedAnimation = parsedData.animations[index];
  65355. var animation = BABYLON.Animation.Parse(parsedAnimation);
  65356. scene.animations.push(animation);
  65357. container.animations.push(animation);
  65358. log += (index === 0 ? "\n\tAnimations:" : "");
  65359. log += "\n\t\t" + animation.toString(fullDetails);
  65360. }
  65361. }
  65362. // Materials
  65363. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  65364. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65365. var parsedMaterial = parsedData.materials[index];
  65366. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65367. container.materials.push(mat);
  65368. log += (index === 0 ? "\n\tMaterials:" : "");
  65369. log += "\n\t\t" + mat.toString(fullDetails);
  65370. }
  65371. }
  65372. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  65373. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  65374. var parsedMultiMaterial = parsedData.multiMaterials[index];
  65375. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  65376. container.multiMaterials.push(mmat);
  65377. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  65378. log += "\n\t\t" + mmat.toString(fullDetails);
  65379. }
  65380. }
  65381. // Morph targets
  65382. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  65383. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  65384. var managerData = _a[_i];
  65385. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  65386. }
  65387. }
  65388. // Skeletons
  65389. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  65390. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  65391. var parsedSkeleton = parsedData.skeletons[index];
  65392. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  65393. container.skeletons.push(skeleton);
  65394. log += (index === 0 ? "\n\tSkeletons:" : "");
  65395. log += "\n\t\t" + skeleton.toString(fullDetails);
  65396. }
  65397. }
  65398. // Geometries
  65399. var geometries = parsedData.geometries;
  65400. if (geometries !== undefined && geometries !== null) {
  65401. var addedGeometry = new Array();
  65402. // Boxes
  65403. var boxes = geometries.boxes;
  65404. if (boxes !== undefined && boxes !== null) {
  65405. for (index = 0, cache = boxes.length; index < cache; index++) {
  65406. var parsedBox = boxes[index];
  65407. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  65408. }
  65409. }
  65410. // Spheres
  65411. var spheres = geometries.spheres;
  65412. if (spheres !== undefined && spheres !== null) {
  65413. for (index = 0, cache = spheres.length; index < cache; index++) {
  65414. var parsedSphere = spheres[index];
  65415. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  65416. }
  65417. }
  65418. // Cylinders
  65419. var cylinders = geometries.cylinders;
  65420. if (cylinders !== undefined && cylinders !== null) {
  65421. for (index = 0, cache = cylinders.length; index < cache; index++) {
  65422. var parsedCylinder = cylinders[index];
  65423. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  65424. }
  65425. }
  65426. // Toruses
  65427. var toruses = geometries.toruses;
  65428. if (toruses !== undefined && toruses !== null) {
  65429. for (index = 0, cache = toruses.length; index < cache; index++) {
  65430. var parsedTorus = toruses[index];
  65431. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  65432. }
  65433. }
  65434. // Grounds
  65435. var grounds = geometries.grounds;
  65436. if (grounds !== undefined && grounds !== null) {
  65437. for (index = 0, cache = grounds.length; index < cache; index++) {
  65438. var parsedGround = grounds[index];
  65439. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  65440. }
  65441. }
  65442. // Planes
  65443. var planes = geometries.planes;
  65444. if (planes !== undefined && planes !== null) {
  65445. for (index = 0, cache = planes.length; index < cache; index++) {
  65446. var parsedPlane = planes[index];
  65447. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  65448. }
  65449. }
  65450. // TorusKnots
  65451. var torusKnots = geometries.torusKnots;
  65452. if (torusKnots !== undefined && torusKnots !== null) {
  65453. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  65454. var parsedTorusKnot = torusKnots[index];
  65455. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  65456. }
  65457. }
  65458. // VertexData
  65459. var vertexData = geometries.vertexData;
  65460. if (vertexData !== undefined && vertexData !== null) {
  65461. for (index = 0, cache = vertexData.length; index < cache; index++) {
  65462. var parsedVertexData = vertexData[index];
  65463. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  65464. }
  65465. }
  65466. addedGeometry.forEach(function (g) {
  65467. if (g) {
  65468. container.geometries.push(g);
  65469. }
  65470. });
  65471. }
  65472. // Transform nodes
  65473. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  65474. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  65475. var parsedTransformNode = parsedData.transformNodes[index];
  65476. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  65477. container.transformNodes.push(node);
  65478. }
  65479. }
  65480. // Meshes
  65481. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  65482. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  65483. var parsedMesh = parsedData.meshes[index];
  65484. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  65485. container.meshes.push(mesh);
  65486. log += (index === 0 ? "\n\tMeshes:" : "");
  65487. log += "\n\t\t" + mesh.toString(fullDetails);
  65488. }
  65489. }
  65490. // Cameras
  65491. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  65492. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  65493. var parsedCamera = parsedData.cameras[index];
  65494. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  65495. container.cameras.push(camera);
  65496. log += (index === 0 ? "\n\tCameras:" : "");
  65497. log += "\n\t\t" + camera.toString(fullDetails);
  65498. }
  65499. }
  65500. // Browsing all the graph to connect the dots
  65501. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  65502. var camera = scene.cameras[index];
  65503. if (camera._waitingParentId) {
  65504. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  65505. camera._waitingParentId = null;
  65506. }
  65507. }
  65508. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  65509. var light_1 = scene.lights[index];
  65510. if (light_1 && light_1._waitingParentId) {
  65511. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  65512. light_1._waitingParentId = null;
  65513. }
  65514. }
  65515. // Sounds
  65516. // TODO: add sound
  65517. var loadedSounds = [];
  65518. var loadedSound;
  65519. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  65520. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  65521. var parsedSound = parsedData.sounds[index];
  65522. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65523. if (!parsedSound.url)
  65524. parsedSound.url = parsedSound.name;
  65525. if (!loadedSounds[parsedSound.url]) {
  65526. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  65527. loadedSounds[parsedSound.url] = loadedSound;
  65528. container.sounds.push(loadedSound);
  65529. }
  65530. else {
  65531. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  65532. }
  65533. }
  65534. else {
  65535. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  65536. }
  65537. }
  65538. }
  65539. loadedSounds = [];
  65540. // Connect parents & children and parse actions
  65541. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  65542. var transformNode = scene.transformNodes[index];
  65543. if (transformNode._waitingParentId) {
  65544. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  65545. transformNode._waitingParentId = null;
  65546. }
  65547. }
  65548. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65549. var mesh = scene.meshes[index];
  65550. if (mesh._waitingParentId) {
  65551. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  65552. mesh._waitingParentId = null;
  65553. }
  65554. if (mesh._waitingActions) {
  65555. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  65556. mesh._waitingActions = null;
  65557. }
  65558. }
  65559. // freeze world matrix application
  65560. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65561. var currentMesh = scene.meshes[index];
  65562. if (currentMesh._waitingFreezeWorldMatrix) {
  65563. currentMesh.freezeWorldMatrix();
  65564. currentMesh._waitingFreezeWorldMatrix = null;
  65565. }
  65566. else {
  65567. currentMesh.computeWorldMatrix(true);
  65568. }
  65569. }
  65570. // Particles Systems
  65571. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  65572. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  65573. var parsedParticleSystem = parsedData.particleSystems[index];
  65574. if (parsedParticleSystem.activeParticleCount) {
  65575. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  65576. container.particleSystems.push(ps);
  65577. }
  65578. else {
  65579. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  65580. container.particleSystems.push(ps);
  65581. }
  65582. }
  65583. }
  65584. // Lens flares
  65585. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  65586. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  65587. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  65588. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  65589. container.lensFlareSystems.push(lf);
  65590. }
  65591. }
  65592. // Shadows
  65593. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  65594. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  65595. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  65596. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  65597. container.shadowGenerators.push(sg);
  65598. }
  65599. }
  65600. // Lights exclusions / inclusions
  65601. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  65602. var light_2 = scene.lights[index];
  65603. // Excluded check
  65604. if (light_2._excludedMeshesIds.length > 0) {
  65605. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  65606. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  65607. if (excludedMesh) {
  65608. light_2.excludedMeshes.push(excludedMesh);
  65609. }
  65610. }
  65611. light_2._excludedMeshesIds = [];
  65612. }
  65613. // Included check
  65614. if (light_2._includedOnlyMeshesIds.length > 0) {
  65615. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  65616. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  65617. if (includedOnlyMesh) {
  65618. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  65619. }
  65620. }
  65621. light_2._includedOnlyMeshesIds = [];
  65622. }
  65623. }
  65624. // Actions (scene)
  65625. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  65626. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  65627. }
  65628. if (!addToScene) {
  65629. container.removeAllFromScene();
  65630. }
  65631. }
  65632. catch (err) {
  65633. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  65634. if (onError) {
  65635. onError(msg, err);
  65636. }
  65637. else {
  65638. BABYLON.Tools.Log(msg);
  65639. throw err;
  65640. }
  65641. }
  65642. finally {
  65643. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  65644. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  65645. }
  65646. }
  65647. return container;
  65648. };
  65649. BABYLON.SceneLoader.RegisterPlugin({
  65650. name: "babylon.js",
  65651. extensions: ".babylon",
  65652. canDirectLoad: function (data) {
  65653. if (data.indexOf("babylon") !== -1) {
  65654. return true;
  65655. }
  65656. return false;
  65657. },
  65658. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  65659. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65660. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65661. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65662. // and avoid problems with multiple concurrent .babylon loads.
  65663. var log = "importMesh has failed JSON parse";
  65664. try {
  65665. var parsedData = JSON.parse(data);
  65666. log = "";
  65667. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  65668. if (!meshesNames) {
  65669. meshesNames = null;
  65670. }
  65671. else if (!Array.isArray(meshesNames)) {
  65672. meshesNames = [meshesNames];
  65673. }
  65674. var hierarchyIds = new Array();
  65675. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  65676. var loadedSkeletonsIds = [];
  65677. var loadedMaterialsIds = [];
  65678. var index;
  65679. var cache;
  65680. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  65681. var parsedMesh = parsedData.meshes[index];
  65682. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  65683. if (meshesNames !== null) {
  65684. // Remove found mesh name from list.
  65685. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  65686. }
  65687. //Geometry?
  65688. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  65689. //does the file contain geometries?
  65690. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  65691. //find the correct geometry and add it to the scene
  65692. var found = false;
  65693. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  65694. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  65695. return;
  65696. }
  65697. else {
  65698. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  65699. if (parsedGeometryData.id === parsedMesh.geometryId) {
  65700. switch (geometryType) {
  65701. case "boxes":
  65702. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  65703. break;
  65704. case "spheres":
  65705. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  65706. break;
  65707. case "cylinders":
  65708. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  65709. break;
  65710. case "toruses":
  65711. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  65712. break;
  65713. case "grounds":
  65714. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  65715. break;
  65716. case "planes":
  65717. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  65718. break;
  65719. case "torusKnots":
  65720. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  65721. break;
  65722. case "vertexData":
  65723. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  65724. break;
  65725. }
  65726. found = true;
  65727. }
  65728. });
  65729. }
  65730. });
  65731. if (found === false) {
  65732. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  65733. }
  65734. }
  65735. }
  65736. // Material ?
  65737. if (parsedMesh.materialId) {
  65738. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  65739. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  65740. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  65741. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  65742. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  65743. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  65744. var subMatId = parsedMultiMaterial.materials[matIndex];
  65745. loadedMaterialsIds.push(subMatId);
  65746. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  65747. if (mat) {
  65748. log += "\n\tMaterial " + mat.toString(fullDetails);
  65749. }
  65750. }
  65751. loadedMaterialsIds.push(parsedMultiMaterial.id);
  65752. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  65753. if (mmat) {
  65754. materialFound = true;
  65755. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  65756. }
  65757. break;
  65758. }
  65759. }
  65760. }
  65761. if (materialFound === false) {
  65762. loadedMaterialsIds.push(parsedMesh.materialId);
  65763. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  65764. if (!mat) {
  65765. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  65766. }
  65767. else {
  65768. log += "\n\tMaterial " + mat.toString(fullDetails);
  65769. }
  65770. }
  65771. }
  65772. // Skeleton ?
  65773. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  65774. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  65775. if (skeletonAlreadyLoaded === false) {
  65776. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  65777. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  65778. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  65779. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  65780. skeletons.push(skeleton);
  65781. loadedSkeletonsIds.push(parsedSkeleton.id);
  65782. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  65783. }
  65784. }
  65785. }
  65786. }
  65787. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  65788. meshes.push(mesh);
  65789. log += "\n\tMesh " + mesh.toString(fullDetails);
  65790. }
  65791. }
  65792. // Connecting parents
  65793. var currentMesh;
  65794. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65795. currentMesh = scene.meshes[index];
  65796. if (currentMesh._waitingParentId) {
  65797. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  65798. currentMesh._waitingParentId = null;
  65799. }
  65800. }
  65801. // freeze and compute world matrix application
  65802. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  65803. currentMesh = scene.meshes[index];
  65804. if (currentMesh._waitingFreezeWorldMatrix) {
  65805. currentMesh.freezeWorldMatrix();
  65806. currentMesh._waitingFreezeWorldMatrix = null;
  65807. }
  65808. else {
  65809. currentMesh.computeWorldMatrix(true);
  65810. }
  65811. }
  65812. }
  65813. // Particles
  65814. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  65815. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  65816. var parsedParticleSystem = parsedData.particleSystems[index];
  65817. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  65818. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  65819. }
  65820. }
  65821. }
  65822. return true;
  65823. }
  65824. catch (err) {
  65825. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  65826. if (onError) {
  65827. onError(msg, err);
  65828. }
  65829. else {
  65830. BABYLON.Tools.Log(msg);
  65831. throw err;
  65832. }
  65833. }
  65834. finally {
  65835. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  65836. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  65837. }
  65838. }
  65839. return false;
  65840. },
  65841. load: function (scene, data, rootUrl, onError) {
  65842. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65843. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65844. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65845. // and avoid problems with multiple concurrent .babylon loads.
  65846. var log = "importScene has failed JSON parse";
  65847. try {
  65848. var parsedData = JSON.parse(data);
  65849. log = "";
  65850. // Scene
  65851. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  65852. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  65853. }
  65854. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  65855. scene.autoClear = parsedData.autoClear;
  65856. }
  65857. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  65858. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  65859. }
  65860. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  65861. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  65862. }
  65863. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  65864. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  65865. }
  65866. // Fog
  65867. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  65868. scene.fogMode = parsedData.fogMode;
  65869. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  65870. scene.fogStart = parsedData.fogStart;
  65871. scene.fogEnd = parsedData.fogEnd;
  65872. scene.fogDensity = parsedData.fogDensity;
  65873. log += "\tFog mode for scene: ";
  65874. switch (scene.fogMode) {
  65875. // getters not compiling, so using hardcoded
  65876. case 1:
  65877. log += "exp\n";
  65878. break;
  65879. case 2:
  65880. log += "exp2\n";
  65881. break;
  65882. case 3:
  65883. log += "linear\n";
  65884. break;
  65885. }
  65886. }
  65887. //Physics
  65888. if (parsedData.physicsEnabled) {
  65889. var physicsPlugin;
  65890. if (parsedData.physicsEngine === "cannon") {
  65891. physicsPlugin = new BABYLON.CannonJSPlugin();
  65892. }
  65893. else if (parsedData.physicsEngine === "oimo") {
  65894. physicsPlugin = new BABYLON.OimoJSPlugin();
  65895. }
  65896. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  65897. //else - default engine, which is currently oimo
  65898. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  65899. scene.enablePhysics(physicsGravity, physicsPlugin);
  65900. }
  65901. // Metadata
  65902. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  65903. scene.metadata = parsedData.metadata;
  65904. }
  65905. //collisions, if defined. otherwise, default is true
  65906. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  65907. scene.collisionsEnabled = parsedData.collisionsEnabled;
  65908. }
  65909. scene.workerCollisions = !!parsedData.workerCollisions;
  65910. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  65911. if (!container) {
  65912. return false;
  65913. }
  65914. if (parsedData.autoAnimate) {
  65915. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  65916. }
  65917. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  65918. scene.setActiveCameraByID(parsedData.activeCameraID);
  65919. }
  65920. // Environment texture
  65921. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  65922. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  65923. if (parsedData.createDefaultSkybox === true) {
  65924. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  65925. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  65926. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  65927. }
  65928. }
  65929. // Finish
  65930. return true;
  65931. }
  65932. catch (err) {
  65933. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  65934. if (onError) {
  65935. onError(msg, err);
  65936. }
  65937. else {
  65938. BABYLON.Tools.Log(msg);
  65939. throw err;
  65940. }
  65941. }
  65942. finally {
  65943. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  65944. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  65945. }
  65946. }
  65947. return false;
  65948. },
  65949. loadAssetContainer: function (scene, data, rootUrl, onError) {
  65950. var container = loadAssetContainer(scene, data, rootUrl, onError);
  65951. return container;
  65952. }
  65953. });
  65954. })(BABYLON || (BABYLON = {}));
  65955. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  65956. "use strict";
  65957. var BABYLON;
  65958. (function (BABYLON) {
  65959. var FilesInput = /** @class */ (function () {
  65960. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  65961. this.onProcessFileCallback = function () { return true; };
  65962. this._engine = engine;
  65963. this._currentScene = scene;
  65964. this._sceneLoadedCallback = sceneLoadedCallback;
  65965. this._progressCallback = progressCallback;
  65966. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  65967. this._textureLoadingCallback = textureLoadingCallback;
  65968. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  65969. this._onReloadCallback = onReloadCallback;
  65970. this._errorCallback = errorCallback;
  65971. }
  65972. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  65973. var _this = this;
  65974. if (elementToMonitor) {
  65975. this._elementToMonitor = elementToMonitor;
  65976. this._dragEnterHandler = function (e) { _this.drag(e); };
  65977. this._dragOverHandler = function (e) { _this.drag(e); };
  65978. this._dropHandler = function (e) { _this.drop(e); };
  65979. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  65980. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  65981. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  65982. }
  65983. };
  65984. FilesInput.prototype.dispose = function () {
  65985. if (!this._elementToMonitor) {
  65986. return;
  65987. }
  65988. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  65989. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  65990. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  65991. };
  65992. FilesInput.prototype.renderFunction = function () {
  65993. if (this._additionalRenderLoopLogicCallback) {
  65994. this._additionalRenderLoopLogicCallback();
  65995. }
  65996. if (this._currentScene) {
  65997. if (this._textureLoadingCallback) {
  65998. var remaining = this._currentScene.getWaitingItemsCount();
  65999. if (remaining > 0) {
  66000. this._textureLoadingCallback(remaining);
  66001. }
  66002. }
  66003. this._currentScene.render();
  66004. }
  66005. };
  66006. FilesInput.prototype.drag = function (e) {
  66007. e.stopPropagation();
  66008. e.preventDefault();
  66009. };
  66010. FilesInput.prototype.drop = function (eventDrop) {
  66011. eventDrop.stopPropagation();
  66012. eventDrop.preventDefault();
  66013. this.loadFiles(eventDrop);
  66014. };
  66015. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  66016. var _this = this;
  66017. var reader = folder.createReader();
  66018. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  66019. reader.readEntries(function (entries) {
  66020. remaining.count += entries.length;
  66021. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  66022. var entry = entries_1[_i];
  66023. if (entry.isFile) {
  66024. entry.file(function (file) {
  66025. file.correctName = relativePath + file.name;
  66026. files.push(file);
  66027. if (--remaining.count === 0) {
  66028. callback();
  66029. }
  66030. });
  66031. }
  66032. else if (entry.isDirectory) {
  66033. _this._traverseFolder(entry, files, remaining, callback);
  66034. }
  66035. }
  66036. if (--remaining.count) {
  66037. callback();
  66038. }
  66039. });
  66040. };
  66041. FilesInput.prototype._processFiles = function (files) {
  66042. for (var i = 0; i < files.length; i++) {
  66043. var name = files[i].correctName.toLowerCase();
  66044. var extension = name.split('.').pop();
  66045. if (!this.onProcessFileCallback(files[i], name, extension)) {
  66046. continue;
  66047. }
  66048. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  66049. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  66050. this._sceneFileToLoad = files[i];
  66051. }
  66052. else {
  66053. FilesInput.FilesToLoad[name] = files[i];
  66054. }
  66055. }
  66056. };
  66057. FilesInput.prototype.loadFiles = function (event) {
  66058. var _this = this;
  66059. if (this._startingProcessingFilesCallback)
  66060. this._startingProcessingFilesCallback();
  66061. // Handling data transfer via drag'n'drop
  66062. if (event && event.dataTransfer && event.dataTransfer.files) {
  66063. this._filesToLoad = event.dataTransfer.files;
  66064. }
  66065. // Handling files from input files
  66066. if (event && event.target && event.target.files) {
  66067. this._filesToLoad = event.target.files;
  66068. }
  66069. if (this._filesToLoad && this._filesToLoad.length > 0) {
  66070. var files_1 = new Array();
  66071. var folders = [];
  66072. var items = event.dataTransfer ? event.dataTransfer.items : null;
  66073. for (var i = 0; i < this._filesToLoad.length; i++) {
  66074. var fileToLoad = this._filesToLoad[i];
  66075. var name_1 = fileToLoad.name.toLowerCase();
  66076. var entry = void 0;
  66077. fileToLoad.correctName = name_1;
  66078. if (items) {
  66079. var item = items[i];
  66080. if (item.getAsEntry) {
  66081. entry = item.getAsEntry();
  66082. }
  66083. else if (item.webkitGetAsEntry) {
  66084. entry = item.webkitGetAsEntry();
  66085. }
  66086. }
  66087. if (!entry) {
  66088. files_1.push(fileToLoad);
  66089. }
  66090. else {
  66091. if (entry.isDirectory) {
  66092. folders.push(entry);
  66093. }
  66094. else {
  66095. files_1.push(fileToLoad);
  66096. }
  66097. }
  66098. }
  66099. if (folders.length === 0) {
  66100. this._processFiles(files_1);
  66101. this._processReload();
  66102. }
  66103. else {
  66104. var remaining = { count: folders.length };
  66105. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  66106. var folder = folders_1[_i];
  66107. this._traverseFolder(folder, files_1, remaining, function () {
  66108. _this._processFiles(files_1);
  66109. if (remaining.count === 0) {
  66110. _this._processReload();
  66111. }
  66112. });
  66113. }
  66114. }
  66115. }
  66116. };
  66117. FilesInput.prototype._processReload = function () {
  66118. if (this._onReloadCallback) {
  66119. this._onReloadCallback(this._sceneFileToLoad);
  66120. }
  66121. else {
  66122. this.reload();
  66123. }
  66124. };
  66125. FilesInput.prototype.reload = function () {
  66126. var _this = this;
  66127. // If a scene file has been provided
  66128. if (this._sceneFileToLoad) {
  66129. if (this._currentScene) {
  66130. if (BABYLON.Tools.errorsCount > 0) {
  66131. BABYLON.Tools.ClearLogCache();
  66132. }
  66133. this._engine.stopRenderLoop();
  66134. this._currentScene.dispose();
  66135. }
  66136. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  66137. if (_this._progressCallback) {
  66138. _this._progressCallback(progress);
  66139. }
  66140. }).then(function (scene) {
  66141. _this._currentScene = scene;
  66142. if (_this._sceneLoadedCallback) {
  66143. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  66144. }
  66145. // Wait for textures and shaders to be ready
  66146. _this._currentScene.executeWhenReady(function () {
  66147. _this._engine.runRenderLoop(function () {
  66148. _this.renderFunction();
  66149. });
  66150. });
  66151. }).catch(function (error) {
  66152. if (_this._errorCallback) {
  66153. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  66154. }
  66155. });
  66156. }
  66157. else {
  66158. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  66159. }
  66160. };
  66161. FilesInput.FilesToLoad = {};
  66162. return FilesInput;
  66163. }());
  66164. BABYLON.FilesInput = FilesInput;
  66165. })(BABYLON || (BABYLON = {}));
  66166. //# sourceMappingURL=babylon.filesInput.js.map
  66167. "use strict";
  66168. var BABYLON;
  66169. (function (BABYLON) {
  66170. /**
  66171. * This class implement a typical dictionary using a string as key and the generic type T as value.
  66172. * The underlying implementation relies on an associative array to ensure the best performances.
  66173. * The value can be anything including 'null' but except 'undefined'
  66174. */
  66175. var StringDictionary = /** @class */ (function () {
  66176. function StringDictionary() {
  66177. this._count = 0;
  66178. this._data = {};
  66179. }
  66180. /**
  66181. * This will clear this dictionary and copy the content from the 'source' one.
  66182. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  66183. * @param source the dictionary to take the content from and copy to this dictionary
  66184. */
  66185. StringDictionary.prototype.copyFrom = function (source) {
  66186. var _this = this;
  66187. this.clear();
  66188. source.forEach(function (t, v) { return _this.add(t, v); });
  66189. };
  66190. /**
  66191. * Get a value based from its key
  66192. * @param key the given key to get the matching value from
  66193. * @return the value if found, otherwise undefined is returned
  66194. */
  66195. StringDictionary.prototype.get = function (key) {
  66196. var val = this._data[key];
  66197. if (val !== undefined) {
  66198. return val;
  66199. }
  66200. return undefined;
  66201. };
  66202. /**
  66203. * Get a value from its key or add it if it doesn't exist.
  66204. * This method will ensure you that a given key/data will be present in the dictionary.
  66205. * @param key the given key to get the matching value from
  66206. * @param factory the factory that will create the value if the key is not present in the dictionary.
  66207. * The factory will only be invoked if there's no data for the given key.
  66208. * @return the value corresponding to the key.
  66209. */
  66210. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  66211. var val = this.get(key);
  66212. if (val !== undefined) {
  66213. return val;
  66214. }
  66215. val = factory(key);
  66216. if (val) {
  66217. this.add(key, val);
  66218. }
  66219. return val;
  66220. };
  66221. /**
  66222. * Get a value from its key if present in the dictionary otherwise add it
  66223. * @param key the key to get the value from
  66224. * @param val if there's no such key/value pair in the dictionary add it with this value
  66225. * @return the value corresponding to the key
  66226. */
  66227. StringDictionary.prototype.getOrAdd = function (key, val) {
  66228. var curVal = this.get(key);
  66229. if (curVal !== undefined) {
  66230. return curVal;
  66231. }
  66232. this.add(key, val);
  66233. return val;
  66234. };
  66235. /**
  66236. * Check if there's a given key in the dictionary
  66237. * @param key the key to check for
  66238. * @return true if the key is present, false otherwise
  66239. */
  66240. StringDictionary.prototype.contains = function (key) {
  66241. return this._data[key] !== undefined;
  66242. };
  66243. /**
  66244. * Add a new key and its corresponding value
  66245. * @param key the key to add
  66246. * @param value the value corresponding to the key
  66247. * @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
  66248. */
  66249. StringDictionary.prototype.add = function (key, value) {
  66250. if (this._data[key] !== undefined) {
  66251. return false;
  66252. }
  66253. this._data[key] = value;
  66254. ++this._count;
  66255. return true;
  66256. };
  66257. StringDictionary.prototype.set = function (key, value) {
  66258. if (this._data[key] === undefined) {
  66259. return false;
  66260. }
  66261. this._data[key] = value;
  66262. return true;
  66263. };
  66264. /**
  66265. * Get the element of the given key and remove it from the dictionary
  66266. * @param key
  66267. */
  66268. StringDictionary.prototype.getAndRemove = function (key) {
  66269. var val = this.get(key);
  66270. if (val !== undefined) {
  66271. delete this._data[key];
  66272. --this._count;
  66273. return val;
  66274. }
  66275. return null;
  66276. };
  66277. /**
  66278. * Remove a key/value from the dictionary.
  66279. * @param key the key to remove
  66280. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  66281. */
  66282. StringDictionary.prototype.remove = function (key) {
  66283. if (this.contains(key)) {
  66284. delete this._data[key];
  66285. --this._count;
  66286. return true;
  66287. }
  66288. return false;
  66289. };
  66290. /**
  66291. * Clear the whole content of the dictionary
  66292. */
  66293. StringDictionary.prototype.clear = function () {
  66294. this._data = {};
  66295. this._count = 0;
  66296. };
  66297. Object.defineProperty(StringDictionary.prototype, "count", {
  66298. get: function () {
  66299. return this._count;
  66300. },
  66301. enumerable: true,
  66302. configurable: true
  66303. });
  66304. /**
  66305. * Execute a callback on each key/val of the dictionary.
  66306. * Note that you can remove any element in this dictionary in the callback implementation
  66307. * @param callback the callback to execute on a given key/value pair
  66308. */
  66309. StringDictionary.prototype.forEach = function (callback) {
  66310. for (var cur in this._data) {
  66311. var val = this._data[cur];
  66312. callback(cur, val);
  66313. }
  66314. };
  66315. /**
  66316. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  66317. * If the callback returns null or undefined the method will iterate to the next key/value pair
  66318. * Note that you can remove any element in this dictionary in the callback implementation
  66319. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  66320. */
  66321. StringDictionary.prototype.first = function (callback) {
  66322. for (var cur in this._data) {
  66323. var val = this._data[cur];
  66324. var res = callback(cur, val);
  66325. if (res) {
  66326. return res;
  66327. }
  66328. }
  66329. return null;
  66330. };
  66331. return StringDictionary;
  66332. }());
  66333. BABYLON.StringDictionary = StringDictionary;
  66334. })(BABYLON || (BABYLON = {}));
  66335. //# sourceMappingURL=babylon.stringDictionary.js.map
  66336. "use strict";
  66337. var BABYLON;
  66338. (function (BABYLON) {
  66339. var Tags = /** @class */ (function () {
  66340. function Tags() {
  66341. }
  66342. Tags.EnableFor = function (obj) {
  66343. obj._tags = obj._tags || {};
  66344. obj.hasTags = function () {
  66345. return Tags.HasTags(obj);
  66346. };
  66347. obj.addTags = function (tagsString) {
  66348. return Tags.AddTagsTo(obj, tagsString);
  66349. };
  66350. obj.removeTags = function (tagsString) {
  66351. return Tags.RemoveTagsFrom(obj, tagsString);
  66352. };
  66353. obj.matchesTagsQuery = function (tagsQuery) {
  66354. return Tags.MatchesQuery(obj, tagsQuery);
  66355. };
  66356. };
  66357. Tags.DisableFor = function (obj) {
  66358. delete obj._tags;
  66359. delete obj.hasTags;
  66360. delete obj.addTags;
  66361. delete obj.removeTags;
  66362. delete obj.matchesTagsQuery;
  66363. };
  66364. Tags.HasTags = function (obj) {
  66365. if (!obj._tags) {
  66366. return false;
  66367. }
  66368. return !BABYLON.Tools.IsEmpty(obj._tags);
  66369. };
  66370. Tags.GetTags = function (obj, asString) {
  66371. if (asString === void 0) { asString = true; }
  66372. if (!obj._tags) {
  66373. return null;
  66374. }
  66375. if (asString) {
  66376. var tagsArray = [];
  66377. for (var tag in obj._tags) {
  66378. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  66379. tagsArray.push(tag);
  66380. }
  66381. }
  66382. return tagsArray.join(" ");
  66383. }
  66384. else {
  66385. return obj._tags;
  66386. }
  66387. };
  66388. // the tags 'true' and 'false' are reserved and cannot be used as tags
  66389. // a tag cannot start with '||', '&&', and '!'
  66390. // it cannot contain whitespaces
  66391. Tags.AddTagsTo = function (obj, tagsString) {
  66392. if (!tagsString) {
  66393. return;
  66394. }
  66395. if (typeof tagsString !== "string") {
  66396. return;
  66397. }
  66398. var tags = tagsString.split(" ");
  66399. tags.forEach(function (tag, index, array) {
  66400. Tags._AddTagTo(obj, tag);
  66401. });
  66402. };
  66403. Tags._AddTagTo = function (obj, tag) {
  66404. tag = tag.trim();
  66405. if (tag === "" || tag === "true" || tag === "false") {
  66406. return;
  66407. }
  66408. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  66409. return;
  66410. }
  66411. Tags.EnableFor(obj);
  66412. obj._tags[tag] = true;
  66413. };
  66414. Tags.RemoveTagsFrom = function (obj, tagsString) {
  66415. if (!Tags.HasTags(obj)) {
  66416. return;
  66417. }
  66418. var tags = tagsString.split(" ");
  66419. for (var t in tags) {
  66420. Tags._RemoveTagFrom(obj, tags[t]);
  66421. }
  66422. };
  66423. Tags._RemoveTagFrom = function (obj, tag) {
  66424. delete obj._tags[tag];
  66425. };
  66426. Tags.MatchesQuery = function (obj, tagsQuery) {
  66427. if (tagsQuery === undefined) {
  66428. return true;
  66429. }
  66430. if (tagsQuery === "") {
  66431. return Tags.HasTags(obj);
  66432. }
  66433. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  66434. };
  66435. return Tags;
  66436. }());
  66437. BABYLON.Tags = Tags;
  66438. })(BABYLON || (BABYLON = {}));
  66439. //# sourceMappingURL=babylon.tags.js.map
  66440. "use strict";
  66441. var BABYLON;
  66442. (function (BABYLON) {
  66443. var AndOrNotEvaluator = /** @class */ (function () {
  66444. function AndOrNotEvaluator() {
  66445. }
  66446. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  66447. if (!query.match(/\([^\(\)]*\)/g)) {
  66448. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  66449. }
  66450. else {
  66451. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  66452. // remove parenthesis
  66453. r = r.slice(1, r.length - 1);
  66454. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  66455. });
  66456. }
  66457. if (query === "true") {
  66458. return true;
  66459. }
  66460. if (query === "false") {
  66461. return false;
  66462. }
  66463. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  66464. };
  66465. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  66466. evaluateCallback = evaluateCallback || (function (r) {
  66467. return r === "true" ? true : false;
  66468. });
  66469. var result;
  66470. var or = parenthesisContent.split("||");
  66471. for (var i in or) {
  66472. if (or.hasOwnProperty(i)) {
  66473. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  66474. var and = ori.split("&&");
  66475. if (and.length > 1) {
  66476. for (var j = 0; j < and.length; ++j) {
  66477. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  66478. if (andj !== "true" && andj !== "false") {
  66479. if (andj[0] === "!") {
  66480. result = !evaluateCallback(andj.substring(1));
  66481. }
  66482. else {
  66483. result = evaluateCallback(andj);
  66484. }
  66485. }
  66486. else {
  66487. result = andj === "true" ? true : false;
  66488. }
  66489. if (!result) {
  66490. ori = "false";
  66491. break;
  66492. }
  66493. }
  66494. }
  66495. if (result || ori === "true") {
  66496. result = true;
  66497. break;
  66498. }
  66499. // result equals false (or undefined)
  66500. if (ori !== "true" && ori !== "false") {
  66501. if (ori[0] === "!") {
  66502. result = !evaluateCallback(ori.substring(1));
  66503. }
  66504. else {
  66505. result = evaluateCallback(ori);
  66506. }
  66507. }
  66508. else {
  66509. result = ori === "true" ? true : false;
  66510. }
  66511. }
  66512. }
  66513. // the whole parenthesis scope is replaced by 'true' or 'false'
  66514. return result ? "true" : "false";
  66515. };
  66516. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  66517. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  66518. // remove whitespaces
  66519. r = r.replace(/[\s]/g, function () { return ""; });
  66520. return r.length % 2 ? "!" : "";
  66521. });
  66522. booleanString = booleanString.trim();
  66523. if (booleanString === "!true") {
  66524. booleanString = "false";
  66525. }
  66526. else if (booleanString === "!false") {
  66527. booleanString = "true";
  66528. }
  66529. return booleanString;
  66530. };
  66531. return AndOrNotEvaluator;
  66532. }());
  66533. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  66534. })(BABYLON || (BABYLON = {}));
  66535. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  66536. "use strict";
  66537. var BABYLON;
  66538. (function (BABYLON) {
  66539. var Database = /** @class */ (function () {
  66540. function Database(urlToScene, callbackManifestChecked) {
  66541. // Handling various flavors of prefixed version of IndexedDB
  66542. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  66543. this.callbackManifestChecked = callbackManifestChecked;
  66544. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  66545. this.db = null;
  66546. this._enableSceneOffline = false;
  66547. this._enableTexturesOffline = false;
  66548. this.manifestVersionFound = 0;
  66549. this.mustUpdateRessources = false;
  66550. this.hasReachedQuota = false;
  66551. if (!Database.IDBStorageEnabled) {
  66552. this.callbackManifestChecked(true);
  66553. }
  66554. else {
  66555. this.checkManifestFile();
  66556. }
  66557. }
  66558. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  66559. get: function () {
  66560. return this._enableSceneOffline;
  66561. },
  66562. enumerable: true,
  66563. configurable: true
  66564. });
  66565. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  66566. get: function () {
  66567. return this._enableTexturesOffline;
  66568. },
  66569. enumerable: true,
  66570. configurable: true
  66571. });
  66572. Database.prototype.checkManifestFile = function () {
  66573. var _this = this;
  66574. var noManifestFile = function () {
  66575. _this._enableSceneOffline = false;
  66576. _this._enableTexturesOffline = false;
  66577. _this.callbackManifestChecked(false);
  66578. };
  66579. var timeStampUsed = false;
  66580. var manifestURL = this.currentSceneUrl + ".manifest";
  66581. var xhr = new XMLHttpRequest();
  66582. if (navigator.onLine) {
  66583. // Adding a timestamp to by-pass browsers' cache
  66584. timeStampUsed = true;
  66585. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  66586. }
  66587. xhr.open("GET", manifestURL, true);
  66588. xhr.addEventListener("load", function () {
  66589. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  66590. try {
  66591. var manifestFile = JSON.parse(xhr.response);
  66592. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  66593. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  66594. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  66595. _this.manifestVersionFound = manifestFile.version;
  66596. }
  66597. if (_this.callbackManifestChecked) {
  66598. _this.callbackManifestChecked(true);
  66599. }
  66600. }
  66601. catch (ex) {
  66602. noManifestFile();
  66603. }
  66604. }
  66605. else {
  66606. noManifestFile();
  66607. }
  66608. }, false);
  66609. xhr.addEventListener("error", function (event) {
  66610. if (timeStampUsed) {
  66611. timeStampUsed = false;
  66612. // Let's retry without the timeStamp
  66613. // It could fail when coupled with HTML5 Offline API
  66614. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  66615. xhr.open("GET", retryManifestURL, true);
  66616. xhr.send();
  66617. }
  66618. else {
  66619. noManifestFile();
  66620. }
  66621. }, false);
  66622. try {
  66623. xhr.send();
  66624. }
  66625. catch (ex) {
  66626. BABYLON.Tools.Error("Error on XHR send request.");
  66627. this.callbackManifestChecked(false);
  66628. }
  66629. };
  66630. Database.prototype.openAsync = function (successCallback, errorCallback) {
  66631. var _this = this;
  66632. var handleError = function () {
  66633. _this.isSupported = false;
  66634. if (errorCallback)
  66635. errorCallback();
  66636. };
  66637. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  66638. // Your browser doesn't support IndexedDB
  66639. this.isSupported = false;
  66640. if (errorCallback)
  66641. errorCallback();
  66642. }
  66643. else {
  66644. // If the DB hasn't been opened or created yet
  66645. if (!this.db) {
  66646. this.hasReachedQuota = false;
  66647. this.isSupported = true;
  66648. var request = this.idbFactory.open("babylonjs", 1);
  66649. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  66650. request.onerror = function (event) {
  66651. handleError();
  66652. };
  66653. // executes when a version change transaction cannot complete due to other active transactions
  66654. request.onblocked = function (event) {
  66655. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  66656. handleError();
  66657. };
  66658. // DB has been opened successfully
  66659. request.onsuccess = function (event) {
  66660. _this.db = request.result;
  66661. successCallback();
  66662. };
  66663. // Initialization of the DB. Creating Scenes & Textures stores
  66664. request.onupgradeneeded = function (event) {
  66665. _this.db = (event.target).result;
  66666. if (_this.db) {
  66667. try {
  66668. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  66669. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  66670. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  66671. }
  66672. catch (ex) {
  66673. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  66674. handleError();
  66675. }
  66676. }
  66677. };
  66678. }
  66679. else {
  66680. if (successCallback)
  66681. successCallback();
  66682. }
  66683. }
  66684. };
  66685. Database.prototype.loadImageFromDB = function (url, image) {
  66686. var _this = this;
  66687. var completeURL = Database.ReturnFullUrlLocation(url);
  66688. var saveAndLoadImage = function () {
  66689. if (!_this.hasReachedQuota && _this.db !== null) {
  66690. // the texture is not yet in the DB, let's try to save it
  66691. _this._saveImageIntoDBAsync(completeURL, image);
  66692. }
  66693. else {
  66694. image.src = url;
  66695. }
  66696. };
  66697. if (!this.mustUpdateRessources) {
  66698. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  66699. }
  66700. else {
  66701. saveAndLoadImage();
  66702. }
  66703. };
  66704. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  66705. if (this.isSupported && this.db !== null) {
  66706. var texture;
  66707. var transaction = this.db.transaction(["textures"]);
  66708. transaction.onabort = function (event) {
  66709. image.src = url;
  66710. };
  66711. transaction.oncomplete = function (event) {
  66712. var blobTextureURL;
  66713. if (texture) {
  66714. var URL = window.URL || window.webkitURL;
  66715. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  66716. image.onerror = function () {
  66717. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  66718. image.src = url;
  66719. };
  66720. image.src = blobTextureURL;
  66721. }
  66722. else {
  66723. notInDBCallback();
  66724. }
  66725. };
  66726. var getRequest = transaction.objectStore("textures").get(url);
  66727. getRequest.onsuccess = function (event) {
  66728. texture = (event.target).result;
  66729. };
  66730. getRequest.onerror = function (event) {
  66731. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  66732. image.src = url;
  66733. };
  66734. }
  66735. else {
  66736. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66737. image.src = url;
  66738. }
  66739. };
  66740. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  66741. var _this = this;
  66742. if (this.isSupported) {
  66743. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  66744. var generateBlobUrl = function () {
  66745. var blobTextureURL;
  66746. if (blob) {
  66747. var URL = window.URL || window.webkitURL;
  66748. try {
  66749. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  66750. }
  66751. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  66752. catch (ex) {
  66753. blobTextureURL = URL.createObjectURL(blob);
  66754. }
  66755. }
  66756. if (blobTextureURL) {
  66757. image.src = blobTextureURL;
  66758. }
  66759. };
  66760. if (Database.IsUASupportingBlobStorage) {
  66761. var xhr = new XMLHttpRequest(), blob;
  66762. xhr.open("GET", url, true);
  66763. xhr.responseType = "blob";
  66764. xhr.addEventListener("load", function () {
  66765. if (xhr.status === 200 && _this.db) {
  66766. // Blob as response (XHR2)
  66767. blob = xhr.response;
  66768. var transaction = _this.db.transaction(["textures"], "readwrite");
  66769. // the transaction could abort because of a QuotaExceededError error
  66770. transaction.onabort = function (event) {
  66771. try {
  66772. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  66773. var srcElement = (event.srcElement || event.target);
  66774. var error = srcElement.error;
  66775. if (error && error.name === "QuotaExceededError") {
  66776. _this.hasReachedQuota = true;
  66777. }
  66778. }
  66779. catch (ex) { }
  66780. generateBlobUrl();
  66781. };
  66782. transaction.oncomplete = function (event) {
  66783. generateBlobUrl();
  66784. };
  66785. var newTexture = { textureUrl: url, data: blob };
  66786. try {
  66787. // Put the blob into the dabase
  66788. var addRequest = transaction.objectStore("textures").put(newTexture);
  66789. addRequest.onsuccess = function (event) {
  66790. };
  66791. addRequest.onerror = function (event) {
  66792. generateBlobUrl();
  66793. };
  66794. }
  66795. catch (ex) {
  66796. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  66797. if (ex.code === 25) {
  66798. Database.IsUASupportingBlobStorage = false;
  66799. }
  66800. image.src = url;
  66801. }
  66802. }
  66803. else {
  66804. image.src = url;
  66805. }
  66806. }, false);
  66807. xhr.addEventListener("error", function (event) {
  66808. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  66809. image.src = url;
  66810. }, false);
  66811. xhr.send();
  66812. }
  66813. else {
  66814. image.src = url;
  66815. }
  66816. }
  66817. else {
  66818. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66819. image.src = url;
  66820. }
  66821. };
  66822. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  66823. var _this = this;
  66824. var updateVersion = function () {
  66825. // the version is not yet in the DB or we need to update it
  66826. _this._saveVersionIntoDBAsync(url, versionLoaded);
  66827. };
  66828. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  66829. };
  66830. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  66831. var _this = this;
  66832. if (this.isSupported && this.db) {
  66833. var version;
  66834. try {
  66835. var transaction = this.db.transaction(["versions"]);
  66836. transaction.oncomplete = function (event) {
  66837. if (version) {
  66838. // If the version in the JSON file is > than the version in DB
  66839. if (_this.manifestVersionFound > version.data) {
  66840. _this.mustUpdateRessources = true;
  66841. updateInDBCallback();
  66842. }
  66843. else {
  66844. callback(version.data);
  66845. }
  66846. }
  66847. else {
  66848. _this.mustUpdateRessources = true;
  66849. updateInDBCallback();
  66850. }
  66851. };
  66852. transaction.onabort = function (event) {
  66853. callback(-1);
  66854. };
  66855. var getRequest = transaction.objectStore("versions").get(url);
  66856. getRequest.onsuccess = function (event) {
  66857. version = (event.target).result;
  66858. };
  66859. getRequest.onerror = function (event) {
  66860. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  66861. callback(-1);
  66862. };
  66863. }
  66864. catch (ex) {
  66865. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  66866. callback(-1);
  66867. }
  66868. }
  66869. else {
  66870. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66871. callback(-1);
  66872. }
  66873. };
  66874. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  66875. var _this = this;
  66876. if (this.isSupported && !this.hasReachedQuota && this.db) {
  66877. try {
  66878. // Open a transaction to the database
  66879. var transaction = this.db.transaction(["versions"], "readwrite");
  66880. // the transaction could abort because of a QuotaExceededError error
  66881. transaction.onabort = function (event) {
  66882. try {
  66883. var error = event.srcElement['error'];
  66884. if (error && error.name === "QuotaExceededError") {
  66885. _this.hasReachedQuota = true;
  66886. }
  66887. }
  66888. catch (ex) { }
  66889. callback(-1);
  66890. };
  66891. transaction.oncomplete = function (event) {
  66892. callback(_this.manifestVersionFound);
  66893. };
  66894. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  66895. // Put the scene into the database
  66896. var addRequest = transaction.objectStore("versions").put(newVersion);
  66897. addRequest.onsuccess = function (event) {
  66898. };
  66899. addRequest.onerror = function (event) {
  66900. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  66901. };
  66902. }
  66903. catch (ex) {
  66904. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  66905. callback(-1);
  66906. }
  66907. }
  66908. else {
  66909. callback(-1);
  66910. }
  66911. };
  66912. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  66913. var _this = this;
  66914. var completeUrl = Database.ReturnFullUrlLocation(url);
  66915. var saveAndLoadFile = function () {
  66916. // the scene is not yet in the DB, let's try to save it
  66917. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  66918. };
  66919. this._checkVersionFromDB(completeUrl, function (version) {
  66920. if (version !== -1) {
  66921. if (!_this.mustUpdateRessources) {
  66922. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  66923. }
  66924. else {
  66925. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  66926. }
  66927. }
  66928. else {
  66929. if (errorCallback) {
  66930. errorCallback();
  66931. }
  66932. }
  66933. });
  66934. };
  66935. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  66936. if (this.isSupported && this.db) {
  66937. var targetStore;
  66938. if (url.indexOf(".babylon") !== -1) {
  66939. targetStore = "scenes";
  66940. }
  66941. else {
  66942. targetStore = "textures";
  66943. }
  66944. var file;
  66945. var transaction = this.db.transaction([targetStore]);
  66946. transaction.oncomplete = function (event) {
  66947. if (file) {
  66948. callback(file.data);
  66949. }
  66950. else {
  66951. notInDBCallback();
  66952. }
  66953. };
  66954. transaction.onabort = function (event) {
  66955. notInDBCallback();
  66956. };
  66957. var getRequest = transaction.objectStore(targetStore).get(url);
  66958. getRequest.onsuccess = function (event) {
  66959. file = (event.target).result;
  66960. };
  66961. getRequest.onerror = function (event) {
  66962. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  66963. notInDBCallback();
  66964. };
  66965. }
  66966. else {
  66967. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  66968. callback();
  66969. }
  66970. };
  66971. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  66972. var _this = this;
  66973. if (this.isSupported) {
  66974. var targetStore;
  66975. if (url.indexOf(".babylon") !== -1) {
  66976. targetStore = "scenes";
  66977. }
  66978. else {
  66979. targetStore = "textures";
  66980. }
  66981. // Create XHR
  66982. var xhr = new XMLHttpRequest();
  66983. var fileData;
  66984. xhr.open("GET", url, true);
  66985. if (useArrayBuffer) {
  66986. xhr.responseType = "arraybuffer";
  66987. }
  66988. if (progressCallback) {
  66989. xhr.onprogress = progressCallback;
  66990. }
  66991. xhr.addEventListener("load", function () {
  66992. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  66993. // Blob as response (XHR2)
  66994. //fileData = xhr.responseText;
  66995. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  66996. if (!_this.hasReachedQuota && _this.db) {
  66997. // Open a transaction to the database
  66998. var transaction = _this.db.transaction([targetStore], "readwrite");
  66999. // the transaction could abort because of a QuotaExceededError error
  67000. transaction.onabort = function (event) {
  67001. try {
  67002. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67003. var error = event.srcElement['error'];
  67004. if (error && error.name === "QuotaExceededError") {
  67005. _this.hasReachedQuota = true;
  67006. }
  67007. }
  67008. catch (ex) { }
  67009. callback(fileData);
  67010. };
  67011. transaction.oncomplete = function (event) {
  67012. callback(fileData);
  67013. };
  67014. var newFile;
  67015. if (targetStore === "scenes") {
  67016. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  67017. }
  67018. else {
  67019. newFile = { textureUrl: url, data: fileData };
  67020. }
  67021. try {
  67022. // Put the scene into the database
  67023. var addRequest = transaction.objectStore(targetStore).put(newFile);
  67024. addRequest.onsuccess = function (event) {
  67025. };
  67026. addRequest.onerror = function (event) {
  67027. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  67028. };
  67029. }
  67030. catch (ex) {
  67031. callback(fileData);
  67032. }
  67033. }
  67034. else {
  67035. callback(fileData);
  67036. }
  67037. }
  67038. else {
  67039. callback();
  67040. }
  67041. }, false);
  67042. xhr.addEventListener("error", function (event) {
  67043. BABYLON.Tools.Error("error on XHR request.");
  67044. callback();
  67045. }, false);
  67046. xhr.send();
  67047. }
  67048. else {
  67049. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67050. callback();
  67051. }
  67052. };
  67053. Database.IsUASupportingBlobStorage = true;
  67054. Database.IDBStorageEnabled = true;
  67055. Database.parseURL = function (url) {
  67056. var a = document.createElement('a');
  67057. a.href = url;
  67058. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  67059. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  67060. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  67061. return absLocation;
  67062. };
  67063. Database.ReturnFullUrlLocation = function (url) {
  67064. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  67065. return (Database.parseURL(window.location.href) + url);
  67066. }
  67067. else {
  67068. return url;
  67069. }
  67070. };
  67071. return Database;
  67072. }());
  67073. BABYLON.Database = Database;
  67074. })(BABYLON || (BABYLON = {}));
  67075. //# sourceMappingURL=babylon.database.js.map
  67076. "use strict";
  67077. var BABYLON;
  67078. (function (BABYLON) {
  67079. var FresnelParameters = /** @class */ (function () {
  67080. function FresnelParameters() {
  67081. this._isEnabled = true;
  67082. this.leftColor = BABYLON.Color3.White();
  67083. this.rightColor = BABYLON.Color3.Black();
  67084. this.bias = 0;
  67085. this.power = 1;
  67086. }
  67087. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  67088. get: function () {
  67089. return this._isEnabled;
  67090. },
  67091. set: function (value) {
  67092. if (this._isEnabled === value) {
  67093. return;
  67094. }
  67095. this._isEnabled = value;
  67096. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  67097. },
  67098. enumerable: true,
  67099. configurable: true
  67100. });
  67101. FresnelParameters.prototype.clone = function () {
  67102. var newFresnelParameters = new FresnelParameters();
  67103. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  67104. return newFresnelParameters;
  67105. };
  67106. FresnelParameters.prototype.serialize = function () {
  67107. var serializationObject = {};
  67108. serializationObject.isEnabled = this.isEnabled;
  67109. serializationObject.leftColor = this.leftColor.asArray();
  67110. serializationObject.rightColor = this.rightColor.asArray();
  67111. serializationObject.bias = this.bias;
  67112. serializationObject.power = this.power;
  67113. return serializationObject;
  67114. };
  67115. FresnelParameters.Parse = function (parsedFresnelParameters) {
  67116. var fresnelParameters = new FresnelParameters();
  67117. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  67118. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  67119. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  67120. fresnelParameters.bias = parsedFresnelParameters.bias;
  67121. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  67122. return fresnelParameters;
  67123. };
  67124. return FresnelParameters;
  67125. }());
  67126. BABYLON.FresnelParameters = FresnelParameters;
  67127. })(BABYLON || (BABYLON = {}));
  67128. //# sourceMappingURL=babylon.fresnelParameters.js.map
  67129. "use strict";
  67130. var BABYLON;
  67131. (function (BABYLON) {
  67132. var MultiMaterial = /** @class */ (function (_super) {
  67133. __extends(MultiMaterial, _super);
  67134. function MultiMaterial(name, scene) {
  67135. var _this = _super.call(this, name, scene, true) || this;
  67136. scene.multiMaterials.push(_this);
  67137. _this.subMaterials = new Array();
  67138. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  67139. return _this;
  67140. }
  67141. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  67142. get: function () {
  67143. return this._subMaterials;
  67144. },
  67145. set: function (value) {
  67146. this._subMaterials = value;
  67147. this._hookArray(value);
  67148. },
  67149. enumerable: true,
  67150. configurable: true
  67151. });
  67152. MultiMaterial.prototype._hookArray = function (array) {
  67153. var _this = this;
  67154. var oldPush = array.push;
  67155. array.push = function () {
  67156. var items = [];
  67157. for (var _i = 0; _i < arguments.length; _i++) {
  67158. items[_i] = arguments[_i];
  67159. }
  67160. var result = oldPush.apply(array, items);
  67161. _this._markAllSubMeshesAsTexturesDirty();
  67162. return result;
  67163. };
  67164. var oldSplice = array.splice;
  67165. array.splice = function (index, deleteCount) {
  67166. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67167. _this._markAllSubMeshesAsTexturesDirty();
  67168. return deleted;
  67169. };
  67170. };
  67171. // Properties
  67172. MultiMaterial.prototype.getSubMaterial = function (index) {
  67173. if (index < 0 || index >= this.subMaterials.length) {
  67174. return this.getScene().defaultMaterial;
  67175. }
  67176. return this.subMaterials[index];
  67177. };
  67178. MultiMaterial.prototype.getActiveTextures = function () {
  67179. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  67180. if (subMaterial) {
  67181. return subMaterial.getActiveTextures();
  67182. }
  67183. else {
  67184. return [];
  67185. }
  67186. }));
  67187. var _a;
  67188. };
  67189. // Methods
  67190. MultiMaterial.prototype.getClassName = function () {
  67191. return "MultiMaterial";
  67192. };
  67193. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  67194. for (var index = 0; index < this.subMaterials.length; index++) {
  67195. var subMaterial = this.subMaterials[index];
  67196. if (subMaterial) {
  67197. if (subMaterial.storeEffectOnSubMeshes) {
  67198. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  67199. return false;
  67200. }
  67201. continue;
  67202. }
  67203. if (!subMaterial.isReady(mesh)) {
  67204. return false;
  67205. }
  67206. }
  67207. }
  67208. return true;
  67209. };
  67210. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  67211. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  67212. for (var index = 0; index < this.subMaterials.length; index++) {
  67213. var subMaterial = null;
  67214. var current = this.subMaterials[index];
  67215. if (cloneChildren && current) {
  67216. subMaterial = current.clone(name + "-" + current.name);
  67217. }
  67218. else {
  67219. subMaterial = this.subMaterials[index];
  67220. }
  67221. newMultiMaterial.subMaterials.push(subMaterial);
  67222. }
  67223. return newMultiMaterial;
  67224. };
  67225. MultiMaterial.prototype.serialize = function () {
  67226. var serializationObject = {};
  67227. serializationObject.name = this.name;
  67228. serializationObject.id = this.id;
  67229. if (BABYLON.Tags) {
  67230. serializationObject.tags = BABYLON.Tags.GetTags(this);
  67231. }
  67232. serializationObject.materials = [];
  67233. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  67234. var subMat = this.subMaterials[matIndex];
  67235. if (subMat) {
  67236. serializationObject.materials.push(subMat.id);
  67237. }
  67238. else {
  67239. serializationObject.materials.push(null);
  67240. }
  67241. }
  67242. return serializationObject;
  67243. };
  67244. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  67245. var scene = this.getScene();
  67246. if (!scene) {
  67247. return;
  67248. }
  67249. var index = scene.multiMaterials.indexOf(this);
  67250. if (index >= 0) {
  67251. scene.multiMaterials.splice(index, 1);
  67252. }
  67253. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  67254. };
  67255. return MultiMaterial;
  67256. }(BABYLON.Material));
  67257. BABYLON.MultiMaterial = MultiMaterial;
  67258. })(BABYLON || (BABYLON = {}));
  67259. //# sourceMappingURL=babylon.multiMaterial.js.map
  67260. "use strict";
  67261. var BABYLON;
  67262. (function (BABYLON) {
  67263. var FreeCameraTouchInput = /** @class */ (function () {
  67264. function FreeCameraTouchInput() {
  67265. this._offsetX = null;
  67266. this._offsetY = null;
  67267. this._pointerPressed = new Array();
  67268. this.touchAngularSensibility = 200000.0;
  67269. this.touchMoveSensibility = 250.0;
  67270. }
  67271. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  67272. var _this = this;
  67273. var previousPosition = null;
  67274. if (this._pointerInput === undefined) {
  67275. this._onLostFocus = function (evt) {
  67276. _this._offsetX = null;
  67277. _this._offsetY = null;
  67278. };
  67279. this._pointerInput = function (p, s) {
  67280. var evt = p.event;
  67281. if (evt.pointerType === "mouse") {
  67282. return;
  67283. }
  67284. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  67285. if (!noPreventDefault) {
  67286. evt.preventDefault();
  67287. }
  67288. _this._pointerPressed.push(evt.pointerId);
  67289. if (_this._pointerPressed.length !== 1) {
  67290. return;
  67291. }
  67292. previousPosition = {
  67293. x: evt.clientX,
  67294. y: evt.clientY
  67295. };
  67296. }
  67297. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  67298. if (!noPreventDefault) {
  67299. evt.preventDefault();
  67300. }
  67301. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67302. if (index === -1) {
  67303. return;
  67304. }
  67305. _this._pointerPressed.splice(index, 1);
  67306. if (index != 0) {
  67307. return;
  67308. }
  67309. previousPosition = null;
  67310. _this._offsetX = null;
  67311. _this._offsetY = null;
  67312. }
  67313. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  67314. if (!noPreventDefault) {
  67315. evt.preventDefault();
  67316. }
  67317. if (!previousPosition) {
  67318. return;
  67319. }
  67320. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67321. if (index != 0) {
  67322. return;
  67323. }
  67324. _this._offsetX = evt.clientX - previousPosition.x;
  67325. _this._offsetY = -(evt.clientY - previousPosition.y);
  67326. }
  67327. };
  67328. }
  67329. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  67330. if (this._onLostFocus) {
  67331. element.addEventListener("blur", this._onLostFocus);
  67332. }
  67333. };
  67334. FreeCameraTouchInput.prototype.detachControl = function (element) {
  67335. if (this._pointerInput && element) {
  67336. if (this._observer) {
  67337. this.camera.getScene().onPointerObservable.remove(this._observer);
  67338. this._observer = null;
  67339. }
  67340. if (this._onLostFocus) {
  67341. element.removeEventListener("blur", this._onLostFocus);
  67342. this._onLostFocus = null;
  67343. }
  67344. this._pointerPressed = [];
  67345. this._offsetX = null;
  67346. this._offsetY = null;
  67347. }
  67348. };
  67349. FreeCameraTouchInput.prototype.checkInputs = function () {
  67350. if (this._offsetX && this._offsetY) {
  67351. var camera = this.camera;
  67352. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  67353. if (this._pointerPressed.length > 1) {
  67354. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  67355. }
  67356. else {
  67357. var speed = camera._computeLocalCameraSpeed();
  67358. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  67359. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  67360. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  67361. }
  67362. }
  67363. };
  67364. FreeCameraTouchInput.prototype.getClassName = function () {
  67365. return "FreeCameraTouchInput";
  67366. };
  67367. FreeCameraTouchInput.prototype.getSimpleName = function () {
  67368. return "touch";
  67369. };
  67370. __decorate([
  67371. BABYLON.serialize()
  67372. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  67373. __decorate([
  67374. BABYLON.serialize()
  67375. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  67376. return FreeCameraTouchInput;
  67377. }());
  67378. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  67379. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  67380. })(BABYLON || (BABYLON = {}));
  67381. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  67382. "use strict";
  67383. var BABYLON;
  67384. (function (BABYLON) {
  67385. // We're mainly based on the logic defined into the FreeCamera code
  67386. var TouchCamera = /** @class */ (function (_super) {
  67387. __extends(TouchCamera, _super);
  67388. //-- end properties for backward compatibility for inputs
  67389. function TouchCamera(name, position, scene) {
  67390. var _this = _super.call(this, name, position, scene) || this;
  67391. _this.inputs.addTouch();
  67392. _this._setupInputs();
  67393. return _this;
  67394. }
  67395. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  67396. //-- Begin properties for backward compatibility for inputs
  67397. get: function () {
  67398. var touch = this.inputs.attached["touch"];
  67399. if (touch)
  67400. return touch.touchAngularSensibility;
  67401. return 0;
  67402. },
  67403. set: function (value) {
  67404. var touch = this.inputs.attached["touch"];
  67405. if (touch)
  67406. touch.touchAngularSensibility = value;
  67407. },
  67408. enumerable: true,
  67409. configurable: true
  67410. });
  67411. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  67412. get: function () {
  67413. var touch = this.inputs.attached["touch"];
  67414. if (touch)
  67415. return touch.touchMoveSensibility;
  67416. return 0;
  67417. },
  67418. set: function (value) {
  67419. var touch = this.inputs.attached["touch"];
  67420. if (touch)
  67421. touch.touchMoveSensibility = value;
  67422. },
  67423. enumerable: true,
  67424. configurable: true
  67425. });
  67426. TouchCamera.prototype.getClassName = function () {
  67427. return "TouchCamera";
  67428. };
  67429. TouchCamera.prototype._setupInputs = function () {
  67430. var mouse = this.inputs.attached["mouse"];
  67431. if (mouse) {
  67432. mouse.touchEnabled = false;
  67433. }
  67434. };
  67435. return TouchCamera;
  67436. }(BABYLON.FreeCamera));
  67437. BABYLON.TouchCamera = TouchCamera;
  67438. })(BABYLON || (BABYLON = {}));
  67439. //# sourceMappingURL=babylon.touchCamera.js.map
  67440. "use strict";
  67441. var BABYLON;
  67442. (function (BABYLON) {
  67443. var ProceduralTexture = /** @class */ (function (_super) {
  67444. __extends(ProceduralTexture, _super);
  67445. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  67446. if (fallbackTexture === void 0) { fallbackTexture = null; }
  67447. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67448. if (isCube === void 0) { isCube = false; }
  67449. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67450. _this.isCube = isCube;
  67451. _this.isEnabled = true;
  67452. _this._currentRefreshId = -1;
  67453. _this._refreshRate = 1;
  67454. _this._vertexBuffers = {};
  67455. _this._uniforms = new Array();
  67456. _this._samplers = new Array();
  67457. _this._textures = {};
  67458. _this._floats = {};
  67459. _this._floatsArrays = {};
  67460. _this._colors3 = {};
  67461. _this._colors4 = {};
  67462. _this._vectors2 = {};
  67463. _this._vectors3 = {};
  67464. _this._matrices = {};
  67465. _this._fallbackTextureUsed = false;
  67466. scene.proceduralTextures.push(_this);
  67467. _this._engine = scene.getEngine();
  67468. _this.name = name;
  67469. _this.isRenderTarget = true;
  67470. _this._size = size;
  67471. _this._generateMipMaps = generateMipMaps;
  67472. _this.setFragment(fragment);
  67473. _this._fallbackTexture = fallbackTexture;
  67474. if (isCube) {
  67475. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  67476. _this.setFloat("face", 0);
  67477. }
  67478. else {
  67479. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  67480. }
  67481. // VBO
  67482. var vertices = [];
  67483. vertices.push(1, 1);
  67484. vertices.push(-1, 1);
  67485. vertices.push(-1, -1);
  67486. vertices.push(1, -1);
  67487. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67488. _this._createIndexBuffer();
  67489. return _this;
  67490. }
  67491. ProceduralTexture.prototype._createIndexBuffer = function () {
  67492. var engine = this._engine;
  67493. // Indices
  67494. var indices = [];
  67495. indices.push(0);
  67496. indices.push(1);
  67497. indices.push(2);
  67498. indices.push(0);
  67499. indices.push(2);
  67500. indices.push(3);
  67501. this._indexBuffer = engine.createIndexBuffer(indices);
  67502. };
  67503. ProceduralTexture.prototype._rebuild = function () {
  67504. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67505. if (vb) {
  67506. vb._rebuild();
  67507. }
  67508. this._createIndexBuffer();
  67509. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67510. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67511. }
  67512. };
  67513. ProceduralTexture.prototype.reset = function () {
  67514. if (this._effect === undefined) {
  67515. return;
  67516. }
  67517. var engine = this._engine;
  67518. engine._releaseEffect(this._effect);
  67519. };
  67520. ProceduralTexture.prototype.isReady = function () {
  67521. var _this = this;
  67522. var engine = this._engine;
  67523. var shaders;
  67524. if (!this._fragment) {
  67525. return false;
  67526. }
  67527. if (this._fallbackTextureUsed) {
  67528. return true;
  67529. }
  67530. if (this._fragment.fragmentElement !== undefined) {
  67531. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  67532. }
  67533. else {
  67534. shaders = { vertex: "procedural", fragment: this._fragment };
  67535. }
  67536. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  67537. _this.releaseInternalTexture();
  67538. if (_this._fallbackTexture) {
  67539. _this._texture = _this._fallbackTexture._texture;
  67540. if (_this._texture) {
  67541. _this._texture.incrementReferences();
  67542. }
  67543. }
  67544. _this._fallbackTextureUsed = true;
  67545. });
  67546. return this._effect.isReady();
  67547. };
  67548. ProceduralTexture.prototype.resetRefreshCounter = function () {
  67549. this._currentRefreshId = -1;
  67550. };
  67551. ProceduralTexture.prototype.setFragment = function (fragment) {
  67552. this._fragment = fragment;
  67553. };
  67554. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  67555. get: function () {
  67556. return this._refreshRate;
  67557. },
  67558. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67559. set: function (value) {
  67560. this._refreshRate = value;
  67561. this.resetRefreshCounter();
  67562. },
  67563. enumerable: true,
  67564. configurable: true
  67565. });
  67566. ProceduralTexture.prototype._shouldRender = function () {
  67567. if (!this.isEnabled || !this.isReady() || !this._texture) {
  67568. return false;
  67569. }
  67570. if (this._fallbackTextureUsed) {
  67571. return false;
  67572. }
  67573. if (this._currentRefreshId === -1) {
  67574. this._currentRefreshId = 1;
  67575. return true;
  67576. }
  67577. if (this.refreshRate === this._currentRefreshId) {
  67578. this._currentRefreshId = 1;
  67579. return true;
  67580. }
  67581. this._currentRefreshId++;
  67582. return false;
  67583. };
  67584. ProceduralTexture.prototype.getRenderSize = function () {
  67585. return this._size;
  67586. };
  67587. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  67588. if (this._fallbackTextureUsed) {
  67589. return;
  67590. }
  67591. this.releaseInternalTexture();
  67592. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  67593. };
  67594. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  67595. if (this._uniforms.indexOf(uniformName) === -1) {
  67596. this._uniforms.push(uniformName);
  67597. }
  67598. };
  67599. ProceduralTexture.prototype.setTexture = function (name, texture) {
  67600. if (this._samplers.indexOf(name) === -1) {
  67601. this._samplers.push(name);
  67602. }
  67603. this._textures[name] = texture;
  67604. return this;
  67605. };
  67606. ProceduralTexture.prototype.setFloat = function (name, value) {
  67607. this._checkUniform(name);
  67608. this._floats[name] = value;
  67609. return this;
  67610. };
  67611. ProceduralTexture.prototype.setFloats = function (name, value) {
  67612. this._checkUniform(name);
  67613. this._floatsArrays[name] = value;
  67614. return this;
  67615. };
  67616. ProceduralTexture.prototype.setColor3 = function (name, value) {
  67617. this._checkUniform(name);
  67618. this._colors3[name] = value;
  67619. return this;
  67620. };
  67621. ProceduralTexture.prototype.setColor4 = function (name, value) {
  67622. this._checkUniform(name);
  67623. this._colors4[name] = value;
  67624. return this;
  67625. };
  67626. ProceduralTexture.prototype.setVector2 = function (name, value) {
  67627. this._checkUniform(name);
  67628. this._vectors2[name] = value;
  67629. return this;
  67630. };
  67631. ProceduralTexture.prototype.setVector3 = function (name, value) {
  67632. this._checkUniform(name);
  67633. this._vectors3[name] = value;
  67634. return this;
  67635. };
  67636. ProceduralTexture.prototype.setMatrix = function (name, value) {
  67637. this._checkUniform(name);
  67638. this._matrices[name] = value;
  67639. return this;
  67640. };
  67641. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  67642. var scene = this.getScene();
  67643. if (!scene) {
  67644. return;
  67645. }
  67646. var engine = this._engine;
  67647. // Render
  67648. engine.enableEffect(this._effect);
  67649. engine.setState(false);
  67650. // Texture
  67651. for (var name in this._textures) {
  67652. this._effect.setTexture(name, this._textures[name]);
  67653. }
  67654. // Float
  67655. for (name in this._floats) {
  67656. this._effect.setFloat(name, this._floats[name]);
  67657. }
  67658. // Floats
  67659. for (name in this._floatsArrays) {
  67660. this._effect.setArray(name, this._floatsArrays[name]);
  67661. }
  67662. // Color3
  67663. for (name in this._colors3) {
  67664. this._effect.setColor3(name, this._colors3[name]);
  67665. }
  67666. // Color4
  67667. for (name in this._colors4) {
  67668. var color = this._colors4[name];
  67669. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  67670. }
  67671. // Vector2
  67672. for (name in this._vectors2) {
  67673. this._effect.setVector2(name, this._vectors2[name]);
  67674. }
  67675. // Vector3
  67676. for (name in this._vectors3) {
  67677. this._effect.setVector3(name, this._vectors3[name]);
  67678. }
  67679. // Matrix
  67680. for (name in this._matrices) {
  67681. this._effect.setMatrix(name, this._matrices[name]);
  67682. }
  67683. if (!this._texture) {
  67684. return;
  67685. }
  67686. if (this.isCube) {
  67687. for (var face = 0; face < 6; face++) {
  67688. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  67689. // VBOs
  67690. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67691. this._effect.setFloat("face", face);
  67692. // Clear
  67693. engine.clear(scene.clearColor, true, true, true);
  67694. // Draw order
  67695. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67696. // Mipmaps
  67697. if (face === 5) {
  67698. engine.generateMipMapsForCubemap(this._texture);
  67699. }
  67700. }
  67701. }
  67702. else {
  67703. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  67704. // VBOs
  67705. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67706. // Clear
  67707. engine.clear(scene.clearColor, true, true, true);
  67708. // Draw order
  67709. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67710. }
  67711. // Unbind
  67712. engine.unBindFramebuffer(this._texture, this.isCube);
  67713. if (this.onGenerated) {
  67714. this.onGenerated();
  67715. }
  67716. };
  67717. ProceduralTexture.prototype.clone = function () {
  67718. var textureSize = this.getSize();
  67719. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  67720. // Base texture
  67721. newTexture.hasAlpha = this.hasAlpha;
  67722. newTexture.level = this.level;
  67723. // RenderTarget Texture
  67724. newTexture.coordinatesMode = this.coordinatesMode;
  67725. return newTexture;
  67726. };
  67727. ProceduralTexture.prototype.dispose = function () {
  67728. var scene = this.getScene();
  67729. if (!scene) {
  67730. return;
  67731. }
  67732. var index = scene.proceduralTextures.indexOf(this);
  67733. if (index >= 0) {
  67734. scene.proceduralTextures.splice(index, 1);
  67735. }
  67736. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67737. if (vertexBuffer) {
  67738. vertexBuffer.dispose();
  67739. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67740. }
  67741. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  67742. this._indexBuffer = null;
  67743. }
  67744. _super.prototype.dispose.call(this);
  67745. };
  67746. return ProceduralTexture;
  67747. }(BABYLON.Texture));
  67748. BABYLON.ProceduralTexture = ProceduralTexture;
  67749. })(BABYLON || (BABYLON = {}));
  67750. //# sourceMappingURL=babylon.proceduralTexture.js.map
  67751. "use strict";
  67752. var BABYLON;
  67753. (function (BABYLON) {
  67754. var CustomProceduralTexture = /** @class */ (function (_super) {
  67755. __extends(CustomProceduralTexture, _super);
  67756. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  67757. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  67758. _this._animate = true;
  67759. _this._time = 0;
  67760. _this._texturePath = texturePath;
  67761. //Try to load json
  67762. _this.loadJson(texturePath);
  67763. _this.refreshRate = 1;
  67764. return _this;
  67765. }
  67766. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  67767. var _this = this;
  67768. var noConfigFile = function () {
  67769. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  67770. try {
  67771. _this.setFragment(_this._texturePath);
  67772. }
  67773. catch (ex) {
  67774. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  67775. }
  67776. };
  67777. var configFileUrl = jsonUrl + "/config.json";
  67778. var xhr = new XMLHttpRequest();
  67779. xhr.open("GET", configFileUrl, true);
  67780. xhr.addEventListener("load", function () {
  67781. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67782. try {
  67783. _this._config = JSON.parse(xhr.response);
  67784. _this.updateShaderUniforms();
  67785. _this.updateTextures();
  67786. _this.setFragment(_this._texturePath + "/custom");
  67787. _this._animate = _this._config.animate;
  67788. _this.refreshRate = _this._config.refreshrate;
  67789. }
  67790. catch (ex) {
  67791. noConfigFile();
  67792. }
  67793. }
  67794. else {
  67795. noConfigFile();
  67796. }
  67797. }, false);
  67798. xhr.addEventListener("error", function () {
  67799. noConfigFile();
  67800. }, false);
  67801. try {
  67802. xhr.send();
  67803. }
  67804. catch (ex) {
  67805. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  67806. }
  67807. };
  67808. CustomProceduralTexture.prototype.isReady = function () {
  67809. if (!_super.prototype.isReady.call(this)) {
  67810. return false;
  67811. }
  67812. for (var name in this._textures) {
  67813. var texture = this._textures[name];
  67814. if (!texture.isReady()) {
  67815. return false;
  67816. }
  67817. }
  67818. return true;
  67819. };
  67820. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  67821. var scene = this.getScene();
  67822. if (this._animate && scene) {
  67823. this._time += scene.getAnimationRatio() * 0.03;
  67824. this.updateShaderUniforms();
  67825. }
  67826. _super.prototype.render.call(this, useCameraPostProcess);
  67827. };
  67828. CustomProceduralTexture.prototype.updateTextures = function () {
  67829. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  67830. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  67831. }
  67832. };
  67833. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  67834. if (this._config) {
  67835. for (var j = 0; j < this._config.uniforms.length; j++) {
  67836. var uniform = this._config.uniforms[j];
  67837. switch (uniform.type) {
  67838. case "float":
  67839. this.setFloat(uniform.name, uniform.value);
  67840. break;
  67841. case "color3":
  67842. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  67843. break;
  67844. case "color4":
  67845. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  67846. break;
  67847. case "vector2":
  67848. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  67849. break;
  67850. case "vector3":
  67851. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  67852. break;
  67853. }
  67854. }
  67855. }
  67856. this.setFloat("time", this._time);
  67857. };
  67858. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  67859. get: function () {
  67860. return this._animate;
  67861. },
  67862. set: function (value) {
  67863. this._animate = value;
  67864. },
  67865. enumerable: true,
  67866. configurable: true
  67867. });
  67868. return CustomProceduralTexture;
  67869. }(BABYLON.ProceduralTexture));
  67870. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  67871. })(BABYLON || (BABYLON = {}));
  67872. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  67873. "use strict";
  67874. var BABYLON;
  67875. (function (BABYLON) {
  67876. var FreeCameraGamepadInput = /** @class */ (function () {
  67877. function FreeCameraGamepadInput() {
  67878. this.gamepadAngularSensibility = 200;
  67879. this.gamepadMoveSensibility = 40;
  67880. // private members
  67881. this._cameraTransform = BABYLON.Matrix.Identity();
  67882. this._deltaTransform = BABYLON.Vector3.Zero();
  67883. this._vector3 = BABYLON.Vector3.Zero();
  67884. this._vector2 = BABYLON.Vector2.Zero();
  67885. }
  67886. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  67887. var _this = this;
  67888. var manager = this.camera.getScene().gamepadManager;
  67889. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67890. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  67891. // prioritize XBOX gamepads.
  67892. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  67893. _this.gamepad = gamepad;
  67894. }
  67895. }
  67896. });
  67897. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  67898. if (_this.gamepad === gamepad) {
  67899. _this.gamepad = null;
  67900. }
  67901. });
  67902. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  67903. };
  67904. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  67905. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  67906. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  67907. this.gamepad = null;
  67908. };
  67909. FreeCameraGamepadInput.prototype.checkInputs = function () {
  67910. if (this.gamepad && this.gamepad.leftStick) {
  67911. var camera = this.camera;
  67912. var LSValues = this.gamepad.leftStick;
  67913. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  67914. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  67915. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  67916. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  67917. var RSValues = this.gamepad.rightStick;
  67918. if (RSValues) {
  67919. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  67920. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  67921. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  67922. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  67923. }
  67924. else {
  67925. RSValues = { x: 0, y: 0 };
  67926. }
  67927. if (!camera.rotationQuaternion) {
  67928. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  67929. }
  67930. else {
  67931. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  67932. }
  67933. var speed = camera._computeLocalCameraSpeed() * 50.0;
  67934. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  67935. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  67936. camera.cameraDirection.addInPlace(this._deltaTransform);
  67937. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  67938. camera.cameraRotation.addInPlace(this._vector2);
  67939. }
  67940. };
  67941. FreeCameraGamepadInput.prototype.getClassName = function () {
  67942. return "FreeCameraGamepadInput";
  67943. };
  67944. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  67945. return "gamepad";
  67946. };
  67947. __decorate([
  67948. BABYLON.serialize()
  67949. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  67950. __decorate([
  67951. BABYLON.serialize()
  67952. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  67953. return FreeCameraGamepadInput;
  67954. }());
  67955. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  67956. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  67957. })(BABYLON || (BABYLON = {}));
  67958. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  67959. "use strict";
  67960. var BABYLON;
  67961. (function (BABYLON) {
  67962. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  67963. function ArcRotateCameraGamepadInput() {
  67964. this.gamepadRotationSensibility = 80;
  67965. this.gamepadMoveSensibility = 40;
  67966. }
  67967. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  67968. var _this = this;
  67969. var manager = this.camera.getScene().gamepadManager;
  67970. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67971. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  67972. // prioritize XBOX gamepads.
  67973. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  67974. _this.gamepad = gamepad;
  67975. }
  67976. }
  67977. });
  67978. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  67979. if (_this.gamepad === gamepad) {
  67980. _this.gamepad = null;
  67981. }
  67982. });
  67983. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  67984. };
  67985. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  67986. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  67987. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  67988. this.gamepad = null;
  67989. };
  67990. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  67991. if (this.gamepad) {
  67992. var camera = this.camera;
  67993. var RSValues = this.gamepad.rightStick;
  67994. if (RSValues) {
  67995. if (RSValues.x != 0) {
  67996. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  67997. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  67998. camera.inertialAlphaOffset += normalizedRX;
  67999. }
  68000. }
  68001. if (RSValues.y != 0) {
  68002. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  68003. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  68004. camera.inertialBetaOffset += normalizedRY;
  68005. }
  68006. }
  68007. }
  68008. var LSValues = this.gamepad.leftStick;
  68009. if (LSValues && LSValues.y != 0) {
  68010. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68011. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  68012. this.camera.inertialRadiusOffset -= normalizedLY;
  68013. }
  68014. }
  68015. }
  68016. };
  68017. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  68018. return "ArcRotateCameraGamepadInput";
  68019. };
  68020. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  68021. return "gamepad";
  68022. };
  68023. __decorate([
  68024. BABYLON.serialize()
  68025. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  68026. __decorate([
  68027. BABYLON.serialize()
  68028. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68029. return ArcRotateCameraGamepadInput;
  68030. }());
  68031. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  68032. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  68033. })(BABYLON || (BABYLON = {}));
  68034. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  68035. "use strict";
  68036. var BABYLON;
  68037. (function (BABYLON) {
  68038. var GamepadManager = /** @class */ (function () {
  68039. function GamepadManager(_scene) {
  68040. var _this = this;
  68041. this._scene = _scene;
  68042. this._babylonGamepads = [];
  68043. this._oneGamepadConnected = false;
  68044. this._isMonitoring = false;
  68045. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  68046. if (!BABYLON.Tools.IsWindowObjectExist()) {
  68047. this._gamepadEventSupported = false;
  68048. }
  68049. else {
  68050. this._gamepadEventSupported = 'GamepadEvent' in window;
  68051. this._gamepadSupport = (navigator.getGamepads ||
  68052. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  68053. }
  68054. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  68055. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  68056. for (var i in _this._babylonGamepads) {
  68057. var gamepad = _this._babylonGamepads[i];
  68058. if (gamepad && gamepad._isConnected) {
  68059. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  68060. }
  68061. }
  68062. });
  68063. this._onGamepadConnectedEvent = function (evt) {
  68064. var gamepad = evt.gamepad;
  68065. if (gamepad.index in _this._babylonGamepads) {
  68066. if (_this._babylonGamepads[gamepad.index].isConnected) {
  68067. return;
  68068. }
  68069. }
  68070. var newGamepad;
  68071. if (_this._babylonGamepads[gamepad.index]) {
  68072. newGamepad = _this._babylonGamepads[gamepad.index];
  68073. newGamepad.browserGamepad = gamepad;
  68074. newGamepad._isConnected = true;
  68075. }
  68076. else {
  68077. newGamepad = _this._addNewGamepad(gamepad);
  68078. }
  68079. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68080. _this._startMonitoringGamepads();
  68081. };
  68082. this._onGamepadDisconnectedEvent = function (evt) {
  68083. var gamepad = evt.gamepad;
  68084. // Remove the gamepad from the list of gamepads to monitor.
  68085. for (var i in _this._babylonGamepads) {
  68086. if (_this._babylonGamepads[i].index === gamepad.index) {
  68087. var disconnectedGamepad = _this._babylonGamepads[i];
  68088. disconnectedGamepad._isConnected = false;
  68089. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  68090. break;
  68091. }
  68092. }
  68093. };
  68094. if (this._gamepadSupport) {
  68095. //first add already-connected gamepads
  68096. this._updateGamepadObjects();
  68097. if (this._babylonGamepads.length) {
  68098. this._startMonitoringGamepads();
  68099. }
  68100. // Checking if the gamepad connected event is supported (like in Firefox)
  68101. if (this._gamepadEventSupported) {
  68102. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  68103. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  68104. }
  68105. else {
  68106. this._startMonitoringGamepads();
  68107. }
  68108. }
  68109. }
  68110. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  68111. get: function () {
  68112. return this._babylonGamepads;
  68113. },
  68114. enumerable: true,
  68115. configurable: true
  68116. });
  68117. GamepadManager.prototype.getGamepadByType = function (type) {
  68118. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  68119. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  68120. var gamepad = _a[_i];
  68121. if (gamepad && gamepad.type === type) {
  68122. return gamepad;
  68123. }
  68124. }
  68125. return null;
  68126. };
  68127. GamepadManager.prototype.dispose = function () {
  68128. if (this._gamepadEventSupported) {
  68129. if (this._onGamepadConnectedEvent) {
  68130. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  68131. }
  68132. if (this._onGamepadDisconnectedEvent) {
  68133. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  68134. }
  68135. this._onGamepadConnectedEvent = null;
  68136. this._onGamepadDisconnectedEvent = null;
  68137. }
  68138. this._babylonGamepads.forEach(function (gamepad) {
  68139. gamepad.dispose();
  68140. });
  68141. this.onGamepadConnectedObservable.clear();
  68142. this.onGamepadDisconnectedObservable.clear();
  68143. this._oneGamepadConnected = false;
  68144. this._stopMonitoringGamepads();
  68145. this._babylonGamepads = [];
  68146. };
  68147. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  68148. if (!this._oneGamepadConnected) {
  68149. this._oneGamepadConnected = true;
  68150. }
  68151. var newGamepad;
  68152. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  68153. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  68154. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  68155. }
  68156. else if (gamepad.pose) {
  68157. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  68158. }
  68159. else {
  68160. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  68161. }
  68162. this._babylonGamepads[newGamepad.index] = newGamepad;
  68163. return newGamepad;
  68164. };
  68165. GamepadManager.prototype._startMonitoringGamepads = function () {
  68166. if (!this._isMonitoring) {
  68167. this._isMonitoring = true;
  68168. //back-comp
  68169. if (!this._scene) {
  68170. this._checkGamepadsStatus();
  68171. }
  68172. }
  68173. };
  68174. GamepadManager.prototype._stopMonitoringGamepads = function () {
  68175. this._isMonitoring = false;
  68176. };
  68177. GamepadManager.prototype._checkGamepadsStatus = function () {
  68178. var _this = this;
  68179. // Hack to be compatible Chrome
  68180. this._updateGamepadObjects();
  68181. for (var i in this._babylonGamepads) {
  68182. var gamepad = this._babylonGamepads[i];
  68183. if (!gamepad || !gamepad.isConnected) {
  68184. continue;
  68185. }
  68186. gamepad.update();
  68187. }
  68188. if (this._isMonitoring && !this._scene) {
  68189. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  68190. }
  68191. };
  68192. // This function is called only on Chrome, which does not properly support
  68193. // connection/disconnection events and forces you to recopy again the gamepad object
  68194. GamepadManager.prototype._updateGamepadObjects = function () {
  68195. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  68196. for (var i = 0; i < gamepads.length; i++) {
  68197. if (gamepads[i]) {
  68198. if (!this._babylonGamepads[gamepads[i].index]) {
  68199. var newGamepad = this._addNewGamepad(gamepads[i]);
  68200. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68201. }
  68202. else {
  68203. // Forced to copy again this object for Chrome for unknown reason
  68204. this._babylonGamepads[i].browserGamepad = gamepads[i];
  68205. if (!this._babylonGamepads[i].isConnected) {
  68206. this._babylonGamepads[i]._isConnected = true;
  68207. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  68208. }
  68209. }
  68210. }
  68211. }
  68212. };
  68213. return GamepadManager;
  68214. }());
  68215. BABYLON.GamepadManager = GamepadManager;
  68216. })(BABYLON || (BABYLON = {}));
  68217. //# sourceMappingURL=babylon.gamepadManager.js.map
  68218. "use strict";
  68219. var BABYLON;
  68220. (function (BABYLON) {
  68221. var StickValues = /** @class */ (function () {
  68222. function StickValues(x, y) {
  68223. this.x = x;
  68224. this.y = y;
  68225. }
  68226. return StickValues;
  68227. }());
  68228. BABYLON.StickValues = StickValues;
  68229. var Gamepad = /** @class */ (function () {
  68230. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  68231. if (leftStickX === void 0) { leftStickX = 0; }
  68232. if (leftStickY === void 0) { leftStickY = 1; }
  68233. if (rightStickX === void 0) { rightStickX = 2; }
  68234. if (rightStickY === void 0) { rightStickY = 3; }
  68235. this.id = id;
  68236. this.index = index;
  68237. this.browserGamepad = browserGamepad;
  68238. this._isConnected = true;
  68239. this._invertLeftStickY = false;
  68240. this.type = Gamepad.GAMEPAD;
  68241. this._leftStickAxisX = leftStickX;
  68242. this._leftStickAxisY = leftStickY;
  68243. this._rightStickAxisX = rightStickX;
  68244. this._rightStickAxisY = rightStickY;
  68245. if (this.browserGamepad.axes.length >= 2) {
  68246. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68247. }
  68248. if (this.browserGamepad.axes.length >= 4) {
  68249. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68250. }
  68251. }
  68252. Object.defineProperty(Gamepad.prototype, "isConnected", {
  68253. get: function () {
  68254. return this._isConnected;
  68255. },
  68256. enumerable: true,
  68257. configurable: true
  68258. });
  68259. Gamepad.prototype.onleftstickchanged = function (callback) {
  68260. this._onleftstickchanged = callback;
  68261. };
  68262. Gamepad.prototype.onrightstickchanged = function (callback) {
  68263. this._onrightstickchanged = callback;
  68264. };
  68265. Object.defineProperty(Gamepad.prototype, "leftStick", {
  68266. get: function () {
  68267. return this._leftStick;
  68268. },
  68269. set: function (newValues) {
  68270. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  68271. this._onleftstickchanged(newValues);
  68272. }
  68273. this._leftStick = newValues;
  68274. },
  68275. enumerable: true,
  68276. configurable: true
  68277. });
  68278. Object.defineProperty(Gamepad.prototype, "rightStick", {
  68279. get: function () {
  68280. return this._rightStick;
  68281. },
  68282. set: function (newValues) {
  68283. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  68284. this._onrightstickchanged(newValues);
  68285. }
  68286. this._rightStick = newValues;
  68287. },
  68288. enumerable: true,
  68289. configurable: true
  68290. });
  68291. Gamepad.prototype.update = function () {
  68292. if (this._leftStick) {
  68293. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68294. if (this._invertLeftStickY) {
  68295. this.leftStick.y *= -1;
  68296. }
  68297. }
  68298. if (this._rightStick) {
  68299. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68300. }
  68301. };
  68302. Gamepad.prototype.dispose = function () {
  68303. };
  68304. Gamepad.GAMEPAD = 0;
  68305. Gamepad.GENERIC = 1;
  68306. Gamepad.XBOX = 2;
  68307. Gamepad.POSE_ENABLED = 3;
  68308. return Gamepad;
  68309. }());
  68310. BABYLON.Gamepad = Gamepad;
  68311. var GenericPad = /** @class */ (function (_super) {
  68312. __extends(GenericPad, _super);
  68313. function GenericPad(id, index, browserGamepad) {
  68314. var _this = _super.call(this, id, index, browserGamepad) || this;
  68315. _this.onButtonDownObservable = new BABYLON.Observable();
  68316. _this.onButtonUpObservable = new BABYLON.Observable();
  68317. _this.type = Gamepad.GENERIC;
  68318. _this._buttons = new Array(browserGamepad.buttons.length);
  68319. return _this;
  68320. }
  68321. GenericPad.prototype.onbuttondown = function (callback) {
  68322. this._onbuttondown = callback;
  68323. };
  68324. GenericPad.prototype.onbuttonup = function (callback) {
  68325. this._onbuttonup = callback;
  68326. };
  68327. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  68328. if (newValue !== currentValue) {
  68329. if (newValue === 1) {
  68330. if (this._onbuttondown) {
  68331. this._onbuttondown(buttonIndex);
  68332. }
  68333. this.onButtonDownObservable.notifyObservers(buttonIndex);
  68334. }
  68335. if (newValue === 0) {
  68336. if (this._onbuttonup) {
  68337. this._onbuttonup(buttonIndex);
  68338. }
  68339. this.onButtonUpObservable.notifyObservers(buttonIndex);
  68340. }
  68341. }
  68342. return newValue;
  68343. };
  68344. GenericPad.prototype.update = function () {
  68345. _super.prototype.update.call(this);
  68346. for (var index = 0; index < this._buttons.length; index++) {
  68347. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  68348. }
  68349. };
  68350. GenericPad.prototype.dispose = function () {
  68351. _super.prototype.dispose.call(this);
  68352. this.onButtonDownObservable.clear();
  68353. this.onButtonUpObservable.clear();
  68354. };
  68355. return GenericPad;
  68356. }(Gamepad));
  68357. BABYLON.GenericPad = GenericPad;
  68358. })(BABYLON || (BABYLON = {}));
  68359. //# sourceMappingURL=babylon.gamepad.js.map
  68360. "use strict";
  68361. var BABYLON;
  68362. (function (BABYLON) {
  68363. var Xbox360Button;
  68364. (function (Xbox360Button) {
  68365. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  68366. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  68367. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  68368. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  68369. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  68370. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  68371. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  68372. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  68373. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  68374. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  68375. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  68376. var Xbox360Dpad;
  68377. (function (Xbox360Dpad) {
  68378. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  68379. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  68380. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  68381. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  68382. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  68383. var Xbox360Pad = /** @class */ (function (_super) {
  68384. __extends(Xbox360Pad, _super);
  68385. function Xbox360Pad(id, index, gamepad, xboxOne) {
  68386. if (xboxOne === void 0) { xboxOne = false; }
  68387. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  68388. _this._leftTrigger = 0;
  68389. _this._rightTrigger = 0;
  68390. _this.onButtonDownObservable = new BABYLON.Observable();
  68391. _this.onButtonUpObservable = new BABYLON.Observable();
  68392. _this.onPadDownObservable = new BABYLON.Observable();
  68393. _this.onPadUpObservable = new BABYLON.Observable();
  68394. _this._buttonA = 0;
  68395. _this._buttonB = 0;
  68396. _this._buttonX = 0;
  68397. _this._buttonY = 0;
  68398. _this._buttonBack = 0;
  68399. _this._buttonStart = 0;
  68400. _this._buttonLB = 0;
  68401. _this._buttonRB = 0;
  68402. _this._buttonLeftStick = 0;
  68403. _this._buttonRightStick = 0;
  68404. _this._dPadUp = 0;
  68405. _this._dPadDown = 0;
  68406. _this._dPadLeft = 0;
  68407. _this._dPadRight = 0;
  68408. _this._isXboxOnePad = false;
  68409. _this.type = BABYLON.Gamepad.XBOX;
  68410. _this._isXboxOnePad = xboxOne;
  68411. return _this;
  68412. }
  68413. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  68414. this._onlefttriggerchanged = callback;
  68415. };
  68416. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  68417. this._onrighttriggerchanged = callback;
  68418. };
  68419. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  68420. get: function () {
  68421. return this._leftTrigger;
  68422. },
  68423. set: function (newValue) {
  68424. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  68425. this._onlefttriggerchanged(newValue);
  68426. }
  68427. this._leftTrigger = newValue;
  68428. },
  68429. enumerable: true,
  68430. configurable: true
  68431. });
  68432. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  68433. get: function () {
  68434. return this._rightTrigger;
  68435. },
  68436. set: function (newValue) {
  68437. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  68438. this._onrighttriggerchanged(newValue);
  68439. }
  68440. this._rightTrigger = newValue;
  68441. },
  68442. enumerable: true,
  68443. configurable: true
  68444. });
  68445. Xbox360Pad.prototype.onbuttondown = function (callback) {
  68446. this._onbuttondown = callback;
  68447. };
  68448. Xbox360Pad.prototype.onbuttonup = function (callback) {
  68449. this._onbuttonup = callback;
  68450. };
  68451. Xbox360Pad.prototype.ondpaddown = function (callback) {
  68452. this._ondpaddown = callback;
  68453. };
  68454. Xbox360Pad.prototype.ondpadup = function (callback) {
  68455. this._ondpadup = callback;
  68456. };
  68457. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  68458. if (newValue !== currentValue) {
  68459. if (newValue === 1) {
  68460. if (this._onbuttondown) {
  68461. this._onbuttondown(buttonType);
  68462. }
  68463. this.onButtonDownObservable.notifyObservers(buttonType);
  68464. }
  68465. if (newValue === 0) {
  68466. if (this._onbuttonup) {
  68467. this._onbuttonup(buttonType);
  68468. }
  68469. this.onButtonUpObservable.notifyObservers(buttonType);
  68470. }
  68471. }
  68472. return newValue;
  68473. };
  68474. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  68475. if (newValue !== currentValue) {
  68476. if (newValue === 1) {
  68477. if (this._ondpaddown) {
  68478. this._ondpaddown(buttonType);
  68479. }
  68480. this.onPadDownObservable.notifyObservers(buttonType);
  68481. }
  68482. if (newValue === 0) {
  68483. if (this._ondpadup) {
  68484. this._ondpadup(buttonType);
  68485. }
  68486. this.onPadUpObservable.notifyObservers(buttonType);
  68487. }
  68488. }
  68489. return newValue;
  68490. };
  68491. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  68492. get: function () {
  68493. return this._buttonA;
  68494. },
  68495. set: function (value) {
  68496. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  68497. },
  68498. enumerable: true,
  68499. configurable: true
  68500. });
  68501. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  68502. get: function () {
  68503. return this._buttonB;
  68504. },
  68505. set: function (value) {
  68506. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  68507. },
  68508. enumerable: true,
  68509. configurable: true
  68510. });
  68511. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  68512. get: function () {
  68513. return this._buttonX;
  68514. },
  68515. set: function (value) {
  68516. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  68517. },
  68518. enumerable: true,
  68519. configurable: true
  68520. });
  68521. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  68522. get: function () {
  68523. return this._buttonY;
  68524. },
  68525. set: function (value) {
  68526. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  68527. },
  68528. enumerable: true,
  68529. configurable: true
  68530. });
  68531. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  68532. get: function () {
  68533. return this._buttonStart;
  68534. },
  68535. set: function (value) {
  68536. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  68537. },
  68538. enumerable: true,
  68539. configurable: true
  68540. });
  68541. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  68542. get: function () {
  68543. return this._buttonBack;
  68544. },
  68545. set: function (value) {
  68546. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  68547. },
  68548. enumerable: true,
  68549. configurable: true
  68550. });
  68551. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  68552. get: function () {
  68553. return this._buttonLB;
  68554. },
  68555. set: function (value) {
  68556. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  68557. },
  68558. enumerable: true,
  68559. configurable: true
  68560. });
  68561. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  68562. get: function () {
  68563. return this._buttonRB;
  68564. },
  68565. set: function (value) {
  68566. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  68567. },
  68568. enumerable: true,
  68569. configurable: true
  68570. });
  68571. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  68572. get: function () {
  68573. return this._buttonLeftStick;
  68574. },
  68575. set: function (value) {
  68576. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  68577. },
  68578. enumerable: true,
  68579. configurable: true
  68580. });
  68581. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  68582. get: function () {
  68583. return this._buttonRightStick;
  68584. },
  68585. set: function (value) {
  68586. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  68587. },
  68588. enumerable: true,
  68589. configurable: true
  68590. });
  68591. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  68592. get: function () {
  68593. return this._dPadUp;
  68594. },
  68595. set: function (value) {
  68596. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  68597. },
  68598. enumerable: true,
  68599. configurable: true
  68600. });
  68601. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  68602. get: function () {
  68603. return this._dPadDown;
  68604. },
  68605. set: function (value) {
  68606. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  68607. },
  68608. enumerable: true,
  68609. configurable: true
  68610. });
  68611. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  68612. get: function () {
  68613. return this._dPadLeft;
  68614. },
  68615. set: function (value) {
  68616. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  68617. },
  68618. enumerable: true,
  68619. configurable: true
  68620. });
  68621. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  68622. get: function () {
  68623. return this._dPadRight;
  68624. },
  68625. set: function (value) {
  68626. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  68627. },
  68628. enumerable: true,
  68629. configurable: true
  68630. });
  68631. Xbox360Pad.prototype.update = function () {
  68632. _super.prototype.update.call(this);
  68633. if (this._isXboxOnePad) {
  68634. this.buttonA = this.browserGamepad.buttons[0].value;
  68635. this.buttonB = this.browserGamepad.buttons[1].value;
  68636. this.buttonX = this.browserGamepad.buttons[2].value;
  68637. this.buttonY = this.browserGamepad.buttons[3].value;
  68638. this.buttonLB = this.browserGamepad.buttons[4].value;
  68639. this.buttonRB = this.browserGamepad.buttons[5].value;
  68640. this.leftTrigger = this.browserGamepad.axes[2];
  68641. this.rightTrigger = this.browserGamepad.axes[5];
  68642. this.buttonBack = this.browserGamepad.buttons[9].value;
  68643. this.buttonStart = this.browserGamepad.buttons[8].value;
  68644. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  68645. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  68646. this.dPadUp = this.browserGamepad.buttons[11].value;
  68647. this.dPadDown = this.browserGamepad.buttons[12].value;
  68648. this.dPadLeft = this.browserGamepad.buttons[13].value;
  68649. this.dPadRight = this.browserGamepad.buttons[14].value;
  68650. }
  68651. else {
  68652. this.buttonA = this.browserGamepad.buttons[0].value;
  68653. this.buttonB = this.browserGamepad.buttons[1].value;
  68654. this.buttonX = this.browserGamepad.buttons[2].value;
  68655. this.buttonY = this.browserGamepad.buttons[3].value;
  68656. this.buttonLB = this.browserGamepad.buttons[4].value;
  68657. this.buttonRB = this.browserGamepad.buttons[5].value;
  68658. this.leftTrigger = this.browserGamepad.buttons[6].value;
  68659. this.rightTrigger = this.browserGamepad.buttons[7].value;
  68660. this.buttonBack = this.browserGamepad.buttons[8].value;
  68661. this.buttonStart = this.browserGamepad.buttons[9].value;
  68662. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  68663. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  68664. this.dPadUp = this.browserGamepad.buttons[12].value;
  68665. this.dPadDown = this.browserGamepad.buttons[13].value;
  68666. this.dPadLeft = this.browserGamepad.buttons[14].value;
  68667. this.dPadRight = this.browserGamepad.buttons[15].value;
  68668. }
  68669. };
  68670. Xbox360Pad.prototype.dispose = function () {
  68671. _super.prototype.dispose.call(this);
  68672. this.onButtonDownObservable.clear();
  68673. this.onButtonUpObservable.clear();
  68674. this.onPadDownObservable.clear();
  68675. this.onPadUpObservable.clear();
  68676. };
  68677. return Xbox360Pad;
  68678. }(BABYLON.Gamepad));
  68679. BABYLON.Xbox360Pad = Xbox360Pad;
  68680. })(BABYLON || (BABYLON = {}));
  68681. //# sourceMappingURL=babylon.xboxGamepad.js.map
  68682. "use strict";
  68683. var BABYLON;
  68684. (function (BABYLON) {
  68685. /**
  68686. * Defines the types of pose enabled controllers that are supported
  68687. */
  68688. var PoseEnabledControllerType;
  68689. (function (PoseEnabledControllerType) {
  68690. /**
  68691. * HTC Vive
  68692. */
  68693. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  68694. /**
  68695. * Oculus Rift
  68696. */
  68697. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  68698. /**
  68699. * Windows mixed reality
  68700. */
  68701. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  68702. /**
  68703. * Samsung gear VR
  68704. */
  68705. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  68706. /**
  68707. * Google Daydream
  68708. */
  68709. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  68710. /**
  68711. * Generic
  68712. */
  68713. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  68714. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  68715. /**
  68716. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  68717. */
  68718. var PoseEnabledControllerHelper = /** @class */ (function () {
  68719. function PoseEnabledControllerHelper() {
  68720. }
  68721. /**
  68722. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  68723. * @param vrGamepad the gamepad to initialized
  68724. * @returns a vr controller of the type the gamepad identified as
  68725. */
  68726. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  68727. // Oculus Touch
  68728. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  68729. return new BABYLON.OculusTouchController(vrGamepad);
  68730. }
  68731. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  68732. return new BABYLON.WindowsMotionController(vrGamepad);
  68733. }
  68734. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  68735. return new BABYLON.ViveController(vrGamepad);
  68736. }
  68737. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  68738. return new BABYLON.GearVRController(vrGamepad);
  68739. }
  68740. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  68741. return new BABYLON.DaydreamController(vrGamepad);
  68742. }
  68743. else {
  68744. return new BABYLON.GenericController(vrGamepad);
  68745. }
  68746. };
  68747. return PoseEnabledControllerHelper;
  68748. }());
  68749. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  68750. /**
  68751. * Defines the PoseEnabledController object that contains state of a vr capable controller
  68752. */
  68753. var PoseEnabledController = /** @class */ (function (_super) {
  68754. __extends(PoseEnabledController, _super);
  68755. /**
  68756. * Creates a new PoseEnabledController from a gamepad
  68757. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  68758. */
  68759. function PoseEnabledController(browserGamepad) {
  68760. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  68761. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  68762. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  68763. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  68764. /**
  68765. * The device position in babylon space
  68766. */
  68767. _this.devicePosition = BABYLON.Vector3.Zero();
  68768. /**
  68769. * The device rotation in babylon space
  68770. */
  68771. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  68772. /**
  68773. * The scale factor of the device in babylon space
  68774. */
  68775. _this.deviceScaleFactor = 1;
  68776. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  68777. /**
  68778. * Internal, matrix used to convert room space to babylon space
  68779. */
  68780. _this._deviceToWorld = BABYLON.Matrix.Identity();
  68781. /**
  68782. * Node to be used when casting a ray from the controller
  68783. */
  68784. _this._pointingPoseNode = null;
  68785. _this._workingMatrix = BABYLON.Matrix.Identity();
  68786. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  68787. _this.controllerType = PoseEnabledControllerType.GENERIC;
  68788. _this.position = BABYLON.Vector3.Zero();
  68789. _this.rotationQuaternion = new BABYLON.Quaternion();
  68790. _this._calculatedPosition = BABYLON.Vector3.Zero();
  68791. _this._calculatedRotation = new BABYLON.Quaternion();
  68792. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  68793. return _this;
  68794. }
  68795. /**
  68796. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  68797. */
  68798. PoseEnabledController.prototype.update = function () {
  68799. _super.prototype.update.call(this);
  68800. var pose = this.browserGamepad.pose;
  68801. this.updateFromDevice(pose);
  68802. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  68803. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  68804. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  68805. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  68806. if (this._mesh) {
  68807. this._mesh.position.copyFrom(this.devicePosition);
  68808. if (this._mesh.rotationQuaternion) {
  68809. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  68810. }
  68811. }
  68812. };
  68813. /**
  68814. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  68815. * @param poseData raw pose fromthe device
  68816. */
  68817. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  68818. if (poseData) {
  68819. this.rawPose = poseData;
  68820. if (poseData.position) {
  68821. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  68822. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  68823. this._deviceRoomPosition.z *= -1;
  68824. }
  68825. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  68826. this._calculatedPosition.addInPlace(this.position);
  68827. }
  68828. var pose = this.rawPose;
  68829. if (poseData.orientation && pose.orientation) {
  68830. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  68831. if (this._mesh) {
  68832. if (this._mesh.getScene().useRightHandedSystem) {
  68833. this._deviceRoomRotationQuaternion.z *= -1;
  68834. this._deviceRoomRotationQuaternion.w *= -1;
  68835. }
  68836. else {
  68837. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  68838. }
  68839. }
  68840. // if the camera is set, rotate to the camera's rotation
  68841. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  68842. }
  68843. }
  68844. };
  68845. /**
  68846. * Attaches a mesh to the controller
  68847. * @param mesh the mesh to be attached
  68848. */
  68849. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  68850. if (this._mesh) {
  68851. this._mesh.parent = null;
  68852. }
  68853. this._mesh = mesh;
  68854. if (this._poseControlledCamera) {
  68855. this._mesh.parent = this._poseControlledCamera;
  68856. }
  68857. if (!this._mesh.rotationQuaternion) {
  68858. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  68859. }
  68860. };
  68861. /**
  68862. * Attaches the controllers mesh to a camera
  68863. * @param camera the camera the mesh should be attached to
  68864. */
  68865. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  68866. this._poseControlledCamera = camera;
  68867. if (this._mesh) {
  68868. this._mesh.parent = this._poseControlledCamera;
  68869. }
  68870. };
  68871. /**
  68872. * Disposes of the controller
  68873. */
  68874. PoseEnabledController.prototype.dispose = function () {
  68875. if (this._mesh) {
  68876. this._mesh.dispose();
  68877. }
  68878. this._mesh = null;
  68879. _super.prototype.dispose.call(this);
  68880. };
  68881. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  68882. /**
  68883. * The mesh that is attached to the controller
  68884. */
  68885. get: function () {
  68886. return this._mesh;
  68887. },
  68888. enumerable: true,
  68889. configurable: true
  68890. });
  68891. /**
  68892. * Gets the ray of the controller in the direction the controller is pointing
  68893. * @param length the length the resulting ray should be
  68894. * @returns a ray in the direction the controller is pointing
  68895. */
  68896. PoseEnabledController.prototype.getForwardRay = function (length) {
  68897. if (length === void 0) { length = 100; }
  68898. if (!this.mesh) {
  68899. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  68900. }
  68901. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  68902. var origin = m.getTranslation();
  68903. var forward = new BABYLON.Vector3(0, 0, -1);
  68904. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  68905. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  68906. return new BABYLON.Ray(origin, direction, length);
  68907. };
  68908. /**
  68909. * Name of the child mesh that can be used to cast a ray from the controller
  68910. */
  68911. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  68912. return PoseEnabledController;
  68913. }(BABYLON.Gamepad));
  68914. BABYLON.PoseEnabledController = PoseEnabledController;
  68915. })(BABYLON || (BABYLON = {}));
  68916. //# sourceMappingURL=babylon.poseEnabledController.js.map
  68917. "use strict";
  68918. var BABYLON;
  68919. (function (BABYLON) {
  68920. /**
  68921. * Defines the WebVRController object that represents controllers tracked in 3D space
  68922. */
  68923. var WebVRController = /** @class */ (function (_super) {
  68924. __extends(WebVRController, _super);
  68925. /**
  68926. * Creates a new WebVRController from a gamepad
  68927. * @param vrGamepad the gamepad that the WebVRController should be created from
  68928. */
  68929. function WebVRController(vrGamepad) {
  68930. var _this = _super.call(this, vrGamepad) || this;
  68931. // Observables
  68932. /**
  68933. * Fired when the trigger state has changed
  68934. */
  68935. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  68936. /**
  68937. * Fired when the main button state has changed
  68938. */
  68939. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  68940. /**
  68941. * Fired when the secondary button state has changed
  68942. */
  68943. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  68944. /**
  68945. * Fired when the pad state has changed
  68946. */
  68947. _this.onPadStateChangedObservable = new BABYLON.Observable();
  68948. /**
  68949. * Fired when controllers stick values have changed
  68950. */
  68951. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  68952. /**
  68953. * X and Y axis corrisponding to the controllers joystick
  68954. */
  68955. _this.pad = { x: 0, y: 0 };
  68956. // avoid GC, store state in a tmp object
  68957. _this._changes = {
  68958. pressChanged: false,
  68959. touchChanged: false,
  68960. valueChanged: false,
  68961. changed: false
  68962. };
  68963. _this._buttons = new Array(vrGamepad.buttons.length);
  68964. _this.hand = vrGamepad.hand;
  68965. return _this;
  68966. }
  68967. /**
  68968. * Fired when a controller button's state has changed
  68969. * @param callback the callback containing the button that was modified
  68970. */
  68971. WebVRController.prototype.onButtonStateChange = function (callback) {
  68972. this._onButtonStateChange = callback;
  68973. };
  68974. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  68975. /**
  68976. * The default controller model for the controller
  68977. */
  68978. get: function () {
  68979. return this._defaultModel;
  68980. },
  68981. enumerable: true,
  68982. configurable: true
  68983. });
  68984. /**
  68985. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  68986. */
  68987. WebVRController.prototype.update = function () {
  68988. _super.prototype.update.call(this);
  68989. for (var index = 0; index < this._buttons.length; index++) {
  68990. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  68991. }
  68992. ;
  68993. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  68994. this.pad.x = this.leftStick.x;
  68995. this.pad.y = this.leftStick.y;
  68996. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  68997. }
  68998. };
  68999. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  69000. if (!newState) {
  69001. newState = {
  69002. pressed: false,
  69003. touched: false,
  69004. value: 0
  69005. };
  69006. }
  69007. if (!currentState) {
  69008. this._buttons[buttonIndex] = {
  69009. pressed: newState.pressed,
  69010. touched: newState.touched,
  69011. value: newState.value
  69012. };
  69013. return;
  69014. }
  69015. this._checkChanges(newState, currentState);
  69016. if (this._changes.changed) {
  69017. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  69018. this._handleButtonChange(buttonIndex, newState, this._changes);
  69019. }
  69020. this._buttons[buttonIndex].pressed = newState.pressed;
  69021. this._buttons[buttonIndex].touched = newState.touched;
  69022. // oculus triggers are never 0, thou not touched.
  69023. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  69024. };
  69025. WebVRController.prototype._checkChanges = function (newState, currentState) {
  69026. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  69027. this._changes.touchChanged = newState.touched !== currentState.touched;
  69028. this._changes.valueChanged = newState.value !== currentState.value;
  69029. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  69030. return this._changes;
  69031. };
  69032. /**
  69033. * Disposes of th webVRCOntroller
  69034. */
  69035. WebVRController.prototype.dispose = function () {
  69036. _super.prototype.dispose.call(this);
  69037. this.onTriggerStateChangedObservable.clear();
  69038. this.onMainButtonStateChangedObservable.clear();
  69039. this.onSecondaryButtonStateChangedObservable.clear();
  69040. this.onPadStateChangedObservable.clear();
  69041. this.onPadValuesChangedObservable.clear();
  69042. };
  69043. return WebVRController;
  69044. }(BABYLON.PoseEnabledController));
  69045. BABYLON.WebVRController = WebVRController;
  69046. })(BABYLON || (BABYLON = {}));
  69047. //# sourceMappingURL=babylon.webVRController.js.map
  69048. "use strict";
  69049. var BABYLON;
  69050. (function (BABYLON) {
  69051. /**
  69052. * Oculus Touch Controller
  69053. */
  69054. var OculusTouchController = /** @class */ (function (_super) {
  69055. __extends(OculusTouchController, _super);
  69056. /**
  69057. * Creates a new OculusTouchController from a gamepad
  69058. * @param vrGamepad the gamepad that the controller should be created from
  69059. */
  69060. function OculusTouchController(vrGamepad) {
  69061. var _this = _super.call(this, vrGamepad) || this;
  69062. /**
  69063. * Fired when the secondary trigger on this controller is modified
  69064. */
  69065. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  69066. /**
  69067. * Fired when the thumb rest on this controller is modified
  69068. */
  69069. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  69070. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  69071. return _this;
  69072. }
  69073. /**
  69074. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69075. * @param scene scene in which to add meshes
  69076. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69077. */
  69078. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69079. var _this = this;
  69080. var meshName;
  69081. // Hand
  69082. if (this.hand === 'left') {
  69083. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  69084. }
  69085. else {
  69086. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  69087. }
  69088. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  69089. /*
  69090. Parent Mesh name: oculus_touch_left
  69091. - body
  69092. - trigger
  69093. - thumbstick
  69094. - grip
  69095. - button_y
  69096. - button_x
  69097. - button_enter
  69098. */
  69099. _this._defaultModel = newMeshes[1];
  69100. _this.attachToMesh(_this._defaultModel);
  69101. if (meshLoaded) {
  69102. meshLoaded(_this._defaultModel);
  69103. }
  69104. });
  69105. };
  69106. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  69107. /**
  69108. * Fired when the A button on this controller is modified
  69109. */
  69110. get: function () {
  69111. if (this.hand === 'right') {
  69112. return this.onMainButtonStateChangedObservable;
  69113. }
  69114. else {
  69115. throw new Error('No A button on left hand');
  69116. }
  69117. },
  69118. enumerable: true,
  69119. configurable: true
  69120. });
  69121. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  69122. /**
  69123. * Fired when the B button on this controller is modified
  69124. */
  69125. get: function () {
  69126. if (this.hand === 'right') {
  69127. return this.onSecondaryButtonStateChangedObservable;
  69128. }
  69129. else {
  69130. throw new Error('No B button on left hand');
  69131. }
  69132. },
  69133. enumerable: true,
  69134. configurable: true
  69135. });
  69136. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  69137. /**
  69138. * Fired when the X button on this controller is modified
  69139. */
  69140. get: function () {
  69141. if (this.hand === 'left') {
  69142. return this.onMainButtonStateChangedObservable;
  69143. }
  69144. else {
  69145. throw new Error('No X button on right hand');
  69146. }
  69147. },
  69148. enumerable: true,
  69149. configurable: true
  69150. });
  69151. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  69152. /**
  69153. * Fired when the Y button on this controller is modified
  69154. */
  69155. get: function () {
  69156. if (this.hand === 'left') {
  69157. return this.onSecondaryButtonStateChangedObservable;
  69158. }
  69159. else {
  69160. throw new Error('No Y button on right hand');
  69161. }
  69162. },
  69163. enumerable: true,
  69164. configurable: true
  69165. });
  69166. /**
  69167. * Called once for each button that changed state since the last frame
  69168. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  69169. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  69170. * 2) secondary trigger (same)
  69171. * 3) A (right) X (left), touch, pressed = value
  69172. * 4) B / Y
  69173. * 5) thumb rest
  69174. * @param buttonIdx Which button index changed
  69175. * @param state New state of the button
  69176. * @param changes Which properties on the state changed since last frame
  69177. */
  69178. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69179. var notifyObject = state; //{ state: state, changes: changes };
  69180. var triggerDirection = this.hand === 'right' ? -1 : 1;
  69181. switch (buttonIdx) {
  69182. case 0:
  69183. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69184. return;
  69185. case 1:// index trigger
  69186. if (this._defaultModel) {
  69187. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  69188. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  69189. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  69190. }
  69191. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69192. return;
  69193. case 2:// secondary trigger
  69194. if (this._defaultModel) {
  69195. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  69196. }
  69197. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  69198. return;
  69199. case 3:
  69200. if (this._defaultModel) {
  69201. if (notifyObject.pressed) {
  69202. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  69203. }
  69204. else {
  69205. (this._defaultModel.getChildren()[1]).position.y = 0;
  69206. }
  69207. }
  69208. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69209. return;
  69210. case 4:
  69211. if (this._defaultModel) {
  69212. if (notifyObject.pressed) {
  69213. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69214. }
  69215. else {
  69216. (this._defaultModel.getChildren()[2]).position.y = 0;
  69217. }
  69218. }
  69219. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69220. return;
  69221. case 5:
  69222. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  69223. return;
  69224. }
  69225. };
  69226. /**
  69227. * Base Url for the controller model.
  69228. */
  69229. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  69230. /**
  69231. * File name for the left controller model.
  69232. */
  69233. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  69234. /**
  69235. * File name for the right controller model.
  69236. */
  69237. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  69238. return OculusTouchController;
  69239. }(BABYLON.WebVRController));
  69240. BABYLON.OculusTouchController = OculusTouchController;
  69241. })(BABYLON || (BABYLON = {}));
  69242. //# sourceMappingURL=babylon.oculusTouchController.js.map
  69243. "use strict";
  69244. var BABYLON;
  69245. (function (BABYLON) {
  69246. /**
  69247. * Vive Controller
  69248. */
  69249. var ViveController = /** @class */ (function (_super) {
  69250. __extends(ViveController, _super);
  69251. /**
  69252. * Creates a new ViveController from a gamepad
  69253. * @param vrGamepad the gamepad that the controller should be created from
  69254. */
  69255. function ViveController(vrGamepad) {
  69256. var _this = _super.call(this, vrGamepad) || this;
  69257. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  69258. _this._invertLeftStickY = true;
  69259. return _this;
  69260. }
  69261. /**
  69262. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69263. * @param scene scene in which to add meshes
  69264. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69265. */
  69266. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69267. var _this = this;
  69268. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  69269. /*
  69270. Parent Mesh name: ViveWand
  69271. - body
  69272. - r_gripper
  69273. - l_gripper
  69274. - menu_button
  69275. - system_button
  69276. - trackpad
  69277. - trigger
  69278. - LED
  69279. */
  69280. _this._defaultModel = newMeshes[1];
  69281. _this.attachToMesh(_this._defaultModel);
  69282. if (meshLoaded) {
  69283. meshLoaded(_this._defaultModel);
  69284. }
  69285. });
  69286. };
  69287. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  69288. /**
  69289. * Fired when the left button on this controller is modified
  69290. */
  69291. get: function () {
  69292. return this.onMainButtonStateChangedObservable;
  69293. },
  69294. enumerable: true,
  69295. configurable: true
  69296. });
  69297. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  69298. /**
  69299. * Fired when the right button on this controller is modified
  69300. */
  69301. get: function () {
  69302. return this.onMainButtonStateChangedObservable;
  69303. },
  69304. enumerable: true,
  69305. configurable: true
  69306. });
  69307. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  69308. /**
  69309. * Fired when the menu button on this controller is modified
  69310. */
  69311. get: function () {
  69312. return this.onSecondaryButtonStateChangedObservable;
  69313. },
  69314. enumerable: true,
  69315. configurable: true
  69316. });
  69317. /**
  69318. * Called once for each button that changed state since the last frame
  69319. * Vive mapping:
  69320. * 0: touchpad
  69321. * 1: trigger
  69322. * 2: left AND right buttons
  69323. * 3: menu button
  69324. * @param buttonIdx Which button index changed
  69325. * @param state New state of the button
  69326. * @param changes Which properties on the state changed since last frame
  69327. */
  69328. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69329. var notifyObject = state; //{ state: state, changes: changes };
  69330. switch (buttonIdx) {
  69331. case 0:
  69332. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69333. return;
  69334. case 1:// index trigger
  69335. if (this._defaultModel) {
  69336. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  69337. }
  69338. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69339. return;
  69340. case 2:// left AND right button
  69341. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69342. return;
  69343. case 3:
  69344. if (this._defaultModel) {
  69345. if (notifyObject.pressed) {
  69346. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69347. }
  69348. else {
  69349. (this._defaultModel.getChildren()[2]).position.y = 0;
  69350. }
  69351. }
  69352. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69353. return;
  69354. }
  69355. };
  69356. /**
  69357. * Base Url for the controller model.
  69358. */
  69359. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  69360. /**
  69361. * File name for the controller model.
  69362. */
  69363. ViveController.MODEL_FILENAME = 'wand.babylon';
  69364. return ViveController;
  69365. }(BABYLON.WebVRController));
  69366. BABYLON.ViveController = ViveController;
  69367. })(BABYLON || (BABYLON = {}));
  69368. //# sourceMappingURL=babylon.viveController.js.map
  69369. "use strict";
  69370. var BABYLON;
  69371. (function (BABYLON) {
  69372. /**
  69373. * Generic Controller
  69374. */
  69375. var GenericController = /** @class */ (function (_super) {
  69376. __extends(GenericController, _super);
  69377. /**
  69378. * Creates a new GenericController from a gamepad
  69379. * @param vrGamepad the gamepad that the controller should be created from
  69380. */
  69381. function GenericController(vrGamepad) {
  69382. return _super.call(this, vrGamepad) || this;
  69383. }
  69384. /**
  69385. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69386. * @param scene scene in which to add meshes
  69387. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69388. */
  69389. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69390. var _this = this;
  69391. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  69392. _this._defaultModel = newMeshes[1];
  69393. _this.attachToMesh(_this._defaultModel);
  69394. if (meshLoaded) {
  69395. meshLoaded(_this._defaultModel);
  69396. }
  69397. });
  69398. };
  69399. /**
  69400. * Called once for each button that changed state since the last frame
  69401. * @param buttonIdx Which button index changed
  69402. * @param state New state of the button
  69403. * @param changes Which properties on the state changed since last frame
  69404. */
  69405. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69406. console.log("Button id: " + buttonIdx + "state: ");
  69407. console.dir(state);
  69408. };
  69409. /**
  69410. * Base Url for the controller model.
  69411. */
  69412. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  69413. /**
  69414. * File name for the controller model.
  69415. */
  69416. GenericController.MODEL_FILENAME = 'generic.babylon';
  69417. return GenericController;
  69418. }(BABYLON.WebVRController));
  69419. BABYLON.GenericController = GenericController;
  69420. })(BABYLON || (BABYLON = {}));
  69421. //# sourceMappingURL=babylon.genericController.js.map
  69422. "use strict";
  69423. var BABYLON;
  69424. (function (BABYLON) {
  69425. /**
  69426. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  69427. */
  69428. var LoadedMeshInfo = /** @class */ (function () {
  69429. function LoadedMeshInfo() {
  69430. /**
  69431. * Map of the button meshes contained in the controller
  69432. */
  69433. this.buttonMeshes = {};
  69434. /**
  69435. * Map of the axis meshes contained in the controller
  69436. */
  69437. this.axisMeshes = {};
  69438. }
  69439. return LoadedMeshInfo;
  69440. }());
  69441. /**
  69442. * Defines the WindowsMotionController object that the state of the windows motion controller
  69443. */
  69444. var WindowsMotionController = /** @class */ (function (_super) {
  69445. __extends(WindowsMotionController, _super);
  69446. /**
  69447. * Creates a new WindowsMotionController from a gamepad
  69448. * @param vrGamepad the gamepad that the controller should be created from
  69449. */
  69450. function WindowsMotionController(vrGamepad) {
  69451. var _this = _super.call(this, vrGamepad) || this;
  69452. _this._mapping = {
  69453. // Semantic button names
  69454. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  69455. // A mapping of the button name to glTF model node name
  69456. // that should be transformed by button value.
  69457. buttonMeshNames: {
  69458. 'trigger': 'SELECT',
  69459. 'menu': 'MENU',
  69460. 'grip': 'GRASP',
  69461. 'thumbstick': 'THUMBSTICK_PRESS',
  69462. 'trackpad': 'TOUCHPAD_PRESS'
  69463. },
  69464. // This mapping is used to translate from the Motion Controller to Babylon semantics
  69465. buttonObservableNames: {
  69466. 'trigger': 'onTriggerStateChangedObservable',
  69467. 'menu': 'onSecondaryButtonStateChangedObservable',
  69468. 'grip': 'onMainButtonStateChangedObservable',
  69469. 'thumbstick': 'onPadStateChangedObservable',
  69470. 'trackpad': 'onTrackpadChangedObservable'
  69471. },
  69472. // A mapping of the axis name to glTF model node name
  69473. // that should be transformed by axis value.
  69474. // This array mirrors the browserGamepad.axes array, such that
  69475. // the mesh corresponding to axis 0 is in this array index 0.
  69476. axisMeshNames: [
  69477. 'THUMBSTICK_X',
  69478. 'THUMBSTICK_Y',
  69479. 'TOUCHPAD_TOUCH_X',
  69480. 'TOUCHPAD_TOUCH_Y'
  69481. ],
  69482. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  69483. };
  69484. /**
  69485. * Fired when the trackpad on this controller is clicked
  69486. */
  69487. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  69488. /**
  69489. * Fired when the trackpad on this controller is modified
  69490. */
  69491. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  69492. /**
  69493. * The current x and y values of this controller's trackpad
  69494. */
  69495. _this.trackpad = { x: 0, y: 0 };
  69496. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  69497. _this._loadedMeshInfo = null;
  69498. return _this;
  69499. }
  69500. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  69501. /**
  69502. * Fired when the trigger on this controller is modified
  69503. */
  69504. get: function () {
  69505. return this.onTriggerStateChangedObservable;
  69506. },
  69507. enumerable: true,
  69508. configurable: true
  69509. });
  69510. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  69511. /**
  69512. * Fired when the menu button on this controller is modified
  69513. */
  69514. get: function () {
  69515. return this.onSecondaryButtonStateChangedObservable;
  69516. },
  69517. enumerable: true,
  69518. configurable: true
  69519. });
  69520. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  69521. /**
  69522. * Fired when the grip button on this controller is modified
  69523. */
  69524. get: function () {
  69525. return this.onMainButtonStateChangedObservable;
  69526. },
  69527. enumerable: true,
  69528. configurable: true
  69529. });
  69530. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  69531. /**
  69532. * Fired when the thumbstick button on this controller is modified
  69533. */
  69534. get: function () {
  69535. return this.onPadStateChangedObservable;
  69536. },
  69537. enumerable: true,
  69538. configurable: true
  69539. });
  69540. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  69541. /**
  69542. * Fired when the touchpad button on this controller is modified
  69543. */
  69544. get: function () {
  69545. return this.onTrackpadChangedObservable;
  69546. },
  69547. enumerable: true,
  69548. configurable: true
  69549. });
  69550. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  69551. /**
  69552. * Fired when the touchpad values on this controller are modified
  69553. */
  69554. get: function () {
  69555. return this.onTrackpadValuesChangedObservable;
  69556. },
  69557. enumerable: true,
  69558. configurable: true
  69559. });
  69560. /**
  69561. * Called once per frame by the engine.
  69562. */
  69563. WindowsMotionController.prototype.update = function () {
  69564. _super.prototype.update.call(this);
  69565. if (this.browserGamepad.axes) {
  69566. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  69567. this.trackpad.x = this.browserGamepad["axes"][2];
  69568. this.trackpad.y = this.browserGamepad["axes"][3];
  69569. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  69570. }
  69571. // Only need to animate axes if there is a loaded mesh
  69572. if (this._loadedMeshInfo) {
  69573. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  69574. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  69575. }
  69576. }
  69577. }
  69578. };
  69579. /**
  69580. * Called once for each button that changed state since the last frame
  69581. * @param buttonIdx Which button index changed
  69582. * @param state New state of the button
  69583. * @param changes Which properties on the state changed since last frame
  69584. */
  69585. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69586. var buttonName = this._mapping.buttons[buttonIdx];
  69587. if (!buttonName) {
  69588. return;
  69589. }
  69590. // Only emit events for buttons that we know how to map from index to name
  69591. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  69592. if (observable) {
  69593. observable.notifyObservers(state);
  69594. }
  69595. this._lerpButtonTransform(buttonName, state.value);
  69596. };
  69597. /**
  69598. * Moves the buttons on the controller mesh based on their current state
  69599. * @param buttonName the name of the button to move
  69600. * @param buttonValue the value of the button which determines the buttons new position
  69601. */
  69602. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  69603. // If there is no loaded mesh, there is nothing to transform.
  69604. if (!this._loadedMeshInfo) {
  69605. return;
  69606. }
  69607. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  69608. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  69609. return;
  69610. }
  69611. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  69612. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  69613. };
  69614. /**
  69615. * Moves the axis on the controller mesh based on its current state
  69616. * @param axis the index of the axis
  69617. * @param axisValue the value of the axis which determines the meshes new position
  69618. * @ignore
  69619. */
  69620. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  69621. if (!this._loadedMeshInfo) {
  69622. return;
  69623. }
  69624. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  69625. if (!meshInfo) {
  69626. return;
  69627. }
  69628. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  69629. return;
  69630. }
  69631. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  69632. var lerpValue = axisValue * 0.5 + 0.5;
  69633. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  69634. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  69635. };
  69636. /**
  69637. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69638. * @param scene scene in which to add meshes
  69639. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69640. */
  69641. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  69642. var _this = this;
  69643. if (forceDefault === void 0) { forceDefault = false; }
  69644. var path;
  69645. var filename;
  69646. // Checking if GLB loader is present
  69647. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  69648. // Determine the device specific folder based on the ID suffix
  69649. var device = 'default';
  69650. if (this.id && !forceDefault) {
  69651. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  69652. device = ((match && match[0]) || device);
  69653. }
  69654. // Hand
  69655. if (this.hand === 'left') {
  69656. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  69657. }
  69658. else {
  69659. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  69660. }
  69661. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  69662. }
  69663. else {
  69664. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  69665. path = BABYLON.GenericController.MODEL_BASE_URL;
  69666. filename = BABYLON.GenericController.MODEL_FILENAME;
  69667. }
  69668. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  69669. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  69670. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  69671. if (!_this._loadedMeshInfo) {
  69672. return;
  69673. }
  69674. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  69675. _this.attachToMesh(_this._defaultModel);
  69676. if (meshLoaded) {
  69677. meshLoaded(_this._defaultModel);
  69678. }
  69679. }, null, function (scene, message) {
  69680. BABYLON.Tools.Log(message);
  69681. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  69682. if (!forceDefault) {
  69683. _this.initControllerMesh(scene, meshLoaded, true);
  69684. }
  69685. });
  69686. };
  69687. /**
  69688. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  69689. * can be transformed by button presses and axes values, based on this._mapping.
  69690. *
  69691. * @param scene scene in which the meshes exist
  69692. * @param meshes list of meshes that make up the controller model to process
  69693. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  69694. */
  69695. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  69696. var loadedMeshInfo = null;
  69697. // Create a new mesh to contain the glTF hierarchy
  69698. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  69699. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  69700. var childMesh = null;
  69701. for (var i = 0; i < meshes.length; i++) {
  69702. var mesh = meshes[i];
  69703. if (!mesh.parent) {
  69704. // Exclude controller meshes from picking results
  69705. mesh.isPickable = false;
  69706. // Handle root node, attach to the new parentMesh
  69707. childMesh = mesh;
  69708. break;
  69709. }
  69710. }
  69711. if (childMesh) {
  69712. childMesh.setParent(parentMesh);
  69713. // Create our mesh info. Note that this method will always return non-null.
  69714. loadedMeshInfo = this.createMeshInfo(parentMesh);
  69715. }
  69716. else {
  69717. BABYLON.Tools.Warn('Could not find root node in model file.');
  69718. }
  69719. return loadedMeshInfo;
  69720. };
  69721. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  69722. var loadedMeshInfo = new LoadedMeshInfo();
  69723. var i;
  69724. loadedMeshInfo.rootNode = rootNode;
  69725. // Reset the caches
  69726. loadedMeshInfo.buttonMeshes = {};
  69727. loadedMeshInfo.axisMeshes = {};
  69728. // Button Meshes
  69729. for (i = 0; i < this._mapping.buttons.length; i++) {
  69730. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  69731. if (!buttonMeshName) {
  69732. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  69733. continue;
  69734. }
  69735. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  69736. if (!buttonMesh) {
  69737. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  69738. continue;
  69739. }
  69740. var buttonMeshInfo = {
  69741. index: i,
  69742. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  69743. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  69744. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  69745. };
  69746. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  69747. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  69748. }
  69749. else {
  69750. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  69751. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  69752. '(VALUE: ' + !!buttonMeshInfo.value +
  69753. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  69754. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  69755. ')');
  69756. }
  69757. }
  69758. // Axis Meshes
  69759. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  69760. var axisMeshName = this._mapping.axisMeshNames[i];
  69761. if (!axisMeshName) {
  69762. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  69763. continue;
  69764. }
  69765. var axisMesh = getChildByName(rootNode, axisMeshName);
  69766. if (!axisMesh) {
  69767. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  69768. continue;
  69769. }
  69770. var axisMeshInfo = {
  69771. index: i,
  69772. value: getImmediateChildByName(axisMesh, 'VALUE'),
  69773. min: getImmediateChildByName(axisMesh, 'MIN'),
  69774. max: getImmediateChildByName(axisMesh, 'MAX')
  69775. };
  69776. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  69777. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  69778. }
  69779. else {
  69780. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  69781. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  69782. '(VALUE: ' + !!axisMeshInfo.value +
  69783. ', MIN: ' + !!axisMeshInfo.min +
  69784. ', MAX:' + !!axisMeshInfo.max +
  69785. ')');
  69786. }
  69787. }
  69788. // Pointing Ray
  69789. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  69790. if (!loadedMeshInfo.pointingPoseNode) {
  69791. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  69792. }
  69793. return loadedMeshInfo;
  69794. // Look through all children recursively. This will return null if no mesh exists with the given name.
  69795. function getChildByName(node, name) {
  69796. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  69797. }
  69798. // Look through only immediate children. This will return null if no mesh exists with the given name.
  69799. function getImmediateChildByName(node, name) {
  69800. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  69801. }
  69802. };
  69803. /**
  69804. * Gets the ray of the controller in the direction the controller is pointing
  69805. * @param length the length the resulting ray should be
  69806. * @returns a ray in the direction the controller is pointing
  69807. */
  69808. WindowsMotionController.prototype.getForwardRay = function (length) {
  69809. if (length === void 0) { length = 100; }
  69810. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  69811. return _super.prototype.getForwardRay.call(this, length);
  69812. }
  69813. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  69814. var origin = m.getTranslation();
  69815. var forward = new BABYLON.Vector3(0, 0, -1);
  69816. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69817. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69818. return new BABYLON.Ray(origin, direction, length);
  69819. };
  69820. /**
  69821. * Disposes of the controller
  69822. */
  69823. WindowsMotionController.prototype.dispose = function () {
  69824. _super.prototype.dispose.call(this);
  69825. this.onTrackpadChangedObservable.clear();
  69826. };
  69827. /**
  69828. * The base url used to load the left and right controller models
  69829. */
  69830. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  69831. /**
  69832. * The name of the left controller model file
  69833. */
  69834. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  69835. /**
  69836. * The name of the right controller model file
  69837. */
  69838. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  69839. /**
  69840. * The controller name prefix for this controller type
  69841. */
  69842. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  69843. /**
  69844. * The controller id pattern for this controller type
  69845. */
  69846. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  69847. return WindowsMotionController;
  69848. }(BABYLON.WebVRController));
  69849. BABYLON.WindowsMotionController = WindowsMotionController;
  69850. })(BABYLON || (BABYLON = {}));
  69851. //# sourceMappingURL=babylon.windowsMotionController.js.map
  69852. "use strict";
  69853. var BABYLON;
  69854. (function (BABYLON) {
  69855. /**
  69856. * Gear VR Controller
  69857. */
  69858. var GearVRController = /** @class */ (function (_super) {
  69859. __extends(GearVRController, _super);
  69860. /**
  69861. * Creates a new GearVRController from a gamepad
  69862. * @param vrGamepad the gamepad that the controller should be created from
  69863. */
  69864. function GearVRController(vrGamepad) {
  69865. var _this = _super.call(this, vrGamepad) || this;
  69866. _this._buttonIndexToObservableNameMap = [
  69867. 'onTrackpadChangedObservable',
  69868. 'onTriggerStateChangedObservable' // Trigger
  69869. ];
  69870. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  69871. return _this;
  69872. }
  69873. /**
  69874. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69875. * @param scene scene in which to add meshes
  69876. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69877. */
  69878. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69879. var _this = this;
  69880. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  69881. _this._defaultModel = newMeshes[1];
  69882. _this.attachToMesh(_this._defaultModel);
  69883. if (meshLoaded) {
  69884. meshLoaded(_this._defaultModel);
  69885. }
  69886. });
  69887. };
  69888. /**
  69889. * Called once for each button that changed state since the last frame
  69890. * @param buttonIdx Which button index changed
  69891. * @param state New state of the button
  69892. * @param changes Which properties on the state changed since last frame
  69893. */
  69894. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69895. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  69896. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  69897. // Only emit events for buttons that we know how to map from index to observable
  69898. var observable = this[observableName];
  69899. if (observable) {
  69900. observable.notifyObservers(state);
  69901. }
  69902. }
  69903. };
  69904. /**
  69905. * Base Url for the controller model.
  69906. */
  69907. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  69908. /**
  69909. * File name for the controller model.
  69910. */
  69911. GearVRController.MODEL_FILENAME = 'generic.babylon';
  69912. /**
  69913. * Gamepad Id prefix used to identify this controller.
  69914. */
  69915. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  69916. return GearVRController;
  69917. }(BABYLON.WebVRController));
  69918. BABYLON.GearVRController = GearVRController;
  69919. })(BABYLON || (BABYLON = {}));
  69920. //# sourceMappingURL=babylon.gearVRController.js.map
  69921. "use strict";
  69922. var BABYLON;
  69923. (function (BABYLON) {
  69924. /**
  69925. * Google Daydream controller
  69926. */
  69927. var DaydreamController = /** @class */ (function (_super) {
  69928. __extends(DaydreamController, _super);
  69929. /**
  69930. * Creates a new DaydreamController from a gamepad
  69931. * @param vrGamepad the gamepad that the controller should be created from
  69932. */
  69933. function DaydreamController(vrGamepad) {
  69934. var _this = _super.call(this, vrGamepad) || this;
  69935. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  69936. return _this;
  69937. }
  69938. /**
  69939. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69940. * @param scene scene in which to add meshes
  69941. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69942. */
  69943. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69944. var _this = this;
  69945. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  69946. _this._defaultModel = newMeshes[1];
  69947. _this.attachToMesh(_this._defaultModel);
  69948. if (meshLoaded) {
  69949. meshLoaded(_this._defaultModel);
  69950. }
  69951. });
  69952. };
  69953. /**
  69954. * Called once for each button that changed state since the last frame
  69955. * @param buttonIdx Which button index changed
  69956. * @param state New state of the button
  69957. * @param changes Which properties on the state changed since last frame
  69958. */
  69959. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69960. // Daydream controller only has 1 GamepadButton (on the trackpad).
  69961. if (buttonIdx === 0) {
  69962. var observable = this.onTriggerStateChangedObservable;
  69963. if (observable) {
  69964. observable.notifyObservers(state);
  69965. }
  69966. }
  69967. else {
  69968. // If the app or home buttons are ever made available
  69969. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  69970. }
  69971. };
  69972. /**
  69973. * Base Url for the controller model.
  69974. */
  69975. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  69976. /**
  69977. * File name for the controller model.
  69978. */
  69979. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  69980. /**
  69981. * Gamepad Id prefix used to identify Daydream Controller.
  69982. */
  69983. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  69984. return DaydreamController;
  69985. }(BABYLON.WebVRController));
  69986. BABYLON.DaydreamController = DaydreamController;
  69987. })(BABYLON || (BABYLON = {}));
  69988. //# sourceMappingURL=babylon.daydreamController.js.map
  69989. "use strict";
  69990. var BABYLON;
  69991. (function (BABYLON) {
  69992. var FollowCamera = /** @class */ (function (_super) {
  69993. __extends(FollowCamera, _super);
  69994. function FollowCamera(name, position, scene, lockedTarget) {
  69995. if (lockedTarget === void 0) { lockedTarget = null; }
  69996. var _this = _super.call(this, name, position, scene) || this;
  69997. _this.radius = 12;
  69998. _this.rotationOffset = 0;
  69999. _this.heightOffset = 4;
  70000. _this.cameraAcceleration = 0.05;
  70001. _this.maxCameraSpeed = 20;
  70002. _this.lockedTarget = lockedTarget;
  70003. return _this;
  70004. }
  70005. FollowCamera.prototype.getRadians = function (degrees) {
  70006. return degrees * Math.PI / 180;
  70007. };
  70008. FollowCamera.prototype.follow = function (cameraTarget) {
  70009. if (!cameraTarget)
  70010. return;
  70011. var yRotation;
  70012. if (cameraTarget.rotationQuaternion) {
  70013. var rotMatrix = new BABYLON.Matrix();
  70014. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  70015. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  70016. }
  70017. else {
  70018. yRotation = cameraTarget.rotation.y;
  70019. }
  70020. var radians = this.getRadians(this.rotationOffset) + yRotation;
  70021. var targetPosition = cameraTarget.getAbsolutePosition();
  70022. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  70023. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  70024. var dx = targetX - this.position.x;
  70025. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  70026. var dz = (targetZ) - this.position.z;
  70027. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  70028. var vy = dy * this.cameraAcceleration;
  70029. var vz = dz * this.cameraAcceleration * 2;
  70030. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  70031. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70032. }
  70033. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  70034. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70035. }
  70036. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  70037. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70038. }
  70039. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  70040. this.setTarget(targetPosition);
  70041. };
  70042. FollowCamera.prototype._checkInputs = function () {
  70043. _super.prototype._checkInputs.call(this);
  70044. if (this.lockedTarget) {
  70045. this.follow(this.lockedTarget);
  70046. }
  70047. };
  70048. FollowCamera.prototype.getClassName = function () {
  70049. return "FollowCamera";
  70050. };
  70051. __decorate([
  70052. BABYLON.serialize()
  70053. ], FollowCamera.prototype, "radius", void 0);
  70054. __decorate([
  70055. BABYLON.serialize()
  70056. ], FollowCamera.prototype, "rotationOffset", void 0);
  70057. __decorate([
  70058. BABYLON.serialize()
  70059. ], FollowCamera.prototype, "heightOffset", void 0);
  70060. __decorate([
  70061. BABYLON.serialize()
  70062. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  70063. __decorate([
  70064. BABYLON.serialize()
  70065. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  70066. __decorate([
  70067. BABYLON.serializeAsMeshReference("lockedTargetId")
  70068. ], FollowCamera.prototype, "lockedTarget", void 0);
  70069. return FollowCamera;
  70070. }(BABYLON.TargetCamera));
  70071. BABYLON.FollowCamera = FollowCamera;
  70072. var ArcFollowCamera = /** @class */ (function (_super) {
  70073. __extends(ArcFollowCamera, _super);
  70074. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  70075. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  70076. _this.alpha = alpha;
  70077. _this.beta = beta;
  70078. _this.radius = radius;
  70079. _this.target = target;
  70080. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  70081. _this.follow();
  70082. return _this;
  70083. }
  70084. ArcFollowCamera.prototype.follow = function () {
  70085. if (!this.target) {
  70086. return;
  70087. }
  70088. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  70089. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  70090. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  70091. var targetPosition = this.target.getAbsolutePosition();
  70092. this.position = targetPosition.add(this._cartesianCoordinates);
  70093. this.setTarget(targetPosition);
  70094. };
  70095. ArcFollowCamera.prototype._checkInputs = function () {
  70096. _super.prototype._checkInputs.call(this);
  70097. this.follow();
  70098. };
  70099. ArcFollowCamera.prototype.getClassName = function () {
  70100. return "ArcFollowCamera";
  70101. };
  70102. return ArcFollowCamera;
  70103. }(BABYLON.TargetCamera));
  70104. BABYLON.ArcFollowCamera = ArcFollowCamera;
  70105. })(BABYLON || (BABYLON = {}));
  70106. //# sourceMappingURL=babylon.followCamera.js.map
  70107. "use strict";
  70108. var BABYLON;
  70109. (function (BABYLON) {
  70110. // We're mainly based on the logic defined into the FreeCamera code
  70111. var UniversalCamera = /** @class */ (function (_super) {
  70112. __extends(UniversalCamera, _super);
  70113. //-- end properties for backward compatibility for inputs
  70114. function UniversalCamera(name, position, scene) {
  70115. var _this = _super.call(this, name, position, scene) || this;
  70116. _this.inputs.addGamepad();
  70117. return _this;
  70118. }
  70119. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  70120. //-- Begin properties for backward compatibility for inputs
  70121. get: function () {
  70122. var gamepad = this.inputs.attached["gamepad"];
  70123. if (gamepad)
  70124. return gamepad.gamepadAngularSensibility;
  70125. return 0;
  70126. },
  70127. set: function (value) {
  70128. var gamepad = this.inputs.attached["gamepad"];
  70129. if (gamepad)
  70130. gamepad.gamepadAngularSensibility = value;
  70131. },
  70132. enumerable: true,
  70133. configurable: true
  70134. });
  70135. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  70136. get: function () {
  70137. var gamepad = this.inputs.attached["gamepad"];
  70138. if (gamepad)
  70139. return gamepad.gamepadMoveSensibility;
  70140. return 0;
  70141. },
  70142. set: function (value) {
  70143. var gamepad = this.inputs.attached["gamepad"];
  70144. if (gamepad)
  70145. gamepad.gamepadMoveSensibility = value;
  70146. },
  70147. enumerable: true,
  70148. configurable: true
  70149. });
  70150. UniversalCamera.prototype.getClassName = function () {
  70151. return "UniversalCamera";
  70152. };
  70153. return UniversalCamera;
  70154. }(BABYLON.TouchCamera));
  70155. BABYLON.UniversalCamera = UniversalCamera;
  70156. })(BABYLON || (BABYLON = {}));
  70157. //# sourceMappingURL=babylon.universalCamera.js.map
  70158. "use strict";
  70159. var BABYLON;
  70160. (function (BABYLON) {
  70161. // We're mainly based on the logic defined into the FreeCamera code
  70162. var GamepadCamera = /** @class */ (function (_super) {
  70163. __extends(GamepadCamera, _super);
  70164. //-- end properties for backward compatibility for inputs
  70165. function GamepadCamera(name, position, scene) {
  70166. return _super.call(this, name, position, scene) || this;
  70167. }
  70168. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  70169. //-- Begin properties for backward compatibility for inputs
  70170. get: function () {
  70171. var gamepad = this.inputs.attached["gamepad"];
  70172. if (gamepad)
  70173. return gamepad.gamepadAngularSensibility;
  70174. return 0;
  70175. },
  70176. set: function (value) {
  70177. var gamepad = this.inputs.attached["gamepad"];
  70178. if (gamepad)
  70179. gamepad.gamepadAngularSensibility = value;
  70180. },
  70181. enumerable: true,
  70182. configurable: true
  70183. });
  70184. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  70185. get: function () {
  70186. var gamepad = this.inputs.attached["gamepad"];
  70187. if (gamepad)
  70188. return gamepad.gamepadMoveSensibility;
  70189. return 0;
  70190. },
  70191. set: function (value) {
  70192. var gamepad = this.inputs.attached["gamepad"];
  70193. if (gamepad)
  70194. gamepad.gamepadMoveSensibility = value;
  70195. },
  70196. enumerable: true,
  70197. configurable: true
  70198. });
  70199. GamepadCamera.prototype.getClassName = function () {
  70200. return "GamepadCamera";
  70201. };
  70202. return GamepadCamera;
  70203. }(BABYLON.UniversalCamera));
  70204. BABYLON.GamepadCamera = GamepadCamera;
  70205. })(BABYLON || (BABYLON = {}));
  70206. //# sourceMappingURL=babylon.gamepadCamera.js.map
  70207. "use strict";
  70208. var BABYLON;
  70209. (function (BABYLON) {
  70210. var PostProcessRenderPipelineManager = /** @class */ (function () {
  70211. function PostProcessRenderPipelineManager() {
  70212. this._renderPipelines = {};
  70213. }
  70214. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  70215. this._renderPipelines[renderPipeline._name] = renderPipeline;
  70216. };
  70217. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  70218. if (unique === void 0) { unique = false; }
  70219. var renderPipeline = this._renderPipelines[renderPipelineName];
  70220. if (!renderPipeline) {
  70221. return;
  70222. }
  70223. renderPipeline._attachCameras(cameras, unique);
  70224. };
  70225. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  70226. var renderPipeline = this._renderPipelines[renderPipelineName];
  70227. if (!renderPipeline) {
  70228. return;
  70229. }
  70230. renderPipeline._detachCameras(cameras);
  70231. };
  70232. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70233. var renderPipeline = this._renderPipelines[renderPipelineName];
  70234. if (!renderPipeline) {
  70235. return;
  70236. }
  70237. renderPipeline._enableEffect(renderEffectName, cameras);
  70238. };
  70239. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70240. var renderPipeline = this._renderPipelines[renderPipelineName];
  70241. if (!renderPipeline) {
  70242. return;
  70243. }
  70244. renderPipeline._disableEffect(renderEffectName, cameras);
  70245. };
  70246. PostProcessRenderPipelineManager.prototype.update = function () {
  70247. for (var renderPipelineName in this._renderPipelines) {
  70248. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70249. var pipeline = this._renderPipelines[renderPipelineName];
  70250. if (!pipeline.isSupported) {
  70251. pipeline.dispose();
  70252. delete this._renderPipelines[renderPipelineName];
  70253. }
  70254. else {
  70255. pipeline._update();
  70256. }
  70257. }
  70258. }
  70259. };
  70260. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  70261. for (var renderPipelineName in this._renderPipelines) {
  70262. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70263. var pipeline = this._renderPipelines[renderPipelineName];
  70264. pipeline._rebuild();
  70265. }
  70266. }
  70267. };
  70268. PostProcessRenderPipelineManager.prototype.dispose = function () {
  70269. for (var renderPipelineName in this._renderPipelines) {
  70270. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70271. var pipeline = this._renderPipelines[renderPipelineName];
  70272. pipeline.dispose();
  70273. }
  70274. }
  70275. };
  70276. return PostProcessRenderPipelineManager;
  70277. }());
  70278. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  70279. })(BABYLON || (BABYLON = {}));
  70280. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  70281. "use strict";
  70282. var BABYLON;
  70283. (function (BABYLON) {
  70284. /**
  70285. * This represents a set of one or more post processes in Babylon.
  70286. * A post process can be used to apply a shader to a texture after it is rendered.
  70287. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  70288. */
  70289. var PostProcessRenderEffect = /** @class */ (function () {
  70290. /**
  70291. * Instantiates a post process render effect.
  70292. * A post process can be used to apply a shader to a texture after it is rendered.
  70293. * @param engine The engine the effect is tied to
  70294. * @param name The name of the effect
  70295. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  70296. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  70297. */
  70298. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  70299. this._name = name;
  70300. this._singleInstance = singleInstance || true;
  70301. this._getPostProcesses = getPostProcesses;
  70302. this._cameras = {};
  70303. this._indicesForCamera = {};
  70304. this._postProcesses = {};
  70305. }
  70306. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  70307. /**
  70308. * Checks if all the post processes in the effect are supported.
  70309. */
  70310. get: function () {
  70311. for (var index in this._postProcesses) {
  70312. for (var ppIndex in this._postProcesses[index]) {
  70313. if (!this._postProcesses[index][ppIndex].isSupported) {
  70314. return false;
  70315. }
  70316. }
  70317. }
  70318. return true;
  70319. },
  70320. enumerable: true,
  70321. configurable: true
  70322. });
  70323. /**
  70324. * Updates the current state of the effect
  70325. */
  70326. PostProcessRenderEffect.prototype._update = function () {
  70327. };
  70328. /**
  70329. * Attaches the effect on cameras
  70330. * @param cameras The camera to attach to.
  70331. */
  70332. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  70333. var _this = this;
  70334. var cameraKey;
  70335. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70336. if (!cams) {
  70337. return;
  70338. }
  70339. for (var i = 0; i < cams.length; i++) {
  70340. var camera = cams[i];
  70341. var cameraName = camera.name;
  70342. if (this._singleInstance) {
  70343. cameraKey = 0;
  70344. }
  70345. else {
  70346. cameraKey = cameraName;
  70347. }
  70348. if (!this._postProcesses[cameraKey]) {
  70349. var postProcess = this._getPostProcesses();
  70350. if (postProcess) {
  70351. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  70352. }
  70353. }
  70354. if (!this._indicesForCamera[cameraName]) {
  70355. this._indicesForCamera[cameraName] = [];
  70356. }
  70357. this._postProcesses[cameraKey].forEach(function (postProcess) {
  70358. var index = camera.attachPostProcess(postProcess);
  70359. _this._indicesForCamera[cameraName].push(index);
  70360. });
  70361. if (!this._cameras[cameraName]) {
  70362. this._cameras[cameraName] = camera;
  70363. }
  70364. }
  70365. };
  70366. /**
  70367. * Detatches the effect on cameras
  70368. * @param cameras The camera to detatch from.
  70369. */
  70370. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  70371. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70372. if (!cams) {
  70373. return;
  70374. }
  70375. for (var i = 0; i < cams.length; i++) {
  70376. var camera = cams[i];
  70377. var cameraName = camera.name;
  70378. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70379. camera.detachPostProcess(postProcess);
  70380. });
  70381. if (this._cameras[cameraName]) {
  70382. //this._indicesForCamera.splice(index, 1);
  70383. this._cameras[cameraName] = null;
  70384. }
  70385. }
  70386. };
  70387. /**
  70388. * Enables the effect on given cameras
  70389. * @param cameras The camera to enable.
  70390. */
  70391. PostProcessRenderEffect.prototype._enable = function (cameras) {
  70392. var _this = this;
  70393. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70394. if (!cams) {
  70395. return;
  70396. }
  70397. for (var i = 0; i < cams.length; i++) {
  70398. var camera = cams[i];
  70399. var cameraName = camera.name;
  70400. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  70401. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  70402. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70403. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  70404. });
  70405. }
  70406. }
  70407. }
  70408. };
  70409. /**
  70410. * Disables the effect on the given cameras
  70411. * @param cameras The camera to disable.
  70412. */
  70413. PostProcessRenderEffect.prototype._disable = function (cameras) {
  70414. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70415. if (!cams) {
  70416. return;
  70417. }
  70418. for (var i = 0; i < cams.length; i++) {
  70419. var camera = cams[i];
  70420. var cameraName = camera.name;
  70421. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70422. camera.detachPostProcess(postProcess);
  70423. });
  70424. }
  70425. };
  70426. /**
  70427. * Gets a list of the post processes contained in the effect.
  70428. * @param camera The camera to get the post processes on.
  70429. * @returns The list of the post processes in the effect.
  70430. */
  70431. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  70432. if (this._singleInstance) {
  70433. return this._postProcesses[0];
  70434. }
  70435. else {
  70436. if (!camera) {
  70437. return null;
  70438. }
  70439. return this._postProcesses[camera.name];
  70440. }
  70441. };
  70442. return PostProcessRenderEffect;
  70443. }());
  70444. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  70445. })(BABYLON || (BABYLON = {}));
  70446. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  70447. "use strict";
  70448. var BABYLON;
  70449. (function (BABYLON) {
  70450. var PostProcessRenderPipeline = /** @class */ (function () {
  70451. function PostProcessRenderPipeline(engine, name) {
  70452. this.engine = engine;
  70453. this._name = name;
  70454. this._renderEffects = {};
  70455. this._renderEffectsForIsolatedPass = new Array();
  70456. this._cameras = [];
  70457. }
  70458. PostProcessRenderPipeline.prototype.getClassName = function () {
  70459. return "PostProcessRenderPipeline";
  70460. };
  70461. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  70462. get: function () {
  70463. for (var renderEffectName in this._renderEffects) {
  70464. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70465. if (!this._renderEffects[renderEffectName].isSupported) {
  70466. return false;
  70467. }
  70468. }
  70469. }
  70470. return true;
  70471. },
  70472. enumerable: true,
  70473. configurable: true
  70474. });
  70475. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  70476. this._renderEffects[renderEffect._name] = renderEffect;
  70477. };
  70478. // private
  70479. PostProcessRenderPipeline.prototype._rebuild = function () {
  70480. };
  70481. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  70482. var renderEffects = this._renderEffects[renderEffectName];
  70483. if (!renderEffects) {
  70484. return;
  70485. }
  70486. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  70487. };
  70488. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  70489. var renderEffects = this._renderEffects[renderEffectName];
  70490. if (!renderEffects) {
  70491. return;
  70492. }
  70493. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  70494. };
  70495. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  70496. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70497. if (!cams) {
  70498. return;
  70499. }
  70500. var indicesToDelete = [];
  70501. var i;
  70502. for (i = 0; i < cams.length; i++) {
  70503. var camera = cams[i];
  70504. var cameraName = camera.name;
  70505. if (this._cameras.indexOf(camera) === -1) {
  70506. this._cameras[cameraName] = camera;
  70507. }
  70508. else if (unique) {
  70509. indicesToDelete.push(i);
  70510. }
  70511. }
  70512. for (i = 0; i < indicesToDelete.length; i++) {
  70513. cameras.splice(indicesToDelete[i], 1);
  70514. }
  70515. for (var renderEffectName in this._renderEffects) {
  70516. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70517. this._renderEffects[renderEffectName]._attachCameras(cams);
  70518. }
  70519. }
  70520. };
  70521. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  70522. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70523. if (!cams) {
  70524. return;
  70525. }
  70526. for (var renderEffectName in this._renderEffects) {
  70527. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70528. this._renderEffects[renderEffectName]._detachCameras(cams);
  70529. }
  70530. }
  70531. for (var i = 0; i < cams.length; i++) {
  70532. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  70533. }
  70534. };
  70535. PostProcessRenderPipeline.prototype._update = function () {
  70536. for (var renderEffectName in this._renderEffects) {
  70537. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70538. this._renderEffects[renderEffectName]._update();
  70539. }
  70540. }
  70541. for (var i = 0; i < this._cameras.length; i++) {
  70542. var cameraName = this._cameras[i].name;
  70543. if (this._renderEffectsForIsolatedPass[cameraName]) {
  70544. this._renderEffectsForIsolatedPass[cameraName]._update();
  70545. }
  70546. }
  70547. };
  70548. PostProcessRenderPipeline.prototype._reset = function () {
  70549. this._renderEffects = {};
  70550. this._renderEffectsForIsolatedPass = new Array();
  70551. };
  70552. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  70553. // 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)
  70554. var effectKeys = Object.keys(this._renderEffects);
  70555. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  70556. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  70557. if (postProcesses) {
  70558. postProcesses[0].samples = sampleCount;
  70559. return true;
  70560. }
  70561. }
  70562. return false;
  70563. };
  70564. PostProcessRenderPipeline.prototype.dispose = function () {
  70565. // Must be implemented by children
  70566. };
  70567. __decorate([
  70568. BABYLON.serialize()
  70569. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  70570. return PostProcessRenderPipeline;
  70571. }());
  70572. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  70573. })(BABYLON || (BABYLON = {}));
  70574. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  70575. "use strict";
  70576. var BABYLON;
  70577. (function (BABYLON) {
  70578. /**
  70579. * This represents a depth renderer in Babylon.
  70580. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  70581. */
  70582. var DepthRenderer = /** @class */ (function () {
  70583. /**
  70584. * Instantiates a depth renderer
  70585. * @param scene The scene the renderer belongs to
  70586. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  70587. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  70588. */
  70589. function DepthRenderer(scene, type, camera) {
  70590. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  70591. if (camera === void 0) { camera = null; }
  70592. var _this = this;
  70593. this._scene = scene;
  70594. this._camera = camera;
  70595. var engine = scene.getEngine();
  70596. // Render target
  70597. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  70598. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70599. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70600. this._depthMap.refreshRate = 1;
  70601. this._depthMap.renderParticles = false;
  70602. this._depthMap.renderList = null;
  70603. // Camera to get depth map from to support multiple concurrent cameras
  70604. this._depthMap.activeCamera = this._camera;
  70605. this._depthMap.ignoreCameraViewport = true;
  70606. this._depthMap.useCameraPostProcesses = false;
  70607. // set default depth value to 1.0 (far away)
  70608. this._depthMap.onClearObservable.add(function (engine) {
  70609. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  70610. });
  70611. // Custom render function
  70612. var renderSubMesh = function (subMesh) {
  70613. var mesh = subMesh.getRenderingMesh();
  70614. var scene = _this._scene;
  70615. var engine = scene.getEngine();
  70616. var material = subMesh.getMaterial();
  70617. if (!material) {
  70618. return;
  70619. }
  70620. // Culling and reverse (right handed system)
  70621. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70622. // Managing instances
  70623. var batch = mesh._getInstancesRenderList(subMesh._id);
  70624. if (batch.mustReturn) {
  70625. return;
  70626. }
  70627. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70628. var camera = _this._camera || scene.activeCamera;
  70629. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  70630. engine.enableEffect(_this._effect);
  70631. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70632. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70633. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  70634. // Alpha test
  70635. if (material && material.needAlphaTesting()) {
  70636. var alphaTexture = material.getAlphaTestTexture();
  70637. if (alphaTexture) {
  70638. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70639. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70640. }
  70641. }
  70642. // Bones
  70643. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70644. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70645. }
  70646. // Draw
  70647. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70648. }
  70649. };
  70650. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70651. var index;
  70652. if (depthOnlySubMeshes.length) {
  70653. engine.setColorWrite(false);
  70654. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70655. renderSubMesh(depthOnlySubMeshes.data[index]);
  70656. }
  70657. engine.setColorWrite(true);
  70658. }
  70659. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70660. renderSubMesh(opaqueSubMeshes.data[index]);
  70661. }
  70662. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70663. renderSubMesh(alphaTestSubMeshes.data[index]);
  70664. }
  70665. };
  70666. }
  70667. /**
  70668. * Creates the depth rendering effect and checks if the effect is ready.
  70669. * @param subMesh The submesh to be used to render the depth map of
  70670. * @param useInstances If multiple world instances should be used
  70671. * @returns if the depth renderer is ready to render the depth map
  70672. */
  70673. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  70674. var material = subMesh.getMaterial();
  70675. if (material.disableDepthWrite) {
  70676. return false;
  70677. }
  70678. var defines = [];
  70679. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70680. var mesh = subMesh.getMesh();
  70681. // Alpha test
  70682. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  70683. defines.push("#define ALPHATEST");
  70684. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70685. attribs.push(BABYLON.VertexBuffer.UVKind);
  70686. defines.push("#define UV1");
  70687. }
  70688. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70689. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70690. defines.push("#define UV2");
  70691. }
  70692. }
  70693. // Bones
  70694. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70695. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70696. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70697. if (mesh.numBoneInfluencers > 4) {
  70698. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70699. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70700. }
  70701. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70702. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70703. }
  70704. else {
  70705. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70706. }
  70707. // Instances
  70708. if (useInstances) {
  70709. defines.push("#define INSTANCES");
  70710. attribs.push("world0");
  70711. attribs.push("world1");
  70712. attribs.push("world2");
  70713. attribs.push("world3");
  70714. }
  70715. // Get correct effect
  70716. var join = defines.join("\n");
  70717. if (this._cachedDefines !== join) {
  70718. this._cachedDefines = join;
  70719. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  70720. }
  70721. return this._effect.isReady();
  70722. };
  70723. /**
  70724. * Gets the texture which the depth map will be written to.
  70725. * @returns The depth map texture
  70726. */
  70727. DepthRenderer.prototype.getDepthMap = function () {
  70728. return this._depthMap;
  70729. };
  70730. /**
  70731. * Disposes of the depth renderer.
  70732. */
  70733. DepthRenderer.prototype.dispose = function () {
  70734. this._depthMap.dispose();
  70735. };
  70736. return DepthRenderer;
  70737. }());
  70738. BABYLON.DepthRenderer = DepthRenderer;
  70739. })(BABYLON || (BABYLON = {}));
  70740. //# sourceMappingURL=babylon.depthRenderer.js.map
  70741. "use strict";
  70742. var BABYLON;
  70743. (function (BABYLON) {
  70744. var SSAORenderingPipeline = /** @class */ (function (_super) {
  70745. __extends(SSAORenderingPipeline, _super);
  70746. /**
  70747. * @constructor
  70748. * @param {string} name - The rendering pipeline name
  70749. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70750. * @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 }
  70751. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70752. */
  70753. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  70754. var _this = _super.call(this, scene.getEngine(), name) || this;
  70755. // Members
  70756. /**
  70757. * The PassPostProcess id in the pipeline that contains the original scene color
  70758. */
  70759. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  70760. /**
  70761. * The SSAO PostProcess id in the pipeline
  70762. */
  70763. _this.SSAORenderEffect = "SSAORenderEffect";
  70764. /**
  70765. * The horizontal blur PostProcess id in the pipeline
  70766. */
  70767. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  70768. /**
  70769. * The vertical blur PostProcess id in the pipeline
  70770. */
  70771. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  70772. /**
  70773. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  70774. */
  70775. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  70776. /**
  70777. * The output strength of the SSAO post-process. Default value is 1.0.
  70778. */
  70779. _this.totalStrength = 1.0;
  70780. /**
  70781. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  70782. */
  70783. _this.radius = 0.0001;
  70784. /**
  70785. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  70786. * Must not be equal to fallOff and superior to fallOff.
  70787. * Default value is 0.975
  70788. */
  70789. _this.area = 0.0075;
  70790. /**
  70791. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  70792. * Must not be equal to area and inferior to area.
  70793. * Default value is 0.0
  70794. */
  70795. _this.fallOff = 0.000001;
  70796. /**
  70797. * The base color of the SSAO post-process
  70798. * The final result is "base + ssao" between [0, 1]
  70799. */
  70800. _this.base = 0.5;
  70801. _this._firstUpdate = true;
  70802. _this._scene = scene;
  70803. // Set up assets
  70804. _this._createRandomTexture();
  70805. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  70806. var ssaoRatio = ratio.ssaoRatio || ratio;
  70807. var combineRatio = ratio.combineRatio || ratio;
  70808. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  70809. _this._createSSAOPostProcess(ssaoRatio);
  70810. _this._createBlurPostProcess(ssaoRatio);
  70811. _this._createSSAOCombinePostProcess(combineRatio);
  70812. // Set up pipeline
  70813. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  70814. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  70815. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  70816. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  70817. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  70818. // Finish
  70819. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70820. if (cameras)
  70821. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  70822. return _this;
  70823. }
  70824. // Public Methods
  70825. /**
  70826. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  70827. */
  70828. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  70829. if (disableDepthRender === void 0) { disableDepthRender = false; }
  70830. for (var i = 0; i < this._scene.cameras.length; i++) {
  70831. var camera = this._scene.cameras[i];
  70832. this._originalColorPostProcess.dispose(camera);
  70833. this._ssaoPostProcess.dispose(camera);
  70834. this._blurHPostProcess.dispose(camera);
  70835. this._blurVPostProcess.dispose(camera);
  70836. this._ssaoCombinePostProcess.dispose(camera);
  70837. }
  70838. this._randomTexture.dispose();
  70839. if (disableDepthRender)
  70840. this._scene.disableDepthRenderer();
  70841. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  70842. _super.prototype.dispose.call(this);
  70843. };
  70844. // Private Methods
  70845. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  70846. var _this = this;
  70847. var size = 16;
  70848. 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);
  70849. 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);
  70850. this._blurHPostProcess.onActivateObservable.add(function () {
  70851. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  70852. _this._blurHPostProcess.kernel = size * dw;
  70853. });
  70854. this._blurVPostProcess.onActivateObservable.add(function () {
  70855. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  70856. _this._blurVPostProcess.kernel = size * dw;
  70857. });
  70858. };
  70859. SSAORenderingPipeline.prototype._rebuild = function () {
  70860. this._firstUpdate = true;
  70861. _super.prototype._rebuild.call(this);
  70862. };
  70863. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  70864. var _this = this;
  70865. var numSamples = 16;
  70866. var sampleSphere = [
  70867. 0.5381, 0.1856, -0.4319,
  70868. 0.1379, 0.2486, 0.4430,
  70869. 0.3371, 0.5679, -0.0057,
  70870. -0.6999, -0.0451, -0.0019,
  70871. 0.0689, -0.1598, -0.8547,
  70872. 0.0560, 0.0069, -0.1843,
  70873. -0.0146, 0.1402, 0.0762,
  70874. 0.0100, -0.1924, -0.0344,
  70875. -0.3577, -0.5301, -0.4358,
  70876. -0.3169, 0.1063, 0.0158,
  70877. 0.0103, -0.5869, 0.0046,
  70878. -0.0897, -0.4940, 0.3287,
  70879. 0.7119, -0.0154, -0.0918,
  70880. -0.0533, 0.0596, -0.5411,
  70881. 0.0352, -0.0631, 0.5460,
  70882. -0.4776, 0.2847, -0.0271
  70883. ];
  70884. var samplesFactor = 1.0 / numSamples;
  70885. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  70886. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  70887. "area", "fallOff", "base", "range", "viewport"
  70888. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  70889. this._ssaoPostProcess.onApply = function (effect) {
  70890. if (_this._firstUpdate) {
  70891. effect.setArray3("sampleSphere", sampleSphere);
  70892. effect.setFloat("samplesFactor", samplesFactor);
  70893. effect.setFloat("randTextureTiles", 4.0);
  70894. }
  70895. effect.setFloat("totalStrength", _this.totalStrength);
  70896. effect.setFloat("radius", _this.radius);
  70897. effect.setFloat("area", _this.area);
  70898. effect.setFloat("fallOff", _this.fallOff);
  70899. effect.setFloat("base", _this.base);
  70900. effect.setTexture("textureSampler", _this._depthTexture);
  70901. effect.setTexture("randomSampler", _this._randomTexture);
  70902. };
  70903. };
  70904. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  70905. var _this = this;
  70906. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  70907. this._ssaoCombinePostProcess.onApply = function (effect) {
  70908. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  70909. };
  70910. };
  70911. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  70912. var size = 512;
  70913. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70914. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  70915. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  70916. var context = this._randomTexture.getContext();
  70917. var rand = function (min, max) {
  70918. return Math.random() * (max - min) + min;
  70919. };
  70920. var randVector = BABYLON.Vector3.Zero();
  70921. for (var x = 0; x < size; x++) {
  70922. for (var y = 0; y < size; y++) {
  70923. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  70924. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  70925. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  70926. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  70927. context.fillRect(x, y, 1, 1);
  70928. }
  70929. }
  70930. this._randomTexture.update(false);
  70931. };
  70932. __decorate([
  70933. BABYLON.serialize()
  70934. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  70935. __decorate([
  70936. BABYLON.serialize()
  70937. ], SSAORenderingPipeline.prototype, "radius", void 0);
  70938. __decorate([
  70939. BABYLON.serialize()
  70940. ], SSAORenderingPipeline.prototype, "area", void 0);
  70941. __decorate([
  70942. BABYLON.serialize()
  70943. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  70944. __decorate([
  70945. BABYLON.serialize()
  70946. ], SSAORenderingPipeline.prototype, "base", void 0);
  70947. return SSAORenderingPipeline;
  70948. }(BABYLON.PostProcessRenderPipeline));
  70949. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  70950. })(BABYLON || (BABYLON = {}));
  70951. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  70952. "use strict";
  70953. var BABYLON;
  70954. (function (BABYLON) {
  70955. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  70956. __extends(SSAO2RenderingPipeline, _super);
  70957. /**
  70958. * @constructor
  70959. * @param {string} name - The rendering pipeline name
  70960. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70961. * @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 }
  70962. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70963. */
  70964. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  70965. var _this = _super.call(this, scene.getEngine(), name) || this;
  70966. // Members
  70967. /**
  70968. * The PassPostProcess id in the pipeline that contains the original scene color
  70969. */
  70970. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  70971. /**
  70972. * The SSAO PostProcess id in the pipeline
  70973. */
  70974. _this.SSAORenderEffect = "SSAORenderEffect";
  70975. /**
  70976. * The horizontal blur PostProcess id in the pipeline
  70977. */
  70978. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  70979. /**
  70980. * The vertical blur PostProcess id in the pipeline
  70981. */
  70982. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  70983. /**
  70984. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  70985. */
  70986. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  70987. /**
  70988. * The output strength of the SSAO post-process. Default value is 1.0.
  70989. */
  70990. _this.totalStrength = 1.0;
  70991. /**
  70992. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  70993. */
  70994. _this.maxZ = 100.0;
  70995. /**
  70996. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  70997. */
  70998. _this.minZAspect = 0.2;
  70999. /**
  71000. * Number of samples used for the SSAO calculations. Default value is 8
  71001. */
  71002. _this._samples = 8;
  71003. /**
  71004. * Are we using bilateral blur ?
  71005. */
  71006. _this._expensiveBlur = true;
  71007. /**
  71008. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  71009. */
  71010. _this.radius = 2.0;
  71011. /**
  71012. * The base color of the SSAO post-process
  71013. * The final result is "base + ssao" between [0, 1]
  71014. */
  71015. _this.base = 0.1;
  71016. _this._firstUpdate = true;
  71017. _this._scene = scene;
  71018. if (!_this.isSupported) {
  71019. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  71020. return _this;
  71021. }
  71022. var ssaoRatio = ratio.ssaoRatio || ratio;
  71023. var blurRatio = ratio.blurRatio || ratio;
  71024. // Set up assets
  71025. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  71026. _this._createRandomTexture();
  71027. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  71028. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  71029. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71030. _this._createSSAOPostProcess(1.0);
  71031. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  71032. _this._createSSAOCombinePostProcess(blurRatio);
  71033. // Set up pipeline
  71034. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71035. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71036. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71037. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71038. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71039. // Finish
  71040. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71041. if (cameras)
  71042. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71043. return _this;
  71044. }
  71045. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  71046. get: function () {
  71047. return this._samples;
  71048. },
  71049. set: function (n) {
  71050. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  71051. this._samples = n;
  71052. this._sampleSphere = this._generateHemisphere();
  71053. this._firstUpdate = true;
  71054. },
  71055. enumerable: true,
  71056. configurable: true
  71057. });
  71058. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  71059. get: function () {
  71060. return this._expensiveBlur;
  71061. },
  71062. set: function (b) {
  71063. 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"]);
  71064. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  71065. this._expensiveBlur = b;
  71066. this._firstUpdate = true;
  71067. },
  71068. enumerable: true,
  71069. configurable: true
  71070. });
  71071. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  71072. /**
  71073. * Support test.
  71074. */
  71075. get: function () {
  71076. var engine = BABYLON.Engine.LastCreatedEngine;
  71077. if (!engine) {
  71078. return false;
  71079. }
  71080. return engine.getCaps().drawBuffersExtension;
  71081. },
  71082. enumerable: true,
  71083. configurable: true
  71084. });
  71085. // Public Methods
  71086. /**
  71087. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71088. */
  71089. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  71090. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  71091. for (var i = 0; i < this._scene.cameras.length; i++) {
  71092. var camera = this._scene.cameras[i];
  71093. this._originalColorPostProcess.dispose(camera);
  71094. this._ssaoPostProcess.dispose(camera);
  71095. this._blurHPostProcess.dispose(camera);
  71096. this._blurVPostProcess.dispose(camera);
  71097. this._ssaoCombinePostProcess.dispose(camera);
  71098. }
  71099. this._randomTexture.dispose();
  71100. if (disableGeometryBufferRenderer)
  71101. this._scene.disableGeometryBufferRenderer();
  71102. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71103. _super.prototype.dispose.call(this);
  71104. };
  71105. // Private Methods
  71106. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  71107. var _this = this;
  71108. this._samplerOffsets = [];
  71109. var expensive = this.expensiveBlur;
  71110. for (var i = -8; i < 8; i++) {
  71111. this._samplerOffsets.push(i * 2 + 0.5);
  71112. }
  71113. 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");
  71114. this._blurHPostProcess.onApply = function (effect) {
  71115. if (!_this._scene.activeCamera) {
  71116. return;
  71117. }
  71118. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  71119. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71120. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71121. effect.setFloat("radius", _this.radius);
  71122. effect.setTexture("depthSampler", _this._depthTexture);
  71123. if (_this._firstUpdate) {
  71124. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71125. }
  71126. };
  71127. 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");
  71128. this._blurVPostProcess.onApply = function (effect) {
  71129. if (!_this._scene.activeCamera) {
  71130. return;
  71131. }
  71132. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  71133. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71134. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71135. effect.setFloat("radius", _this.radius);
  71136. effect.setTexture("depthSampler", _this._depthTexture);
  71137. if (_this._firstUpdate) {
  71138. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71139. _this._firstUpdate = false;
  71140. }
  71141. };
  71142. };
  71143. SSAO2RenderingPipeline.prototype._rebuild = function () {
  71144. this._firstUpdate = true;
  71145. _super.prototype._rebuild.call(this);
  71146. };
  71147. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  71148. var numSamples = this.samples;
  71149. var result = [];
  71150. var vector, scale;
  71151. var rand = function (min, max) {
  71152. return Math.random() * (max - min) + min;
  71153. };
  71154. var i = 0;
  71155. while (i < numSamples) {
  71156. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  71157. vector.normalize();
  71158. scale = i / numSamples;
  71159. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  71160. vector.scaleInPlace(scale);
  71161. result.push(vector.x, vector.y, vector.z);
  71162. i++;
  71163. }
  71164. return result;
  71165. };
  71166. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71167. var _this = this;
  71168. var numSamples = this.samples;
  71169. this._sampleSphere = this._generateHemisphere();
  71170. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  71171. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71172. "base", "range", "projection", "near", "far", "texelSize",
  71173. "xViewport", "yViewport", "maxZ", "minZAspect"
  71174. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71175. this._ssaoPostProcess.onApply = function (effect) {
  71176. if (_this._firstUpdate) {
  71177. effect.setArray3("sampleSphere", _this._sampleSphere);
  71178. effect.setFloat("randTextureTiles", 4.0);
  71179. }
  71180. if (!_this._scene.activeCamera) {
  71181. return;
  71182. }
  71183. effect.setFloat("samplesFactor", 1 / _this.samples);
  71184. effect.setFloat("totalStrength", _this.totalStrength);
  71185. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  71186. effect.setFloat("radius", _this.radius);
  71187. effect.setFloat("maxZ", _this.maxZ);
  71188. effect.setFloat("minZAspect", _this.minZAspect);
  71189. effect.setFloat("base", _this.base);
  71190. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71191. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71192. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  71193. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  71194. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  71195. effect.setTexture("textureSampler", _this._depthTexture);
  71196. effect.setTexture("normalSampler", _this._normalTexture);
  71197. effect.setTexture("randomSampler", _this._randomTexture);
  71198. };
  71199. };
  71200. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71201. var _this = this;
  71202. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71203. this._ssaoCombinePostProcess.onApply = function (effect) {
  71204. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71205. };
  71206. };
  71207. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  71208. var size = 512;
  71209. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71210. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71211. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71212. var context = this._randomTexture.getContext();
  71213. var rand = function (min, max) {
  71214. return Math.random() * (max - min) + min;
  71215. };
  71216. var randVector = BABYLON.Vector3.Zero();
  71217. for (var x = 0; x < size; x++) {
  71218. for (var y = 0; y < size; y++) {
  71219. randVector.x = rand(0.0, 1.0);
  71220. randVector.y = rand(0.0, 1.0);
  71221. randVector.z = 0.0;
  71222. randVector.normalize();
  71223. randVector.scaleInPlace(255);
  71224. randVector.x = Math.floor(randVector.x);
  71225. randVector.y = Math.floor(randVector.y);
  71226. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71227. context.fillRect(x, y, 1, 1);
  71228. }
  71229. }
  71230. this._randomTexture.update(false);
  71231. };
  71232. __decorate([
  71233. BABYLON.serialize()
  71234. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  71235. __decorate([
  71236. BABYLON.serialize()
  71237. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  71238. __decorate([
  71239. BABYLON.serialize()
  71240. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  71241. __decorate([
  71242. BABYLON.serialize("samples")
  71243. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  71244. __decorate([
  71245. BABYLON.serialize("expensiveBlur")
  71246. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  71247. __decorate([
  71248. BABYLON.serialize()
  71249. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  71250. __decorate([
  71251. BABYLON.serialize()
  71252. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  71253. return SSAO2RenderingPipeline;
  71254. }(BABYLON.PostProcessRenderPipeline));
  71255. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  71256. })(BABYLON || (BABYLON = {}));
  71257. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  71258. "use strict";
  71259. // BABYLON.JS Chromatic Aberration GLSL Shader
  71260. // Author: Olivier Guyot
  71261. // Separates very slightly R, G and B colors on the edges of the screen
  71262. // Inspired by Francois Tarlier & Martins Upitis
  71263. var BABYLON;
  71264. (function (BABYLON) {
  71265. var LensRenderingPipeline = /** @class */ (function (_super) {
  71266. __extends(LensRenderingPipeline, _super);
  71267. /**
  71268. * @constructor
  71269. *
  71270. * Effect parameters are as follow:
  71271. * {
  71272. * chromatic_aberration: number; // from 0 to x (1 for realism)
  71273. * edge_blur: number; // from 0 to x (1 for realism)
  71274. * distortion: number; // from 0 to x (1 for realism)
  71275. * grain_amount: number; // from 0 to 1
  71276. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  71277. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  71278. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  71279. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  71280. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  71281. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  71282. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  71283. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  71284. * }
  71285. * Note: if an effect parameter is unset, effect is disabled
  71286. *
  71287. * @param {string} name - The rendering pipeline name
  71288. * @param {object} parameters - An object containing all parameters (see above)
  71289. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71290. * @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)
  71291. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71292. */
  71293. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  71294. if (ratio === void 0) { ratio = 1.0; }
  71295. var _this = _super.call(this, scene.getEngine(), name) || this;
  71296. // Lens effects can be of the following:
  71297. // - chromatic aberration (slight shift of RGB colors)
  71298. // - blur on the edge of the lens
  71299. // - lens distortion
  71300. // - depth-of-field blur & highlights enhancing
  71301. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  71302. // - grain effect (noise or custom texture)
  71303. // Two additional texture samplers are needed:
  71304. // - depth map (for depth-of-field)
  71305. // - grain texture
  71306. /**
  71307. * The chromatic aberration PostProcess id in the pipeline
  71308. */
  71309. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  71310. /**
  71311. * The highlights enhancing PostProcess id in the pipeline
  71312. */
  71313. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  71314. /**
  71315. * The depth-of-field PostProcess id in the pipeline
  71316. */
  71317. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  71318. _this._scene = scene;
  71319. // Fetch texture samplers
  71320. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71321. if (parameters.grain_texture) {
  71322. _this._grainTexture = parameters.grain_texture;
  71323. }
  71324. else {
  71325. _this._createGrainTexture();
  71326. }
  71327. // save parameters
  71328. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  71329. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  71330. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  71331. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  71332. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  71333. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  71334. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  71335. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  71336. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  71337. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  71338. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  71339. // Create effects
  71340. _this._createChromaticAberrationPostProcess(ratio);
  71341. _this._createHighlightsPostProcess(ratio);
  71342. _this._createDepthOfFieldPostProcess(ratio / 4);
  71343. // Set up pipeline
  71344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  71345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  71346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  71347. if (_this._highlightsGain === -1) {
  71348. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  71349. }
  71350. // Finish
  71351. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71352. if (cameras) {
  71353. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71354. }
  71355. return _this;
  71356. }
  71357. // public methods (self explanatory)
  71358. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  71359. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  71360. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  71361. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  71362. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  71363. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  71364. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  71365. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  71366. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  71367. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  71368. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  71369. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  71370. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  71371. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  71372. };
  71373. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  71374. this._highlightsPostProcess.updateEffect();
  71375. };
  71376. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  71377. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  71378. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  71379. this._highlightsGain = amount;
  71380. };
  71381. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  71382. if (this._highlightsGain === -1) {
  71383. this._highlightsGain = 1.0;
  71384. }
  71385. this._highlightsThreshold = amount;
  71386. };
  71387. LensRenderingPipeline.prototype.disableHighlights = function () {
  71388. this._highlightsGain = -1;
  71389. };
  71390. /**
  71391. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  71392. */
  71393. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71394. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71395. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71396. this._chromaticAberrationPostProcess = null;
  71397. this._highlightsPostProcess = null;
  71398. this._depthOfFieldPostProcess = null;
  71399. this._grainTexture.dispose();
  71400. if (disableDepthRender)
  71401. this._scene.disableDepthRenderer();
  71402. };
  71403. // colors shifting and distortion
  71404. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  71405. var _this = this;
  71406. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  71407. [], // samplers
  71408. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71409. this._chromaticAberrationPostProcess.onApply = function (effect) {
  71410. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  71411. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71412. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71413. effect.setFloat('radialIntensity', 1);
  71414. effect.setFloat2('direction', 17, 17);
  71415. effect.setFloat2('centerPosition', 0.5, 0.5);
  71416. };
  71417. };
  71418. // highlights enhancing
  71419. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  71420. var _this = this;
  71421. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  71422. [], // samplers
  71423. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  71424. this._highlightsPostProcess.onApply = function (effect) {
  71425. effect.setFloat('gain', _this._highlightsGain);
  71426. effect.setFloat('threshold', _this._highlightsThreshold);
  71427. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  71428. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71429. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71430. };
  71431. };
  71432. // colors shifting and distortion
  71433. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  71434. var _this = this;
  71435. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  71436. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  71437. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  71438. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71439. this._depthOfFieldPostProcess.onApply = function (effect) {
  71440. effect.setTexture("depthSampler", _this._depthTexture);
  71441. effect.setTexture("grainSampler", _this._grainTexture);
  71442. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  71443. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  71444. effect.setFloat('grain_amount', _this._grainAmount);
  71445. effect.setBool('blur_noise', _this._blurNoise);
  71446. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71447. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71448. effect.setFloat('distortion', _this._distortion);
  71449. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  71450. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  71451. effect.setFloat('aperture', _this._dofAperture);
  71452. effect.setFloat('darken', _this._dofDarken);
  71453. effect.setFloat('edge_blur', _this._edgeBlur);
  71454. effect.setBool('highlights', (_this._highlightsGain !== -1));
  71455. if (_this._scene.activeCamera) {
  71456. effect.setFloat('near', _this._scene.activeCamera.minZ);
  71457. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  71458. }
  71459. };
  71460. };
  71461. // creates a black and white random noise texture, 512x512
  71462. LensRenderingPipeline.prototype._createGrainTexture = function () {
  71463. var size = 512;
  71464. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71465. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71466. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71467. var context = this._grainTexture.getContext();
  71468. var rand = function (min, max) {
  71469. return Math.random() * (max - min) + min;
  71470. };
  71471. var value;
  71472. for (var x = 0; x < size; x++) {
  71473. for (var y = 0; y < size; y++) {
  71474. value = Math.floor(rand(0.42, 0.58) * 255);
  71475. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  71476. context.fillRect(x, y, 1, 1);
  71477. }
  71478. }
  71479. this._grainTexture.update(false);
  71480. };
  71481. return LensRenderingPipeline;
  71482. }(BABYLON.PostProcessRenderPipeline));
  71483. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  71484. })(BABYLON || (BABYLON = {}));
  71485. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  71486. "use strict";
  71487. var BABYLON;
  71488. (function (BABYLON) {
  71489. var StandardRenderingPipeline = /** @class */ (function (_super) {
  71490. __extends(StandardRenderingPipeline, _super);
  71491. /**
  71492. * @constructor
  71493. * @param {string} name - The rendering pipeline name
  71494. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71495. * @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)
  71496. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  71497. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71498. */
  71499. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  71500. if (originalPostProcess === void 0) { originalPostProcess = null; }
  71501. var _this = _super.call(this, scene.getEngine(), name) || this;
  71502. _this.downSampleX4PostProcess = null;
  71503. _this.brightPassPostProcess = null;
  71504. _this.blurHPostProcesses = [];
  71505. _this.blurVPostProcesses = [];
  71506. _this.textureAdderPostProcess = null;
  71507. _this.volumetricLightPostProcess = null;
  71508. _this.volumetricLightSmoothXPostProcess = null;
  71509. _this.volumetricLightSmoothYPostProcess = null;
  71510. _this.volumetricLightMergePostProces = null;
  71511. _this.volumetricLightFinalPostProcess = null;
  71512. _this.luminancePostProcess = null;
  71513. _this.luminanceDownSamplePostProcesses = [];
  71514. _this.hdrPostProcess = null;
  71515. _this.textureAdderFinalPostProcess = null;
  71516. _this.lensFlareFinalPostProcess = null;
  71517. _this.hdrFinalPostProcess = null;
  71518. _this.lensFlarePostProcess = null;
  71519. _this.lensFlareComposePostProcess = null;
  71520. _this.motionBlurPostProcess = null;
  71521. _this.depthOfFieldPostProcess = null;
  71522. // Values
  71523. _this.brightThreshold = 1.0;
  71524. _this.blurWidth = 512.0;
  71525. _this.horizontalBlur = false;
  71526. _this.exposure = 1.0;
  71527. _this.lensTexture = null;
  71528. _this.volumetricLightCoefficient = 0.2;
  71529. _this.volumetricLightPower = 4.0;
  71530. _this.volumetricLightBlurScale = 64.0;
  71531. _this.sourceLight = null;
  71532. _this.hdrMinimumLuminance = 1.0;
  71533. _this.hdrDecreaseRate = 0.5;
  71534. _this.hdrIncreaseRate = 0.5;
  71535. _this.lensColorTexture = null;
  71536. _this.lensFlareStrength = 20.0;
  71537. _this.lensFlareGhostDispersal = 1.4;
  71538. _this.lensFlareHaloWidth = 0.7;
  71539. _this.lensFlareDistortionStrength = 16.0;
  71540. _this.lensStarTexture = null;
  71541. _this.lensFlareDirtTexture = null;
  71542. _this.depthOfFieldDistance = 10.0;
  71543. _this.depthOfFieldBlurWidth = 64.0;
  71544. _this.motionStrength = 1.0;
  71545. // IAnimatable
  71546. _this.animations = [];
  71547. _this._currentDepthOfFieldSource = null;
  71548. _this._hdrCurrentLuminance = 1.0;
  71549. // Getters and setters
  71550. _this._bloomEnabled = true;
  71551. _this._depthOfFieldEnabled = false;
  71552. _this._vlsEnabled = false;
  71553. _this._lensFlareEnabled = false;
  71554. _this._hdrEnabled = false;
  71555. _this._motionBlurEnabled = false;
  71556. _this._motionBlurSamples = 64.0;
  71557. _this._volumetricLightStepsCount = 50.0;
  71558. _this._cameras = cameras || [];
  71559. // Initialize
  71560. _this._scene = scene;
  71561. _this._basePostProcess = originalPostProcess;
  71562. _this._ratio = ratio;
  71563. // Misc
  71564. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71565. // Finish
  71566. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71567. _this._buildPipeline();
  71568. return _this;
  71569. }
  71570. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  71571. get: function () {
  71572. return this._bloomEnabled;
  71573. },
  71574. set: function (enabled) {
  71575. if (this._bloomEnabled === enabled) {
  71576. return;
  71577. }
  71578. this._bloomEnabled = enabled;
  71579. this._buildPipeline();
  71580. },
  71581. enumerable: true,
  71582. configurable: true
  71583. });
  71584. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  71585. get: function () {
  71586. return this._depthOfFieldEnabled;
  71587. },
  71588. set: function (enabled) {
  71589. if (this._depthOfFieldEnabled === enabled) {
  71590. return;
  71591. }
  71592. this._depthOfFieldEnabled = enabled;
  71593. this._buildPipeline();
  71594. },
  71595. enumerable: true,
  71596. configurable: true
  71597. });
  71598. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  71599. get: function () {
  71600. return this._lensFlareEnabled;
  71601. },
  71602. set: function (enabled) {
  71603. if (this._lensFlareEnabled === enabled) {
  71604. return;
  71605. }
  71606. this._lensFlareEnabled = enabled;
  71607. this._buildPipeline();
  71608. },
  71609. enumerable: true,
  71610. configurable: true
  71611. });
  71612. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  71613. get: function () {
  71614. return this._hdrEnabled;
  71615. },
  71616. set: function (enabled) {
  71617. if (this._hdrEnabled === enabled) {
  71618. return;
  71619. }
  71620. this._hdrEnabled = enabled;
  71621. this._buildPipeline();
  71622. },
  71623. enumerable: true,
  71624. configurable: true
  71625. });
  71626. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  71627. get: function () {
  71628. return this._vlsEnabled;
  71629. },
  71630. set: function (enabled) {
  71631. if (this._vlsEnabled === enabled) {
  71632. return;
  71633. }
  71634. if (enabled) {
  71635. var geometry = this._scene.enableGeometryBufferRenderer();
  71636. if (!geometry) {
  71637. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  71638. return;
  71639. }
  71640. }
  71641. this._vlsEnabled = enabled;
  71642. this._buildPipeline();
  71643. },
  71644. enumerable: true,
  71645. configurable: true
  71646. });
  71647. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  71648. get: function () {
  71649. return this._motionBlurEnabled;
  71650. },
  71651. set: function (enabled) {
  71652. if (this._motionBlurEnabled === enabled) {
  71653. return;
  71654. }
  71655. this._motionBlurEnabled = enabled;
  71656. this._buildPipeline();
  71657. },
  71658. enumerable: true,
  71659. configurable: true
  71660. });
  71661. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  71662. get: function () {
  71663. return this._volumetricLightStepsCount;
  71664. },
  71665. set: function (count) {
  71666. if (this.volumetricLightPostProcess) {
  71667. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  71668. }
  71669. this._volumetricLightStepsCount = count;
  71670. },
  71671. enumerable: true,
  71672. configurable: true
  71673. });
  71674. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  71675. get: function () {
  71676. return this._motionBlurSamples;
  71677. },
  71678. set: function (samples) {
  71679. if (this.motionBlurPostProcess) {
  71680. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  71681. }
  71682. this._motionBlurSamples = samples;
  71683. },
  71684. enumerable: true,
  71685. configurable: true
  71686. });
  71687. StandardRenderingPipeline.prototype._buildPipeline = function () {
  71688. var _this = this;
  71689. var ratio = this._ratio;
  71690. var scene = this._scene;
  71691. this._disposePostProcesses();
  71692. this._reset();
  71693. // Create pass post-process
  71694. if (!this._basePostProcess) {
  71695. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  71696. this.originalPostProcess.onApply = function (effect) {
  71697. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  71698. };
  71699. }
  71700. else {
  71701. this.originalPostProcess = this._basePostProcess;
  71702. }
  71703. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  71704. this._currentDepthOfFieldSource = this.originalPostProcess;
  71705. if (this._vlsEnabled) {
  71706. // Create volumetric light
  71707. this._createVolumetricLightPostProcess(scene, ratio);
  71708. // Create volumetric light final post-process
  71709. 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);
  71710. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  71711. }
  71712. if (this._bloomEnabled) {
  71713. // Create down sample X4 post-process
  71714. this._createDownSampleX4PostProcess(scene, ratio / 2);
  71715. // Create bright pass post-process
  71716. this._createBrightPassPostProcess(scene, ratio / 2);
  71717. // Create gaussian blur post-processes (down sampling blurs)
  71718. this._createBlurPostProcesses(scene, ratio / 4, 1);
  71719. // Create texture adder post-process
  71720. this._createTextureAdderPostProcess(scene, ratio);
  71721. // Create depth-of-field source post-process
  71722. 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);
  71723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  71724. }
  71725. if (this._lensFlareEnabled) {
  71726. // Create lens flare post-process
  71727. this._createLensFlarePostProcess(scene, ratio);
  71728. // Create depth-of-field source post-process post lens-flare and disable it now
  71729. 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);
  71730. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  71731. }
  71732. if (this._hdrEnabled) {
  71733. // Create luminance
  71734. this._createLuminancePostProcesses(scene, this._floatTextureType);
  71735. // Create HDR
  71736. this._createHdrPostProcess(scene, ratio);
  71737. // Create depth-of-field source post-process post hdr and disable it now
  71738. 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);
  71739. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  71740. }
  71741. if (this._depthOfFieldEnabled) {
  71742. // Create gaussian blur used by depth-of-field
  71743. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  71744. // Create depth-of-field post-process
  71745. this._createDepthOfFieldPostProcess(scene, ratio);
  71746. }
  71747. if (this._motionBlurEnabled) {
  71748. // Create motion blur post-process
  71749. this._createMotionBlurPostProcess(scene, ratio);
  71750. }
  71751. if (this._cameras !== null) {
  71752. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71753. }
  71754. };
  71755. // Down Sample X4 Post-Processs
  71756. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  71757. var _this = this;
  71758. var downSampleX4Offsets = new Array(32);
  71759. 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);
  71760. this.downSampleX4PostProcess.onApply = function (effect) {
  71761. var id = 0;
  71762. var width = _this.downSampleX4PostProcess.width;
  71763. var height = _this.downSampleX4PostProcess.height;
  71764. for (var i = -2; i < 2; i++) {
  71765. for (var j = -2; j < 2; j++) {
  71766. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  71767. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  71768. id += 2;
  71769. }
  71770. }
  71771. effect.setArray2("dsOffsets", downSampleX4Offsets);
  71772. };
  71773. // Add to pipeline
  71774. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  71775. };
  71776. // Brightpass Post-Process
  71777. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  71778. var _this = this;
  71779. var brightOffsets = new Array(8);
  71780. 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);
  71781. this.brightPassPostProcess.onApply = function (effect) {
  71782. var sU = (1.0 / _this.brightPassPostProcess.width);
  71783. var sV = (1.0 / _this.brightPassPostProcess.height);
  71784. brightOffsets[0] = -0.5 * sU;
  71785. brightOffsets[1] = 0.5 * sV;
  71786. brightOffsets[2] = 0.5 * sU;
  71787. brightOffsets[3] = 0.5 * sV;
  71788. brightOffsets[4] = -0.5 * sU;
  71789. brightOffsets[5] = -0.5 * sV;
  71790. brightOffsets[6] = 0.5 * sU;
  71791. brightOffsets[7] = -0.5 * sV;
  71792. effect.setArray2("dsOffsets", brightOffsets);
  71793. effect.setFloat("brightThreshold", _this.brightThreshold);
  71794. };
  71795. // Add to pipeline
  71796. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  71797. };
  71798. // Create blur H&V post-processes
  71799. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  71800. var _this = this;
  71801. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  71802. var engine = scene.getEngine();
  71803. 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);
  71804. 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);
  71805. blurX.onActivateObservable.add(function () {
  71806. var dw = blurX.width / engine.getRenderWidth();
  71807. blurX.kernel = _this[blurWidthKey] * dw;
  71808. });
  71809. blurY.onActivateObservable.add(function () {
  71810. var dw = blurY.height / engine.getRenderHeight();
  71811. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  71812. });
  71813. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  71814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  71815. this.blurHPostProcesses.push(blurX);
  71816. this.blurVPostProcesses.push(blurY);
  71817. };
  71818. // Create texture adder post-process
  71819. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  71820. var _this = this;
  71821. 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);
  71822. this.textureAdderPostProcess.onApply = function (effect) {
  71823. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  71824. effect.setTexture("lensSampler", _this.lensTexture);
  71825. effect.setFloat("exposure", _this.exposure);
  71826. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  71827. };
  71828. // Add to pipeline
  71829. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  71830. };
  71831. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  71832. var _this = this;
  71833. var geometryRenderer = scene.enableGeometryBufferRenderer();
  71834. geometryRenderer.enablePosition = true;
  71835. var geometry = geometryRenderer.getGBuffer();
  71836. // Base post-process
  71837. 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));
  71838. var depthValues = BABYLON.Vector2.Zero();
  71839. this.volumetricLightPostProcess.onApply = function (effect) {
  71840. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  71841. var generator = _this.sourceLight.getShadowGenerator();
  71842. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  71843. effect.setTexture("positionSampler", geometry.textures[2]);
  71844. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  71845. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  71846. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  71847. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  71848. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  71849. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  71850. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  71851. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  71852. effect.setVector2("depthValues", depthValues);
  71853. }
  71854. };
  71855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  71856. // Smooth
  71857. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  71858. // Merge
  71859. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  71860. this.volumetricLightMergePostProces.onApply = function (effect) {
  71861. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  71862. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  71863. };
  71864. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  71865. };
  71866. // Create luminance
  71867. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  71868. var _this = this;
  71869. // Create luminance
  71870. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  71871. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  71872. var offsets = [];
  71873. this.luminancePostProcess.onApply = function (effect) {
  71874. var sU = (1.0 / _this.luminancePostProcess.width);
  71875. var sV = (1.0 / _this.luminancePostProcess.height);
  71876. offsets[0] = -0.5 * sU;
  71877. offsets[1] = 0.5 * sV;
  71878. offsets[2] = 0.5 * sU;
  71879. offsets[3] = 0.5 * sV;
  71880. offsets[4] = -0.5 * sU;
  71881. offsets[5] = -0.5 * sV;
  71882. offsets[6] = 0.5 * sU;
  71883. offsets[7] = -0.5 * sV;
  71884. effect.setArray2("lumOffsets", offsets);
  71885. };
  71886. // Add to pipeline
  71887. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  71888. // Create down sample luminance
  71889. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  71890. var size = Math.pow(3, i);
  71891. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  71892. if (i === 0) {
  71893. defines += "#define FINAL_DOWN_SAMPLER";
  71894. }
  71895. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  71896. this.luminanceDownSamplePostProcesses.push(postProcess);
  71897. }
  71898. // Create callbacks and add effects
  71899. var lastLuminance = this.luminancePostProcess;
  71900. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  71901. var downSampleOffsets = new Array(18);
  71902. pp.onApply = function (effect) {
  71903. if (!lastLuminance) {
  71904. return;
  71905. }
  71906. var id = 0;
  71907. for (var x = -1; x < 2; x++) {
  71908. for (var y = -1; y < 2; y++) {
  71909. downSampleOffsets[id] = x / lastLuminance.width;
  71910. downSampleOffsets[id + 1] = y / lastLuminance.height;
  71911. id += 2;
  71912. }
  71913. }
  71914. effect.setArray2("dsOffsets", downSampleOffsets);
  71915. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  71916. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  71917. lastLuminance = _this.luminancePostProcess;
  71918. }
  71919. else {
  71920. lastLuminance = pp;
  71921. }
  71922. };
  71923. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  71924. pp.onAfterRender = function (effect) {
  71925. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  71926. 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);
  71927. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  71928. };
  71929. }
  71930. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  71931. });
  71932. };
  71933. // Create HDR post-process
  71934. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  71935. var _this = this;
  71936. 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);
  71937. var outputLiminance = 1;
  71938. var time = 0;
  71939. var lastTime = 0;
  71940. this.hdrPostProcess.onApply = function (effect) {
  71941. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  71942. time += scene.getEngine().getDeltaTime();
  71943. if (outputLiminance < 0) {
  71944. outputLiminance = _this._hdrCurrentLuminance;
  71945. }
  71946. else {
  71947. var dt = (lastTime - time) / 1000.0;
  71948. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  71949. outputLiminance += _this.hdrDecreaseRate * dt;
  71950. }
  71951. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  71952. outputLiminance -= _this.hdrIncreaseRate * dt;
  71953. }
  71954. else {
  71955. outputLiminance = _this._hdrCurrentLuminance;
  71956. }
  71957. }
  71958. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  71959. effect.setFloat("averageLuminance", outputLiminance);
  71960. lastTime = time;
  71961. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  71962. };
  71963. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  71964. };
  71965. // Create lens flare post-process
  71966. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  71967. var _this = this;
  71968. 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);
  71969. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  71970. this._createBlurPostProcesses(scene, ratio / 4, 2);
  71971. 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);
  71972. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  71973. var resolution = new BABYLON.Vector2(0, 0);
  71974. // Lens flare
  71975. this.lensFlarePostProcess.onApply = function (effect) {
  71976. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  71977. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  71978. effect.setFloat("strength", _this.lensFlareStrength);
  71979. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  71980. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  71981. // Shift
  71982. resolution.x = _this.lensFlarePostProcess.width;
  71983. resolution.y = _this.lensFlarePostProcess.height;
  71984. effect.setVector2("resolution", resolution);
  71985. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  71986. };
  71987. // Compose
  71988. 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);
  71989. 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);
  71990. this.lensFlareComposePostProcess.onApply = function (effect) {
  71991. if (!_this._scene.activeCamera) {
  71992. return;
  71993. }
  71994. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  71995. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  71996. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  71997. // Lens start rotation matrix
  71998. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  71999. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  72000. 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));
  72001. camRot *= 4.0;
  72002. 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);
  72003. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  72004. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  72005. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  72006. };
  72007. };
  72008. // Create depth-of-field post-process
  72009. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  72010. var _this = this;
  72011. 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);
  72012. this.depthOfFieldPostProcess.onApply = function (effect) {
  72013. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72014. effect.setTexture("depthSampler", _this._getDepthTexture());
  72015. effect.setFloat("distance", _this.depthOfFieldDistance);
  72016. };
  72017. // Add to pipeline
  72018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  72019. };
  72020. // Create motion blur post-process
  72021. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  72022. var _this = this;
  72023. 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);
  72024. var motionScale = 0;
  72025. var prevViewProjection = BABYLON.Matrix.Identity();
  72026. var invViewProjection = BABYLON.Matrix.Identity();
  72027. var viewProjection = BABYLON.Matrix.Identity();
  72028. var screenSize = BABYLON.Vector2.Zero();
  72029. this.motionBlurPostProcess.onApply = function (effect) {
  72030. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  72031. viewProjection.invertToRef(invViewProjection);
  72032. effect.setMatrix("inverseViewProjection", invViewProjection);
  72033. effect.setMatrix("prevViewProjection", prevViewProjection);
  72034. prevViewProjection = viewProjection;
  72035. screenSize.x = _this.motionBlurPostProcess.width;
  72036. screenSize.y = _this.motionBlurPostProcess.height;
  72037. effect.setVector2("screenSize", screenSize);
  72038. motionScale = scene.getEngine().getFps() / 60.0;
  72039. effect.setFloat("motionScale", motionScale);
  72040. effect.setFloat("motionStrength", _this.motionStrength);
  72041. effect.setTexture("depthSampler", _this._getDepthTexture());
  72042. };
  72043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  72044. };
  72045. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  72046. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  72047. var renderer = this._scene.enableGeometryBufferRenderer();
  72048. return renderer.getGBuffer().textures[0];
  72049. }
  72050. return this._scene.enableDepthRenderer().getDepthMap();
  72051. };
  72052. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  72053. for (var i = 0; i < this._cameras.length; i++) {
  72054. var camera = this._cameras[i];
  72055. if (this.originalPostProcess) {
  72056. this.originalPostProcess.dispose(camera);
  72057. }
  72058. if (this.downSampleX4PostProcess) {
  72059. this.downSampleX4PostProcess.dispose(camera);
  72060. }
  72061. if (this.brightPassPostProcess) {
  72062. this.brightPassPostProcess.dispose(camera);
  72063. }
  72064. if (this.textureAdderPostProcess) {
  72065. this.textureAdderPostProcess.dispose(camera);
  72066. }
  72067. if (this.textureAdderFinalPostProcess) {
  72068. this.textureAdderFinalPostProcess.dispose(camera);
  72069. }
  72070. if (this.volumetricLightPostProcess) {
  72071. this.volumetricLightPostProcess.dispose(camera);
  72072. }
  72073. if (this.volumetricLightSmoothXPostProcess) {
  72074. this.volumetricLightSmoothXPostProcess.dispose(camera);
  72075. }
  72076. if (this.volumetricLightSmoothYPostProcess) {
  72077. this.volumetricLightSmoothYPostProcess.dispose(camera);
  72078. }
  72079. if (this.volumetricLightMergePostProces) {
  72080. this.volumetricLightMergePostProces.dispose(camera);
  72081. }
  72082. if (this.volumetricLightFinalPostProcess) {
  72083. this.volumetricLightFinalPostProcess.dispose(camera);
  72084. }
  72085. if (this.lensFlarePostProcess) {
  72086. this.lensFlarePostProcess.dispose(camera);
  72087. }
  72088. if (this.lensFlareComposePostProcess) {
  72089. this.lensFlareComposePostProcess.dispose(camera);
  72090. }
  72091. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  72092. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  72093. }
  72094. if (this.luminancePostProcess) {
  72095. this.luminancePostProcess.dispose(camera);
  72096. }
  72097. if (this.hdrPostProcess) {
  72098. this.hdrPostProcess.dispose(camera);
  72099. }
  72100. if (this.hdrFinalPostProcess) {
  72101. this.hdrFinalPostProcess.dispose(camera);
  72102. }
  72103. if (this.depthOfFieldPostProcess) {
  72104. this.depthOfFieldPostProcess.dispose(camera);
  72105. }
  72106. if (this.motionBlurPostProcess) {
  72107. this.motionBlurPostProcess.dispose(camera);
  72108. }
  72109. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  72110. this.blurHPostProcesses[j].dispose(camera);
  72111. }
  72112. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  72113. this.blurVPostProcesses[j].dispose(camera);
  72114. }
  72115. }
  72116. this.originalPostProcess = null;
  72117. this.downSampleX4PostProcess = null;
  72118. this.brightPassPostProcess = null;
  72119. this.textureAdderPostProcess = null;
  72120. this.textureAdderFinalPostProcess = null;
  72121. this.volumetricLightPostProcess = null;
  72122. this.volumetricLightSmoothXPostProcess = null;
  72123. this.volumetricLightSmoothYPostProcess = null;
  72124. this.volumetricLightMergePostProces = null;
  72125. this.volumetricLightFinalPostProcess = null;
  72126. this.lensFlarePostProcess = null;
  72127. this.lensFlareComposePostProcess = null;
  72128. this.luminancePostProcess = null;
  72129. this.hdrPostProcess = null;
  72130. this.hdrFinalPostProcess = null;
  72131. this.depthOfFieldPostProcess = null;
  72132. this.motionBlurPostProcess = null;
  72133. this.luminanceDownSamplePostProcesses = [];
  72134. this.blurHPostProcesses = [];
  72135. this.blurVPostProcesses = [];
  72136. };
  72137. // Dispose
  72138. StandardRenderingPipeline.prototype.dispose = function () {
  72139. this._disposePostProcesses();
  72140. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72141. _super.prototype.dispose.call(this);
  72142. };
  72143. // Serialize rendering pipeline
  72144. StandardRenderingPipeline.prototype.serialize = function () {
  72145. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72146. serializationObject.customType = "StandardRenderingPipeline";
  72147. return serializationObject;
  72148. };
  72149. /**
  72150. * Static members
  72151. */
  72152. // Parse serialized pipeline
  72153. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  72154. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  72155. };
  72156. // Luminance steps
  72157. StandardRenderingPipeline.LuminanceSteps = 6;
  72158. __decorate([
  72159. BABYLON.serialize()
  72160. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  72161. __decorate([
  72162. BABYLON.serialize()
  72163. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  72164. __decorate([
  72165. BABYLON.serialize()
  72166. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  72167. __decorate([
  72168. BABYLON.serialize()
  72169. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  72170. __decorate([
  72171. BABYLON.serializeAsTexture("lensTexture")
  72172. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  72173. __decorate([
  72174. BABYLON.serialize()
  72175. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  72176. __decorate([
  72177. BABYLON.serialize()
  72178. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  72179. __decorate([
  72180. BABYLON.serialize()
  72181. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  72182. __decorate([
  72183. BABYLON.serialize()
  72184. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  72185. __decorate([
  72186. BABYLON.serialize()
  72187. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  72188. __decorate([
  72189. BABYLON.serialize()
  72190. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  72191. __decorate([
  72192. BABYLON.serializeAsTexture("lensColorTexture")
  72193. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  72194. __decorate([
  72195. BABYLON.serialize()
  72196. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  72197. __decorate([
  72198. BABYLON.serialize()
  72199. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  72200. __decorate([
  72201. BABYLON.serialize()
  72202. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  72203. __decorate([
  72204. BABYLON.serialize()
  72205. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  72206. __decorate([
  72207. BABYLON.serializeAsTexture("lensStarTexture")
  72208. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  72209. __decorate([
  72210. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  72211. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  72212. __decorate([
  72213. BABYLON.serialize()
  72214. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  72215. __decorate([
  72216. BABYLON.serialize()
  72217. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  72218. __decorate([
  72219. BABYLON.serialize()
  72220. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  72221. __decorate([
  72222. BABYLON.serialize()
  72223. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  72224. __decorate([
  72225. BABYLON.serialize()
  72226. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  72227. __decorate([
  72228. BABYLON.serialize()
  72229. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  72230. __decorate([
  72231. BABYLON.serialize()
  72232. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  72233. __decorate([
  72234. BABYLON.serialize()
  72235. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  72236. __decorate([
  72237. BABYLON.serialize()
  72238. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  72239. __decorate([
  72240. BABYLON.serialize()
  72241. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  72242. __decorate([
  72243. BABYLON.serialize()
  72244. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  72245. __decorate([
  72246. BABYLON.serialize()
  72247. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  72248. return StandardRenderingPipeline;
  72249. }(BABYLON.PostProcessRenderPipeline));
  72250. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  72251. })(BABYLON || (BABYLON = {}));
  72252. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  72253. "use strict";
  72254. var BABYLON;
  72255. (function (BABYLON) {
  72256. var FxaaPostProcess = /** @class */ (function (_super) {
  72257. __extends(FxaaPostProcess, _super);
  72258. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72259. if (camera === void 0) { camera = null; }
  72260. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72261. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  72262. _this.onApplyObservable.add(function (effect) {
  72263. var texelSize = _this.texelSize;
  72264. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  72265. });
  72266. return _this;
  72267. }
  72268. return FxaaPostProcess;
  72269. }(BABYLON.PostProcess));
  72270. BABYLON.FxaaPostProcess = FxaaPostProcess;
  72271. })(BABYLON || (BABYLON = {}));
  72272. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  72273. "use strict";
  72274. var BABYLON;
  72275. (function (BABYLON) {
  72276. /**
  72277. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  72278. */
  72279. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  72280. __extends(ChromaticAberrationPostProcess, _super);
  72281. /**
  72282. * Creates a new instance ChromaticAberrationPostProcess
  72283. * @param name The name of the effect.
  72284. * @param screenWidth The width of the screen to apply the effect on.
  72285. * @param screenHeight The height of the screen to apply the effect on.
  72286. * @param options The required width/height ratio to downsize to before computing the render pass.
  72287. * @param camera The camera to apply the render pass to.
  72288. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72289. * @param engine The engine which the post process will be applied. (default: current engine)
  72290. * @param reusable If the post process can be reused on the same frame. (default: false)
  72291. * @param textureType Type of textures used when performing the post process. (default: 0)
  72292. * @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)
  72293. */
  72294. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72295. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72296. if (blockCompilation === void 0) { blockCompilation = false; }
  72297. 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;
  72298. /**
  72299. * The amount of seperation of rgb channels (default: 30)
  72300. */
  72301. _this.aberrationAmount = 30;
  72302. /**
  72303. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  72304. */
  72305. _this.radialIntensity = 0;
  72306. /**
  72307. * 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))
  72308. */
  72309. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  72310. /**
  72311. * 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))
  72312. */
  72313. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  72314. _this.onApplyObservable.add(function (effect) {
  72315. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  72316. effect.setFloat('screen_width', screenWidth);
  72317. effect.setFloat('screen_height', screenHeight);
  72318. effect.setFloat('radialIntensity', _this.radialIntensity);
  72319. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  72320. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  72321. });
  72322. return _this;
  72323. }
  72324. return ChromaticAberrationPostProcess;
  72325. }(BABYLON.PostProcess));
  72326. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  72327. })(BABYLON || (BABYLON = {}));
  72328. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  72329. "use strict";
  72330. var BABYLON;
  72331. (function (BABYLON) {
  72332. /**
  72333. * The GrainPostProcess adds noise to the image at mid luminance levels
  72334. */
  72335. var GrainPostProcess = /** @class */ (function (_super) {
  72336. __extends(GrainPostProcess, _super);
  72337. /**
  72338. * Creates a new instance of @see GrainPostProcess
  72339. * @param name The name of the effect.
  72340. * @param options The required width/height ratio to downsize to before computing the render pass.
  72341. * @param camera The camera to apply the render pass to.
  72342. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72343. * @param engine The engine which the post process will be applied. (default: current engine)
  72344. * @param reusable If the post process can be reused on the same frame. (default: false)
  72345. * @param textureType Type of textures used when performing the post process. (default: 0)
  72346. * @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)
  72347. */
  72348. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72349. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72350. if (blockCompilation === void 0) { blockCompilation = false; }
  72351. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72352. /**
  72353. * The intensity of the grain added (default: 30)
  72354. */
  72355. _this.intensity = 30;
  72356. /**
  72357. * If the grain should be randomized on every frame
  72358. */
  72359. _this.animated = false;
  72360. _this.onApplyObservable.add(function (effect) {
  72361. effect.setFloat('intensity', _this.intensity);
  72362. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  72363. });
  72364. return _this;
  72365. }
  72366. return GrainPostProcess;
  72367. }(BABYLON.PostProcess));
  72368. BABYLON.GrainPostProcess = GrainPostProcess;
  72369. })(BABYLON || (BABYLON = {}));
  72370. //# sourceMappingURL=babylon.grainPostProcess.js.map
  72371. "use strict";
  72372. var BABYLON;
  72373. (function (BABYLON) {
  72374. /**
  72375. * The SharpenPostProcess applies a sharpen kernel to every pixel
  72376. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  72377. */
  72378. var SharpenPostProcess = /** @class */ (function (_super) {
  72379. __extends(SharpenPostProcess, _super);
  72380. /**
  72381. * Creates a new instance ConvolutionPostProcess
  72382. * @param name The name of the effect.
  72383. * @param options The required width/height ratio to downsize to before computing the render pass.
  72384. * @param camera The camera to apply the render pass to.
  72385. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72386. * @param engine The engine which the post process will be applied. (default: current engine)
  72387. * @param reusable If the post process can be reused on the same frame. (default: false)
  72388. * @param textureType Type of textures used when performing the post process. (default: 0)
  72389. * @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)
  72390. */
  72391. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72392. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72393. if (blockCompilation === void 0) { blockCompilation = false; }
  72394. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72395. /**
  72396. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  72397. */
  72398. _this.colorAmount = 1.0;
  72399. /**
  72400. * How much sharpness should be applied (default: 0.3)
  72401. */
  72402. _this.edgeAmount = 0.3;
  72403. _this.onApply = function (effect) {
  72404. effect.setFloat2("screenSize", _this.width, _this.height);
  72405. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  72406. };
  72407. return _this;
  72408. }
  72409. return SharpenPostProcess;
  72410. }(BABYLON.PostProcess));
  72411. BABYLON.SharpenPostProcess = SharpenPostProcess;
  72412. })(BABYLON || (BABYLON = {}));
  72413. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  72414. "use strict";
  72415. var BABYLON;
  72416. (function (BABYLON) {
  72417. /**
  72418. * The Blur Post Process which blurs an image based on a kernel and direction.
  72419. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  72420. */
  72421. var BlurPostProcess = /** @class */ (function (_super) {
  72422. __extends(BlurPostProcess, _super);
  72423. /**
  72424. * Creates a new instance BlurPostProcess
  72425. * @param name The name of the effect.
  72426. * @param direction The direction in which to blur the image.
  72427. * @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.
  72428. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  72429. * @param camera The camera to apply the render pass to.
  72430. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72431. * @param engine The engine which the post process will be applied. (default: current engine)
  72432. * @param reusable If the post process can be reused on the same frame. (default: false)
  72433. * @param textureType Type of textures used when performing the post process. (default: 0)
  72434. * @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)
  72435. */
  72436. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  72437. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72438. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72439. if (defines === void 0) { defines = ""; }
  72440. if (blockCompilation === void 0) { blockCompilation = false; }
  72441. 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;
  72442. _this.direction = direction;
  72443. _this.blockCompilation = blockCompilation;
  72444. _this._packedFloat = false;
  72445. _this._staticDefines = "";
  72446. _this._staticDefines = defines;
  72447. _this.onApplyObservable.add(function (effect) {
  72448. if (_this._outputTexture) {
  72449. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  72450. }
  72451. else {
  72452. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  72453. }
  72454. });
  72455. _this.kernel = kernel;
  72456. return _this;
  72457. }
  72458. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  72459. /**
  72460. * Gets the length in pixels of the blur sample region
  72461. */
  72462. get: function () {
  72463. return this._idealKernel;
  72464. },
  72465. /**
  72466. * Sets the length in pixels of the blur sample region
  72467. */
  72468. set: function (v) {
  72469. if (this._idealKernel === v) {
  72470. return;
  72471. }
  72472. v = Math.max(v, 1);
  72473. this._idealKernel = v;
  72474. this._kernel = this._nearestBestKernel(v);
  72475. if (!this.blockCompilation) {
  72476. this._updateParameters();
  72477. }
  72478. },
  72479. enumerable: true,
  72480. configurable: true
  72481. });
  72482. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  72483. /**
  72484. * Gets wether or not the blur is unpacking/repacking floats
  72485. */
  72486. get: function () {
  72487. return this._packedFloat;
  72488. },
  72489. /**
  72490. * Sets wether or not the blur needs to unpack/repack floats
  72491. */
  72492. set: function (v) {
  72493. if (this._packedFloat === v) {
  72494. return;
  72495. }
  72496. this._packedFloat = v;
  72497. if (!this.blockCompilation) {
  72498. this._updateParameters();
  72499. }
  72500. },
  72501. enumerable: true,
  72502. configurable: true
  72503. });
  72504. /**
  72505. * Updates the effect with the current post process compile time values and recompiles the shader.
  72506. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72507. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72508. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72509. * @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
  72510. * @param onCompiled Called when the shader has been compiled.
  72511. * @param onError Called if there is an error when compiling a shader.
  72512. */
  72513. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72514. if (defines === void 0) { defines = null; }
  72515. if (uniforms === void 0) { uniforms = null; }
  72516. if (samplers === void 0) { samplers = null; }
  72517. this._updateParameters(onCompiled, onError);
  72518. };
  72519. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  72520. // Generate sampling offsets and weights
  72521. var N = this._kernel;
  72522. var centerIndex = (N - 1) / 2;
  72523. // Generate Gaussian sampling weights over kernel
  72524. var offsets = [];
  72525. var weights = [];
  72526. var totalWeight = 0;
  72527. for (var i = 0; i < N; i++) {
  72528. var u = i / (N - 1);
  72529. var w = this._gaussianWeight(u * 2.0 - 1);
  72530. offsets[i] = (i - centerIndex);
  72531. weights[i] = w;
  72532. totalWeight += w;
  72533. }
  72534. // Normalize weights
  72535. for (var i = 0; i < weights.length; i++) {
  72536. weights[i] /= totalWeight;
  72537. }
  72538. // Optimize: combine samples to take advantage of hardware linear sampling
  72539. // Walk from left to center, combining pairs (symmetrically)
  72540. var linearSamplingWeights = [];
  72541. var linearSamplingOffsets = [];
  72542. var linearSamplingMap = [];
  72543. for (var i = 0; i <= centerIndex; i += 2) {
  72544. var j = Math.min(i + 1, Math.floor(centerIndex));
  72545. var singleCenterSample = i === j;
  72546. if (singleCenterSample) {
  72547. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  72548. }
  72549. else {
  72550. var sharedCell = j === centerIndex;
  72551. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  72552. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  72553. if (offsetLinear === 0) {
  72554. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  72555. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  72556. }
  72557. else {
  72558. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  72559. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  72560. }
  72561. }
  72562. }
  72563. for (var i = 0; i < linearSamplingMap.length; i++) {
  72564. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  72565. linearSamplingWeights[i] = linearSamplingMap[i].w;
  72566. }
  72567. // Replace with optimized
  72568. offsets = linearSamplingOffsets;
  72569. weights = linearSamplingWeights;
  72570. // Generate shaders
  72571. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  72572. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  72573. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  72574. var defines = "";
  72575. defines += this._staticDefines;
  72576. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  72577. if (this._staticDefines.indexOf("DOF") != -1) {
  72578. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  72579. varyingCount--;
  72580. }
  72581. for (var i = 0; i < varyingCount; i++) {
  72582. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  72583. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  72584. }
  72585. var depCount = 0;
  72586. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  72587. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  72588. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  72589. depCount++;
  72590. }
  72591. if (this.packedFloat) {
  72592. defines += "#define PACKEDFLOAT 1";
  72593. }
  72594. this.blockCompilation = false;
  72595. _super.prototype.updateEffect.call(this, defines, null, null, {
  72596. varyingCount: varyingCount,
  72597. depCount: depCount
  72598. }, onCompiled, onError);
  72599. };
  72600. /**
  72601. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  72602. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  72603. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  72604. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  72605. * The gaps between physical kernels are compensated for in the weighting of the samples
  72606. * @param idealKernel Ideal blur kernel.
  72607. * @return Nearest best kernel.
  72608. */
  72609. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  72610. var v = Math.round(idealKernel);
  72611. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  72612. var k = _a[_i];
  72613. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  72614. return Math.max(k, 3);
  72615. }
  72616. }
  72617. return Math.max(v, 3);
  72618. };
  72619. /**
  72620. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  72621. * @param x The point on the Gaussian distribution to sample.
  72622. * @return the value of the Gaussian function at x.
  72623. */
  72624. BlurPostProcess.prototype._gaussianWeight = function (x) {
  72625. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  72626. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  72627. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  72628. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  72629. // truncated at around 1.3% of peak strength.
  72630. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  72631. var sigma = (1 / 3);
  72632. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  72633. var exponent = -((x * x) / (2.0 * sigma * sigma));
  72634. var weight = (1.0 / denominator) * Math.exp(exponent);
  72635. return weight;
  72636. };
  72637. /**
  72638. * Generates a string that can be used as a floating point number in GLSL.
  72639. * @param x Value to print.
  72640. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  72641. * @return GLSL float string.
  72642. */
  72643. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  72644. if (decimalFigures === void 0) { decimalFigures = 8; }
  72645. return x.toFixed(decimalFigures).replace(/0+$/, '');
  72646. };
  72647. return BlurPostProcess;
  72648. }(BABYLON.PostProcess));
  72649. BABYLON.BlurPostProcess = BlurPostProcess;
  72650. })(BABYLON || (BABYLON = {}));
  72651. //# sourceMappingURL=babylon.blurPostProcess.js.map
  72652. "use strict";
  72653. var BABYLON;
  72654. (function (BABYLON) {
  72655. /**
  72656. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  72657. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  72658. * based on samples that have a large difference in distance than the center pixel.
  72659. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  72660. */
  72661. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  72662. __extends(DepthOfFieldBlurPostProcess, _super);
  72663. /**
  72664. * Creates a new instance CircleOfConfusionPostProcess
  72665. * @param name The name of the effect.
  72666. * @param scene The scene the effect belongs to.
  72667. * @param direction The direction the blur should be applied.
  72668. * @param kernel The size of the kernel used to blur.
  72669. * @param options The required width/height ratio to downsize to before computing the render pass.
  72670. * @param camera The camera to apply the render pass to.
  72671. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  72672. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  72673. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72674. * @param engine The engine which the post process will be applied. (default: current engine)
  72675. * @param reusable If the post process can be reused on the same frame. (default: false)
  72676. * @param textureType Type of textures used when performing the post process. (default: 0)
  72677. * @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)
  72678. */
  72679. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  72680. if (imageToBlur === void 0) { imageToBlur = null; }
  72681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72682. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72683. if (blockCompilation === void 0) { blockCompilation = false; }
  72684. 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;
  72685. _this.direction = direction;
  72686. _this.onApplyObservable.add(function (effect) {
  72687. if (imageToBlur != null) {
  72688. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  72689. }
  72690. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  72691. if (scene.activeCamera) {
  72692. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  72693. }
  72694. });
  72695. return _this;
  72696. }
  72697. return DepthOfFieldBlurPostProcess;
  72698. }(BABYLON.BlurPostProcess));
  72699. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  72700. })(BABYLON || (BABYLON = {}));
  72701. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  72702. "use strict";
  72703. var BABYLON;
  72704. (function (BABYLON) {
  72705. /**
  72706. * Options to be set when merging outputs from the default pipeline.
  72707. */
  72708. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  72709. function DepthOfFieldMergePostProcessOptions() {
  72710. }
  72711. return DepthOfFieldMergePostProcessOptions;
  72712. }());
  72713. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  72714. /**
  72715. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  72716. */
  72717. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  72718. __extends(DepthOfFieldMergePostProcess, _super);
  72719. /**
  72720. * Creates a new instance of DepthOfFieldMergePostProcess
  72721. * @param name The name of the effect.
  72722. * @param originalFromInput Post process which's input will be used for the merge.
  72723. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  72724. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  72725. * @param options The required width/height ratio to downsize to before computing the render pass.
  72726. * @param camera The camera to apply the render pass to.
  72727. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72728. * @param engine The engine which the post process will be applied. (default: current engine)
  72729. * @param reusable If the post process can be reused on the same frame. (default: false)
  72730. * @param textureType Type of textures used when performing the post process. (default: 0)
  72731. * @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)
  72732. */
  72733. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72734. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72735. if (blockCompilation === void 0) { blockCompilation = false; }
  72736. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  72737. _this.blurSteps = blurSteps;
  72738. _this.onApplyObservable.add(function (effect) {
  72739. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  72740. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  72741. blurSteps.forEach(function (step, index) {
  72742. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  72743. });
  72744. });
  72745. if (!blockCompilation) {
  72746. _this.updateEffect();
  72747. }
  72748. return _this;
  72749. }
  72750. /**
  72751. * Updates the effect with the current post process compile time values and recompiles the shader.
  72752. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72753. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72754. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72755. * @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
  72756. * @param onCompiled Called when the shader has been compiled.
  72757. * @param onError Called if there is an error when compiling a shader.
  72758. */
  72759. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72760. if (defines === void 0) { defines = null; }
  72761. if (uniforms === void 0) { uniforms = null; }
  72762. if (samplers === void 0) { samplers = null; }
  72763. if (!defines) {
  72764. defines = "";
  72765. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  72766. }
  72767. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  72768. };
  72769. return DepthOfFieldMergePostProcess;
  72770. }(BABYLON.PostProcess));
  72771. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  72772. })(BABYLON || (BABYLON = {}));
  72773. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  72774. "use strict";
  72775. var BABYLON;
  72776. (function (BABYLON) {
  72777. /**
  72778. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  72779. */
  72780. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  72781. __extends(CircleOfConfusionPostProcess, _super);
  72782. /**
  72783. * Creates a new instance CircleOfConfusionPostProcess
  72784. * @param name The name of the effect.
  72785. * @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.
  72786. * @param options The required width/height ratio to downsize to before computing the render pass.
  72787. * @param camera The camera to apply the render pass to.
  72788. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72789. * @param engine The engine which the post process will be applied. (default: current engine)
  72790. * @param reusable If the post process can be reused on the same frame. (default: false)
  72791. * @param textureType Type of textures used when performing the post process. (default: 0)
  72792. * @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)
  72793. */
  72794. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72795. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72796. if (blockCompilation === void 0) { blockCompilation = false; }
  72797. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72798. /**
  72799. * 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.
  72800. */
  72801. _this.lensSize = 50;
  72802. /**
  72803. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  72804. */
  72805. _this.fStop = 1.4;
  72806. /**
  72807. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  72808. */
  72809. _this.focusDistance = 2000;
  72810. /**
  72811. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  72812. */
  72813. _this.focalLength = 50;
  72814. _this._depthTexture = null;
  72815. _this._depthTexture = depthTexture;
  72816. _this.onApplyObservable.add(function (effect) {
  72817. if (!_this._depthTexture) {
  72818. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  72819. return;
  72820. }
  72821. effect.setTexture("depthSampler", _this._depthTexture);
  72822. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  72823. var aperture = _this.lensSize / _this.fStop;
  72824. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  72825. effect.setFloat('focusDistance', _this.focusDistance);
  72826. effect.setFloat('cocPrecalculation', cocPrecalculation);
  72827. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  72828. });
  72829. return _this;
  72830. }
  72831. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  72832. /**
  72833. * 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.
  72834. */
  72835. set: function (value) {
  72836. this._depthTexture = value;
  72837. },
  72838. enumerable: true,
  72839. configurable: true
  72840. });
  72841. return CircleOfConfusionPostProcess;
  72842. }(BABYLON.PostProcess));
  72843. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  72844. })(BABYLON || (BABYLON = {}));
  72845. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  72846. "use strict";
  72847. var BABYLON;
  72848. (function (BABYLON) {
  72849. /**
  72850. * Specifies the level of max blur that should be applied when using the depth of field effect
  72851. */
  72852. var DepthOfFieldEffectBlurLevel;
  72853. (function (DepthOfFieldEffectBlurLevel) {
  72854. /**
  72855. * Subtle blur
  72856. */
  72857. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  72858. /**
  72859. * Medium blur
  72860. */
  72861. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  72862. /**
  72863. * Large blur
  72864. */
  72865. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  72866. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  72867. ;
  72868. /**
  72869. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  72870. */
  72871. var DepthOfFieldEffect = /** @class */ (function (_super) {
  72872. __extends(DepthOfFieldEffect, _super);
  72873. /**
  72874. * Creates a new instance DepthOfFieldEffect
  72875. * @param scene The scene the effect belongs to.
  72876. * @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.
  72877. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  72878. * @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)
  72879. */
  72880. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  72881. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  72882. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  72883. if (blockCompilation === void 0) { blockCompilation = false; }
  72884. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  72885. return _this._effects;
  72886. }, true) || this;
  72887. /**
  72888. * Internal post processes in depth of field effect
  72889. */
  72890. _this._effects = [];
  72891. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  72892. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  72893. // 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)
  72894. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  72895. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  72896. _this._depthOfFieldBlurY = [];
  72897. _this._depthOfFieldBlurX = [];
  72898. var blurCount = 1;
  72899. var kernelSize = 15;
  72900. switch (blurLevel) {
  72901. case DepthOfFieldEffectBlurLevel.High: {
  72902. blurCount = 3;
  72903. kernelSize = 51;
  72904. break;
  72905. }
  72906. case DepthOfFieldEffectBlurLevel.Medium: {
  72907. blurCount = 2;
  72908. kernelSize = 31;
  72909. break;
  72910. }
  72911. default: {
  72912. kernelSize = 15;
  72913. blurCount = 1;
  72914. break;
  72915. }
  72916. }
  72917. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  72918. var ratio = 1.0;
  72919. for (var i = 0; i < blurCount; i++) {
  72920. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  72921. blurY.autoClear = false;
  72922. ratio = 0.75 / Math.pow(2, i);
  72923. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  72924. blurX.autoClear = false;
  72925. _this._depthOfFieldBlurY.push(blurY);
  72926. _this._depthOfFieldBlurX.push(blurX);
  72927. }
  72928. // Set all post processes on the effect.
  72929. _this._effects = [_this._circleOfConfusion];
  72930. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  72931. _this._effects.push(_this._depthOfFieldBlurY[i]);
  72932. _this._effects.push(_this._depthOfFieldBlurX[i]);
  72933. }
  72934. // Merge blurred images with original image based on circleOfConfusion
  72935. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  72936. _this._dofMerge.autoClear = false;
  72937. _this._effects.push(_this._dofMerge);
  72938. return _this;
  72939. }
  72940. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  72941. get: function () {
  72942. return this._circleOfConfusion.focalLength;
  72943. },
  72944. /**
  72945. * The focal the length of the camera used in the effect
  72946. */
  72947. set: function (value) {
  72948. this._circleOfConfusion.focalLength = value;
  72949. },
  72950. enumerable: true,
  72951. configurable: true
  72952. });
  72953. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  72954. get: function () {
  72955. return this._circleOfConfusion.fStop;
  72956. },
  72957. /**
  72958. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  72959. */
  72960. set: function (value) {
  72961. this._circleOfConfusion.fStop = value;
  72962. },
  72963. enumerable: true,
  72964. configurable: true
  72965. });
  72966. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  72967. get: function () {
  72968. return this._circleOfConfusion.focusDistance;
  72969. },
  72970. /**
  72971. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  72972. */
  72973. set: function (value) {
  72974. this._circleOfConfusion.focusDistance = value;
  72975. },
  72976. enumerable: true,
  72977. configurable: true
  72978. });
  72979. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  72980. get: function () {
  72981. return this._circleOfConfusion.lensSize;
  72982. },
  72983. /**
  72984. * 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.
  72985. */
  72986. set: function (value) {
  72987. this._circleOfConfusion.lensSize = value;
  72988. },
  72989. enumerable: true,
  72990. configurable: true
  72991. });
  72992. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  72993. /**
  72994. * 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.
  72995. */
  72996. set: function (value) {
  72997. this._circleOfConfusion.depthTexture = value;
  72998. },
  72999. enumerable: true,
  73000. configurable: true
  73001. });
  73002. /**
  73003. * Disposes each of the internal effects for a given camera.
  73004. * @param camera The camera to dispose the effect on.
  73005. */
  73006. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  73007. for (var effect in this._effects) {
  73008. this._effects[effect].dispose(camera);
  73009. }
  73010. };
  73011. /**
  73012. * Internal
  73013. */
  73014. DepthOfFieldEffect.prototype._updateEffects = function () {
  73015. for (var effect in this._effects) {
  73016. this._effects[effect].updateEffect();
  73017. }
  73018. };
  73019. /**
  73020. * Internal
  73021. * @returns if all the contained post processes are ready.
  73022. */
  73023. DepthOfFieldEffect.prototype._isReady = function () {
  73024. for (var effect in this._effects) {
  73025. if (!this._effects[effect].isReady()) {
  73026. return false;
  73027. }
  73028. }
  73029. return true;
  73030. };
  73031. return DepthOfFieldEffect;
  73032. }(BABYLON.PostProcessRenderEffect));
  73033. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  73034. })(BABYLON || (BABYLON = {}));
  73035. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  73036. "use strict";
  73037. var BABYLON;
  73038. (function (BABYLON) {
  73039. /**
  73040. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73041. */
  73042. var BloomMergePostProcess = /** @class */ (function (_super) {
  73043. __extends(BloomMergePostProcess, _super);
  73044. /**
  73045. * Creates a new instance of @see BloomMergePostProcess
  73046. * @param name The name of the effect.
  73047. * @param originalFromInput Post process which's input will be used for the merge.
  73048. * @param blurred Blurred highlights post process which's output will be used.
  73049. * @param weight Weight of the bloom to be added to the original input.
  73050. * @param options The required width/height ratio to downsize to before computing the render pass.
  73051. * @param camera The camera to apply the render pass to.
  73052. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73053. * @param engine The engine which the post process will be applied. (default: current engine)
  73054. * @param reusable If the post process can be reused on the same frame. (default: false)
  73055. * @param textureType Type of textures used when performing the post process. (default: 0)
  73056. * @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)
  73057. */
  73058. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73059. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73060. if (blockCompilation === void 0) { blockCompilation = false; }
  73061. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73062. _this.weight = weight;
  73063. _this.onApplyObservable.add(function (effect) {
  73064. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73065. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  73066. effect.setFloat("bloomWeight", _this.weight);
  73067. });
  73068. if (!blockCompilation) {
  73069. _this.updateEffect();
  73070. }
  73071. return _this;
  73072. }
  73073. return BloomMergePostProcess;
  73074. }(BABYLON.PostProcess));
  73075. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  73076. })(BABYLON || (BABYLON = {}));
  73077. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  73078. "use strict";
  73079. var BABYLON;
  73080. (function (BABYLON) {
  73081. /**
  73082. * 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.
  73083. */
  73084. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  73085. __extends(ExtractHighlightsPostProcess, _super);
  73086. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73087. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73088. if (blockCompilation === void 0) { blockCompilation = false; }
  73089. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73090. /**
  73091. * The luminance threshold, pixels below this value will be set to black.
  73092. */
  73093. _this.threshold = 0.9;
  73094. /**
  73095. * Internal
  73096. */
  73097. _this._exposure = 1;
  73098. /**
  73099. * Post process which has the input texture to be used when performing highlight extraction
  73100. */
  73101. _this._inputPostProcess = null;
  73102. _this.onApplyObservable.add(function (effect) {
  73103. if (_this._inputPostProcess) {
  73104. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  73105. }
  73106. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  73107. effect.setFloat('exposure', _this._exposure);
  73108. });
  73109. return _this;
  73110. }
  73111. return ExtractHighlightsPostProcess;
  73112. }(BABYLON.PostProcess));
  73113. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  73114. })(BABYLON || (BABYLON = {}));
  73115. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  73116. "use strict";
  73117. var BABYLON;
  73118. (function (BABYLON) {
  73119. /**
  73120. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  73121. */
  73122. var BloomEffect = /** @class */ (function (_super) {
  73123. __extends(BloomEffect, _super);
  73124. /**
  73125. * Creates a new instance of @see BloomEffect
  73126. * @param scene The scene the effect belongs to.
  73127. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  73128. * @param bloomKernel The size of the kernel to be used when applying the blur.
  73129. * @param bloomWeight The the strength of bloom.
  73130. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73131. * @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)
  73132. */
  73133. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  73134. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73135. if (blockCompilation === void 0) { blockCompilation = false; }
  73136. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  73137. return _this._effects;
  73138. }, true) || this;
  73139. _this.bloomScale = bloomScale;
  73140. /**
  73141. * Internal
  73142. */
  73143. _this._effects = [];
  73144. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73145. _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);
  73146. _this._blurX.alwaysForcePOT = true;
  73147. _this._blurX.autoClear = false;
  73148. _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);
  73149. _this._blurY.alwaysForcePOT = true;
  73150. _this._blurY.autoClear = false;
  73151. _this.kernel = bloomKernel;
  73152. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  73153. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73154. _this._merge.autoClear = false;
  73155. _this._effects.push(_this._merge);
  73156. return _this;
  73157. }
  73158. Object.defineProperty(BloomEffect.prototype, "threshold", {
  73159. /**
  73160. * The luminance threshold to find bright areas of the image to bloom.
  73161. */
  73162. get: function () {
  73163. return this._downscale.threshold;
  73164. },
  73165. set: function (value) {
  73166. this._downscale.threshold = value;
  73167. },
  73168. enumerable: true,
  73169. configurable: true
  73170. });
  73171. Object.defineProperty(BloomEffect.prototype, "weight", {
  73172. /**
  73173. * The strength of the bloom.
  73174. */
  73175. get: function () {
  73176. return this._merge.weight;
  73177. },
  73178. set: function (value) {
  73179. this._merge.weight = value;
  73180. },
  73181. enumerable: true,
  73182. configurable: true
  73183. });
  73184. Object.defineProperty(BloomEffect.prototype, "kernel", {
  73185. /**
  73186. * Specifies the size of the bloom blur kernel, relative to the final output size
  73187. */
  73188. get: function () {
  73189. return this._blurX.kernel / this.bloomScale;
  73190. },
  73191. set: function (value) {
  73192. this._blurX.kernel = value * this.bloomScale;
  73193. this._blurY.kernel = value * this.bloomScale;
  73194. },
  73195. enumerable: true,
  73196. configurable: true
  73197. });
  73198. /**
  73199. * Disposes each of the internal effects for a given camera.
  73200. * @param camera The camera to dispose the effect on.
  73201. */
  73202. BloomEffect.prototype.disposeEffects = function (camera) {
  73203. for (var effect in this._effects) {
  73204. this._effects[effect].dispose(camera);
  73205. }
  73206. };
  73207. /**
  73208. * Internal
  73209. */
  73210. BloomEffect.prototype._updateEffects = function () {
  73211. for (var effect in this._effects) {
  73212. this._effects[effect].updateEffect();
  73213. }
  73214. };
  73215. /**
  73216. * Internal
  73217. * @returns if all the contained post processes are ready.
  73218. */
  73219. BloomEffect.prototype._isReady = function () {
  73220. for (var effect in this._effects) {
  73221. if (!this._effects[effect].isReady()) {
  73222. return false;
  73223. }
  73224. }
  73225. return true;
  73226. };
  73227. return BloomEffect;
  73228. }(BABYLON.PostProcessRenderEffect));
  73229. BABYLON.BloomEffect = BloomEffect;
  73230. })(BABYLON || (BABYLON = {}));
  73231. //# sourceMappingURL=babylon.bloomEffect.js.map
  73232. "use strict";
  73233. var BABYLON;
  73234. (function (BABYLON) {
  73235. /**
  73236. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  73237. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  73238. */
  73239. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  73240. __extends(DefaultRenderingPipeline, _super);
  73241. /**
  73242. * @constructor
  73243. * @param {string} name - The rendering pipeline name
  73244. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73245. * @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)
  73246. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73247. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  73248. */
  73249. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  73250. if (automaticBuild === void 0) { automaticBuild = true; }
  73251. var _this = _super.call(this, scene.getEngine(), name) || this;
  73252. _this._originalCameras = [];
  73253. /**
  73254. * ID of the sharpen post process,
  73255. */
  73256. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  73257. /**
  73258. * ID of the image processing post process;
  73259. */
  73260. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  73261. /**
  73262. * ID of the Fast Approximate Anti-Aliasing post process;
  73263. */
  73264. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  73265. /**
  73266. * ID of the chromatic aberration post process,
  73267. */
  73268. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  73269. /**
  73270. * ID of the grain post process
  73271. */
  73272. _this.GrainPostProcessId = "GrainPostProcessEffect";
  73273. /**
  73274. * Animations which can be used to tweak settings over a period of time
  73275. */
  73276. _this.animations = [];
  73277. _this._imageProcessingConfigurationObserver = null;
  73278. // Values
  73279. _this._sharpenEnabled = false;
  73280. _this._bloomEnabled = false;
  73281. _this._depthOfFieldEnabled = false;
  73282. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  73283. _this._fxaaEnabled = false;
  73284. _this._imageProcessingEnabled = true;
  73285. _this._bloomScale = 0.5;
  73286. _this._chromaticAberrationEnabled = false;
  73287. _this._grainEnabled = false;
  73288. _this._buildAllowed = true;
  73289. _this._resizeObserver = null;
  73290. _this._hardwareScaleLevel = 1.0;
  73291. _this._bloomKernel = 64;
  73292. /**
  73293. * Specifies the weight of the bloom in the final rendering
  73294. */
  73295. _this._bloomWeight = 0.15;
  73296. /**
  73297. * Specifies the luma threshold for the area that will be blurred by the bloom
  73298. */
  73299. _this._bloomThreshold = 0.9;
  73300. _this._samples = 1;
  73301. _this._hasCleared = false;
  73302. _this._prevPostProcess = null;
  73303. _this._prevPrevPostProcess = null;
  73304. _this._cameras = cameras || [];
  73305. _this._originalCameras = _this._cameras.slice();
  73306. _this._buildAllowed = automaticBuild;
  73307. // Initialize
  73308. _this._scene = scene;
  73309. var caps = _this._scene.getEngine().getCaps();
  73310. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  73311. // Misc
  73312. if (_this._hdr) {
  73313. if (caps.textureHalfFloatRender) {
  73314. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73315. }
  73316. else if (caps.textureFloatRender) {
  73317. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73318. }
  73319. }
  73320. else {
  73321. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73322. }
  73323. // Attach
  73324. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73325. var engine = _this._scene.getEngine();
  73326. // Create post processes before hand so they can be modified before enabled.
  73327. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  73328. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73329. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  73330. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  73331. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  73332. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73333. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  73334. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73335. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  73336. _this._resizeObserver = engine.onResizeObservable.add(function () {
  73337. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  73338. _this.bloomKernel = _this.bloomKernel;
  73339. });
  73340. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  73341. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  73342. });
  73343. _this._buildPipeline();
  73344. return _this;
  73345. }
  73346. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  73347. get: function () {
  73348. return this._sharpenEnabled;
  73349. },
  73350. /**
  73351. * Enable or disable the sharpen process from the pipeline
  73352. */
  73353. set: function (enabled) {
  73354. if (this._sharpenEnabled === enabled) {
  73355. return;
  73356. }
  73357. this._sharpenEnabled = enabled;
  73358. this._buildPipeline();
  73359. },
  73360. enumerable: true,
  73361. configurable: true
  73362. });
  73363. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  73364. /**
  73365. * Specifies the size of the bloom blur kernel, relative to the final output size
  73366. */
  73367. get: function () {
  73368. return this._bloomKernel;
  73369. },
  73370. set: function (value) {
  73371. this._bloomKernel = value;
  73372. this.bloom.kernel = value / this._hardwareScaleLevel;
  73373. },
  73374. enumerable: true,
  73375. configurable: true
  73376. });
  73377. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  73378. get: function () {
  73379. return this._bloomWeight;
  73380. },
  73381. /**
  73382. * The strength of the bloom.
  73383. */
  73384. set: function (value) {
  73385. if (this._bloomWeight === value) {
  73386. return;
  73387. }
  73388. this.bloom.weight = value;
  73389. this._bloomWeight = value;
  73390. },
  73391. enumerable: true,
  73392. configurable: true
  73393. });
  73394. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  73395. get: function () {
  73396. return this._bloomThreshold;
  73397. },
  73398. /**
  73399. * The strength of the bloom.
  73400. */
  73401. set: function (value) {
  73402. if (this._bloomThreshold === value) {
  73403. return;
  73404. }
  73405. this.bloom.threshold = value;
  73406. this._bloomThreshold = value;
  73407. },
  73408. enumerable: true,
  73409. configurable: true
  73410. });
  73411. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  73412. get: function () {
  73413. return this._bloomScale;
  73414. },
  73415. /**
  73416. * The scale of the bloom, lower value will provide better performance.
  73417. */
  73418. set: function (value) {
  73419. if (this._bloomScale === value) {
  73420. return;
  73421. }
  73422. this._bloomScale = value;
  73423. // recreate bloom and dispose old as this setting is not dynamic
  73424. this._rebuildBloom();
  73425. this._buildPipeline();
  73426. },
  73427. enumerable: true,
  73428. configurable: true
  73429. });
  73430. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  73431. get: function () {
  73432. return this._bloomEnabled;
  73433. },
  73434. /**
  73435. * Enable or disable the bloom from the pipeline
  73436. */
  73437. set: function (enabled) {
  73438. if (this._bloomEnabled === enabled) {
  73439. return;
  73440. }
  73441. this._bloomEnabled = enabled;
  73442. this._buildPipeline();
  73443. },
  73444. enumerable: true,
  73445. configurable: true
  73446. });
  73447. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  73448. // recreate bloom and dispose old as this setting is not dynamic
  73449. var oldBloom = this.bloom;
  73450. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  73451. this.bloom.threshold = oldBloom.threshold;
  73452. for (var i = 0; i < this._cameras.length; i++) {
  73453. oldBloom.disposeEffects(this._cameras[i]);
  73454. }
  73455. };
  73456. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  73457. /**
  73458. * If the depth of field is enabled.
  73459. */
  73460. get: function () {
  73461. return this._depthOfFieldEnabled;
  73462. },
  73463. set: function (enabled) {
  73464. if (this._depthOfFieldEnabled === enabled) {
  73465. return;
  73466. }
  73467. this._depthOfFieldEnabled = enabled;
  73468. this._buildPipeline();
  73469. },
  73470. enumerable: true,
  73471. configurable: true
  73472. });
  73473. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  73474. /**
  73475. * Blur level of the depth of field effect. (Higher blur will effect performance)
  73476. */
  73477. get: function () {
  73478. return this._depthOfFieldBlurLevel;
  73479. },
  73480. set: function (value) {
  73481. if (this._depthOfFieldBlurLevel === value) {
  73482. return;
  73483. }
  73484. this._depthOfFieldBlurLevel = value;
  73485. // recreate dof and dispose old as this setting is not dynamic
  73486. var oldDof = this.depthOfField;
  73487. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  73488. this.depthOfField.focalLength = oldDof.focalLength;
  73489. this.depthOfField.focusDistance = oldDof.focusDistance;
  73490. this.depthOfField.fStop = oldDof.fStop;
  73491. this.depthOfField.lensSize = oldDof.lensSize;
  73492. for (var i = 0; i < this._cameras.length; i++) {
  73493. oldDof.disposeEffects(this._cameras[i]);
  73494. }
  73495. this._buildPipeline();
  73496. },
  73497. enumerable: true,
  73498. configurable: true
  73499. });
  73500. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  73501. get: function () {
  73502. return this._fxaaEnabled;
  73503. },
  73504. /**
  73505. * If the anti aliasing is enabled.
  73506. */
  73507. set: function (enabled) {
  73508. if (this._fxaaEnabled === enabled) {
  73509. return;
  73510. }
  73511. this._fxaaEnabled = enabled;
  73512. this._buildPipeline();
  73513. },
  73514. enumerable: true,
  73515. configurable: true
  73516. });
  73517. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  73518. get: function () {
  73519. return this._samples;
  73520. },
  73521. /**
  73522. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  73523. */
  73524. set: function (sampleCount) {
  73525. if (this._samples === sampleCount) {
  73526. return;
  73527. }
  73528. this._samples = sampleCount;
  73529. this._buildPipeline();
  73530. },
  73531. enumerable: true,
  73532. configurable: true
  73533. });
  73534. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  73535. get: function () {
  73536. return this._imageProcessingEnabled;
  73537. },
  73538. /**
  73539. * If image processing is enabled.
  73540. */
  73541. set: function (enabled) {
  73542. if (this._imageProcessingEnabled === enabled) {
  73543. return;
  73544. }
  73545. this._imageProcessingEnabled = enabled;
  73546. this._buildPipeline();
  73547. },
  73548. enumerable: true,
  73549. configurable: true
  73550. });
  73551. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  73552. get: function () {
  73553. return this._chromaticAberrationEnabled;
  73554. },
  73555. /**
  73556. * Enable or disable the chromaticAberration process from the pipeline
  73557. */
  73558. set: function (enabled) {
  73559. if (this._chromaticAberrationEnabled === enabled) {
  73560. return;
  73561. }
  73562. this._chromaticAberrationEnabled = enabled;
  73563. this._buildPipeline();
  73564. },
  73565. enumerable: true,
  73566. configurable: true
  73567. });
  73568. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  73569. get: function () {
  73570. return this._grainEnabled;
  73571. },
  73572. /**
  73573. * Enable or disable the grain process from the pipeline
  73574. */
  73575. set: function (enabled) {
  73576. if (this._grainEnabled === enabled) {
  73577. return;
  73578. }
  73579. this._grainEnabled = enabled;
  73580. this._buildPipeline();
  73581. },
  73582. enumerable: true,
  73583. configurable: true
  73584. });
  73585. /**
  73586. * Force the compilation of the entire pipeline.
  73587. */
  73588. DefaultRenderingPipeline.prototype.prepare = function () {
  73589. var previousState = this._buildAllowed;
  73590. this._buildAllowed = true;
  73591. this._buildPipeline();
  73592. this._buildAllowed = previousState;
  73593. };
  73594. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  73595. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  73596. if (this._hasCleared) {
  73597. postProcess.autoClear = false;
  73598. }
  73599. else {
  73600. postProcess.autoClear = true;
  73601. this._scene.autoClear = false;
  73602. this._hasCleared = true;
  73603. }
  73604. if (!skipTextureSharing) {
  73605. if (this._prevPrevPostProcess) {
  73606. postProcess.shareOutputWith(this._prevPrevPostProcess);
  73607. }
  73608. else {
  73609. postProcess.useOwnOutput();
  73610. }
  73611. if (this._prevPostProcess) {
  73612. this._prevPrevPostProcess = this._prevPostProcess;
  73613. }
  73614. this._prevPostProcess = postProcess;
  73615. }
  73616. };
  73617. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  73618. var _this = this;
  73619. if (!this._buildAllowed) {
  73620. return;
  73621. }
  73622. this._scene.autoClear = true;
  73623. var engine = this._scene.getEngine();
  73624. this._disposePostProcesses();
  73625. if (this._cameras !== null) {
  73626. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73627. // get back cameras to be used to reattach pipeline
  73628. this._cameras = this._originalCameras.slice();
  73629. }
  73630. this._reset();
  73631. this._prevPostProcess = null;
  73632. this._prevPrevPostProcess = null;
  73633. this._hasCleared = false;
  73634. if (this.depthOfFieldEnabled) {
  73635. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  73636. this.depthOfField.depthTexture = depthTexture;
  73637. if (!this.depthOfField._isReady()) {
  73638. this.depthOfField._updateEffects();
  73639. }
  73640. this.addEffect(this.depthOfField);
  73641. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  73642. }
  73643. if (this.bloomEnabled) {
  73644. if (!this.bloom._isReady()) {
  73645. this.bloom._updateEffects();
  73646. }
  73647. this.addEffect(this.bloom);
  73648. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  73649. }
  73650. if (this._imageProcessingEnabled) {
  73651. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  73652. if (this._hdr) {
  73653. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  73654. this._setAutoClearAndTextureSharing(this.imageProcessing);
  73655. }
  73656. else {
  73657. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  73658. }
  73659. }
  73660. if (this.sharpenEnabled) {
  73661. if (!this.sharpen.isReady()) {
  73662. this.sharpen.updateEffect();
  73663. }
  73664. this.addEffect(this._sharpenEffect);
  73665. this._setAutoClearAndTextureSharing(this.sharpen);
  73666. }
  73667. if (this.grainEnabled) {
  73668. if (!this.grain.isReady()) {
  73669. this.grain.updateEffect();
  73670. }
  73671. this.addEffect(this._grainEffect);
  73672. this._setAutoClearAndTextureSharing(this.grain);
  73673. }
  73674. if (this.chromaticAberrationEnabled) {
  73675. if (!this.chromaticAberration.isReady()) {
  73676. this.chromaticAberration.updateEffect();
  73677. }
  73678. this.addEffect(this._chromaticAberrationEffect);
  73679. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  73680. }
  73681. if (this.fxaaEnabled) {
  73682. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  73683. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  73684. this._setAutoClearAndTextureSharing(this.fxaa, true);
  73685. }
  73686. if (this._cameras !== null) {
  73687. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73688. }
  73689. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  73690. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  73691. }
  73692. };
  73693. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  73694. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  73695. for (var i = 0; i < this._cameras.length; i++) {
  73696. var camera = this._cameras[i];
  73697. if (this.imageProcessing) {
  73698. this.imageProcessing.dispose(camera);
  73699. }
  73700. if (this.fxaa) {
  73701. this.fxaa.dispose(camera);
  73702. }
  73703. // These are created in the constructor and should not be disposed on every pipeline change
  73704. if (disposeNonRecreated) {
  73705. if (this.sharpen) {
  73706. this.sharpen.dispose(camera);
  73707. }
  73708. if (this.depthOfField) {
  73709. this.depthOfField.disposeEffects(camera);
  73710. }
  73711. if (this.bloom) {
  73712. this.bloom.disposeEffects(camera);
  73713. }
  73714. if (this.chromaticAberration) {
  73715. this.chromaticAberration.dispose(camera);
  73716. }
  73717. if (this.grain) {
  73718. this.grain.dispose(camera);
  73719. }
  73720. }
  73721. }
  73722. this.imageProcessing = null;
  73723. this.fxaa = null;
  73724. if (disposeNonRecreated) {
  73725. this.sharpen = null;
  73726. this._sharpenEffect = null;
  73727. this.depthOfField = null;
  73728. this.bloom = null;
  73729. this.chromaticAberration = null;
  73730. this._chromaticAberrationEffect = null;
  73731. this.grain = null;
  73732. this._grainEffect = null;
  73733. }
  73734. };
  73735. /**
  73736. * Dispose of the pipeline and stop all post processes
  73737. */
  73738. DefaultRenderingPipeline.prototype.dispose = function () {
  73739. this._disposePostProcesses(true);
  73740. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73741. this._scene.autoClear = true;
  73742. if (this._resizeObserver) {
  73743. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  73744. this._resizeObserver = null;
  73745. }
  73746. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  73747. _super.prototype.dispose.call(this);
  73748. };
  73749. /**
  73750. * Serialize the rendering pipeline (Used when exporting)
  73751. * @returns the serialized object
  73752. */
  73753. DefaultRenderingPipeline.prototype.serialize = function () {
  73754. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73755. serializationObject.customType = "DefaultRenderingPipeline";
  73756. return serializationObject;
  73757. };
  73758. /**
  73759. * Parse the serialized pipeline
  73760. * @param source Source pipeline.
  73761. * @param scene The scene to load the pipeline to.
  73762. * @param rootUrl The URL of the serialized pipeline.
  73763. * @returns An instantiated pipeline from the serialized object.
  73764. */
  73765. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73766. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  73767. };
  73768. __decorate([
  73769. BABYLON.serialize()
  73770. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  73771. __decorate([
  73772. BABYLON.serialize()
  73773. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  73774. __decorate([
  73775. BABYLON.serialize()
  73776. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  73777. __decorate([
  73778. BABYLON.serialize()
  73779. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  73780. __decorate([
  73781. BABYLON.serialize()
  73782. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  73783. __decorate([
  73784. BABYLON.serialize()
  73785. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  73786. __decorate([
  73787. BABYLON.serialize()
  73788. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  73789. __decorate([
  73790. BABYLON.serialize()
  73791. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  73792. __decorate([
  73793. BABYLON.serialize()
  73794. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  73795. __decorate([
  73796. BABYLON.serialize()
  73797. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  73798. __decorate([
  73799. BABYLON.serialize()
  73800. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  73801. __decorate([
  73802. BABYLON.serialize()
  73803. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  73804. __decorate([
  73805. BABYLON.serialize()
  73806. ], DefaultRenderingPipeline.prototype, "samples", null);
  73807. __decorate([
  73808. BABYLON.serialize()
  73809. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  73810. __decorate([
  73811. BABYLON.serialize()
  73812. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  73813. __decorate([
  73814. BABYLON.serialize()
  73815. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  73816. return DefaultRenderingPipeline;
  73817. }(BABYLON.PostProcessRenderPipeline));
  73818. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  73819. })(BABYLON || (BABYLON = {}));
  73820. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  73821. "use strict";
  73822. var BABYLON;
  73823. (function (BABYLON) {
  73824. /**
  73825. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  73826. */
  73827. var GeometryBufferRenderer = /** @class */ (function () {
  73828. /**
  73829. * Creates a new G Buffer for the scene
  73830. * @param scene The scene the buffer belongs to
  73831. * @param ratio How big is the buffer related to the main canvas.
  73832. */
  73833. function GeometryBufferRenderer(scene, ratio) {
  73834. if (ratio === void 0) { ratio = 1; }
  73835. this._enablePosition = false;
  73836. this._scene = scene;
  73837. this._ratio = ratio;
  73838. // Render target
  73839. this._createRenderTargets();
  73840. }
  73841. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  73842. /**
  73843. * Set the render list (meshes to be rendered) used in the G buffer.
  73844. */
  73845. set: function (meshes) {
  73846. this._multiRenderTarget.renderList = meshes;
  73847. },
  73848. enumerable: true,
  73849. configurable: true
  73850. });
  73851. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  73852. /**
  73853. * Gets wether or not G buffer are supported by the running hardware.
  73854. * This requires draw buffer supports
  73855. */
  73856. get: function () {
  73857. return this._multiRenderTarget.isSupported;
  73858. },
  73859. enumerable: true,
  73860. configurable: true
  73861. });
  73862. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  73863. /**
  73864. * Gets wether or not position are enabled for the G buffer.
  73865. */
  73866. get: function () {
  73867. return this._enablePosition;
  73868. },
  73869. /**
  73870. * Sets wether or not position are enabled for the G buffer.
  73871. */
  73872. set: function (enable) {
  73873. this._enablePosition = enable;
  73874. this.dispose();
  73875. this._createRenderTargets();
  73876. },
  73877. enumerable: true,
  73878. configurable: true
  73879. });
  73880. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  73881. /**
  73882. * Gets the scene associated with the buffer.
  73883. */
  73884. get: function () {
  73885. return this._scene;
  73886. },
  73887. enumerable: true,
  73888. configurable: true
  73889. });
  73890. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  73891. /**
  73892. * Gets the ratio used by the buffer during its creation.
  73893. * How big is the buffer related to the main canvas.
  73894. */
  73895. get: function () {
  73896. return this._ratio;
  73897. },
  73898. enumerable: true,
  73899. configurable: true
  73900. });
  73901. /**
  73902. * Checks wether everything is ready to render a submesh to the G buffer.
  73903. * @param subMesh the submesh to check readiness for
  73904. * @param useInstances is the mesh drawn using instance or not
  73905. * @returns true if ready otherwise false
  73906. */
  73907. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  73908. var material = subMesh.getMaterial();
  73909. if (material && material.disableDepthWrite) {
  73910. return false;
  73911. }
  73912. var defines = [];
  73913. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  73914. var mesh = subMesh.getMesh();
  73915. // Alpha test
  73916. if (material && material.needAlphaTesting()) {
  73917. defines.push("#define ALPHATEST");
  73918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73919. attribs.push(BABYLON.VertexBuffer.UVKind);
  73920. defines.push("#define UV1");
  73921. }
  73922. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73923. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73924. defines.push("#define UV2");
  73925. }
  73926. }
  73927. // Buffers
  73928. if (this._enablePosition) {
  73929. defines.push("#define POSITION");
  73930. }
  73931. // Bones
  73932. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73933. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73934. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73935. if (mesh.numBoneInfluencers > 4) {
  73936. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73937. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73938. }
  73939. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73940. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73941. }
  73942. else {
  73943. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73944. }
  73945. // Instances
  73946. if (useInstances) {
  73947. defines.push("#define INSTANCES");
  73948. attribs.push("world0");
  73949. attribs.push("world1");
  73950. attribs.push("world2");
  73951. attribs.push("world3");
  73952. }
  73953. // Get correct effect
  73954. var join = defines.join("\n");
  73955. if (this._cachedDefines !== join) {
  73956. this._cachedDefines = join;
  73957. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  73958. }
  73959. return this._effect.isReady();
  73960. };
  73961. /**
  73962. * Gets the current underlying G Buffer.
  73963. * @returns the buffer
  73964. */
  73965. GeometryBufferRenderer.prototype.getGBuffer = function () {
  73966. return this._multiRenderTarget;
  73967. };
  73968. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  73969. /**
  73970. * Gets the number of samples used to render the buffer (anti aliasing).
  73971. */
  73972. get: function () {
  73973. return this._multiRenderTarget.samples;
  73974. },
  73975. /**
  73976. * Sets the number of samples used to render the buffer (anti aliasing).
  73977. */
  73978. set: function (value) {
  73979. this._multiRenderTarget.samples = value;
  73980. },
  73981. enumerable: true,
  73982. configurable: true
  73983. });
  73984. /**
  73985. * Disposes the renderer and frees up associated resources.
  73986. */
  73987. GeometryBufferRenderer.prototype.dispose = function () {
  73988. this.getGBuffer().dispose();
  73989. };
  73990. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  73991. var _this = this;
  73992. var engine = this._scene.getEngine();
  73993. var count = this._enablePosition ? 3 : 2;
  73994. 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 });
  73995. if (!this.isSupported) {
  73996. return;
  73997. }
  73998. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73999. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74000. this._multiRenderTarget.refreshRate = 1;
  74001. this._multiRenderTarget.renderParticles = false;
  74002. this._multiRenderTarget.renderList = null;
  74003. // set default depth value to 1.0 (far away)
  74004. this._multiRenderTarget.onClearObservable.add(function (engine) {
  74005. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  74006. });
  74007. // Custom render function
  74008. var renderSubMesh = function (subMesh) {
  74009. var mesh = subMesh.getRenderingMesh();
  74010. var scene = _this._scene;
  74011. var engine = scene.getEngine();
  74012. var material = subMesh.getMaterial();
  74013. if (!material) {
  74014. return;
  74015. }
  74016. // Culling
  74017. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74018. // Managing instances
  74019. var batch = mesh._getInstancesRenderList(subMesh._id);
  74020. if (batch.mustReturn) {
  74021. return;
  74022. }
  74023. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74024. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  74025. engine.enableEffect(_this._effect);
  74026. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74027. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74028. _this._effect.setMatrix("view", scene.getViewMatrix());
  74029. // Alpha test
  74030. if (material && material.needAlphaTesting()) {
  74031. var alphaTexture = material.getAlphaTestTexture();
  74032. if (alphaTexture) {
  74033. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74034. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74035. }
  74036. }
  74037. // Bones
  74038. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74039. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74040. }
  74041. // Draw
  74042. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74043. }
  74044. };
  74045. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74046. var index;
  74047. if (depthOnlySubMeshes.length) {
  74048. engine.setColorWrite(false);
  74049. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74050. renderSubMesh(depthOnlySubMeshes.data[index]);
  74051. }
  74052. engine.setColorWrite(true);
  74053. }
  74054. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74055. renderSubMesh(opaqueSubMeshes.data[index]);
  74056. }
  74057. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74058. renderSubMesh(alphaTestSubMeshes.data[index]);
  74059. }
  74060. };
  74061. };
  74062. return GeometryBufferRenderer;
  74063. }());
  74064. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  74065. })(BABYLON || (BABYLON = {}));
  74066. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  74067. "use strict";
  74068. var BABYLON;
  74069. (function (BABYLON) {
  74070. var RefractionPostProcess = /** @class */ (function (_super) {
  74071. __extends(RefractionPostProcess, _super);
  74072. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  74073. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  74074. _this.color = color;
  74075. _this.depth = depth;
  74076. _this.colorLevel = colorLevel;
  74077. _this._ownRefractionTexture = true;
  74078. _this.onActivateObservable.add(function (cam) {
  74079. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  74080. });
  74081. _this.onApplyObservable.add(function (effect) {
  74082. effect.setColor3("baseColor", _this.color);
  74083. effect.setFloat("depth", _this.depth);
  74084. effect.setFloat("colorLevel", _this.colorLevel);
  74085. effect.setTexture("refractionSampler", _this._refTexture);
  74086. });
  74087. return _this;
  74088. }
  74089. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  74090. /**
  74091. * Gets or sets the refraction texture
  74092. * Please note that you are responsible for disposing the texture if you set it manually
  74093. */
  74094. get: function () {
  74095. return this._refTexture;
  74096. },
  74097. set: function (value) {
  74098. if (this._refTexture && this._ownRefractionTexture) {
  74099. this._refTexture.dispose();
  74100. }
  74101. this._refTexture = value;
  74102. this._ownRefractionTexture = false;
  74103. },
  74104. enumerable: true,
  74105. configurable: true
  74106. });
  74107. // Methods
  74108. RefractionPostProcess.prototype.dispose = function (camera) {
  74109. if (this._refTexture && this._ownRefractionTexture) {
  74110. this._refTexture.dispose();
  74111. this._refTexture = null;
  74112. }
  74113. _super.prototype.dispose.call(this, camera);
  74114. };
  74115. return RefractionPostProcess;
  74116. }(BABYLON.PostProcess));
  74117. BABYLON.RefractionPostProcess = RefractionPostProcess;
  74118. })(BABYLON || (BABYLON = {}));
  74119. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  74120. "use strict";
  74121. var BABYLON;
  74122. (function (BABYLON) {
  74123. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  74124. __extends(BlackAndWhitePostProcess, _super);
  74125. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  74126. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  74127. _this.degree = 1;
  74128. _this.onApplyObservable.add(function (effect) {
  74129. effect.setFloat("degree", _this.degree);
  74130. });
  74131. return _this;
  74132. }
  74133. return BlackAndWhitePostProcess;
  74134. }(BABYLON.PostProcess));
  74135. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  74136. })(BABYLON || (BABYLON = {}));
  74137. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  74138. "use strict";
  74139. var BABYLON;
  74140. (function (BABYLON) {
  74141. /**
  74142. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  74143. * input texture to perform effects such as edge detection or sharpening
  74144. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74145. */
  74146. var ConvolutionPostProcess = /** @class */ (function (_super) {
  74147. __extends(ConvolutionPostProcess, _super);
  74148. /**
  74149. * Creates a new instance ConvolutionPostProcess
  74150. * @param name The name of the effect.
  74151. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  74152. * @param options The required width/height ratio to downsize to before computing the render pass.
  74153. * @param camera The camera to apply the render pass to.
  74154. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74155. * @param engine The engine which the post process will be applied. (default: current engine)
  74156. * @param reusable If the post process can be reused on the same frame. (default: false)
  74157. * @param textureType Type of textures used when performing the post process. (default: 0)
  74158. */
  74159. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  74160. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74161. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74162. _this.kernel = kernel;
  74163. _this.onApply = function (effect) {
  74164. effect.setFloat2("screenSize", _this.width, _this.height);
  74165. effect.setArray("kernel", _this.kernel);
  74166. };
  74167. return _this;
  74168. }
  74169. // Statics
  74170. /**
  74171. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74172. */
  74173. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  74174. /**
  74175. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74176. */
  74177. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  74178. /**
  74179. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74180. */
  74181. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  74182. /**
  74183. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74184. */
  74185. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  74186. /**
  74187. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74188. */
  74189. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  74190. /**
  74191. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74192. */
  74193. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  74194. return ConvolutionPostProcess;
  74195. }(BABYLON.PostProcess));
  74196. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  74197. })(BABYLON || (BABYLON = {}));
  74198. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  74199. "use strict";
  74200. var BABYLON;
  74201. (function (BABYLON) {
  74202. var FilterPostProcess = /** @class */ (function (_super) {
  74203. __extends(FilterPostProcess, _super);
  74204. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  74205. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  74206. _this.kernelMatrix = kernelMatrix;
  74207. _this.onApply = function (effect) {
  74208. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  74209. };
  74210. return _this;
  74211. }
  74212. return FilterPostProcess;
  74213. }(BABYLON.PostProcess));
  74214. BABYLON.FilterPostProcess = FilterPostProcess;
  74215. })(BABYLON || (BABYLON = {}));
  74216. //# sourceMappingURL=babylon.filterPostProcess.js.map
  74217. "use strict";
  74218. var BABYLON;
  74219. (function (BABYLON) {
  74220. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  74221. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  74222. __extends(VolumetricLightScatteringPostProcess, _super);
  74223. /**
  74224. * @constructor
  74225. * @param {string} name - The post-process name
  74226. * @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)
  74227. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  74228. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  74229. * @param {number} samples - The post-process quality, default 100
  74230. * @param {number} samplingMode - The post-process filtering mode
  74231. * @param {BABYLON.Engine} engine - The babylon engine
  74232. * @param {boolean} reusable - If the post-process is reusable
  74233. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  74234. */
  74235. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  74236. if (samples === void 0) { samples = 100; }
  74237. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74238. 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;
  74239. _this._screenCoordinates = BABYLON.Vector2.Zero();
  74240. /**
  74241. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  74242. */
  74243. _this.customMeshPosition = BABYLON.Vector3.Zero();
  74244. /**
  74245. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  74246. */
  74247. _this.useCustomMeshPosition = false;
  74248. /**
  74249. * If the post-process should inverse the light scattering direction
  74250. */
  74251. _this.invert = true;
  74252. /**
  74253. * Array containing the excluded meshes not rendered in the internal pass
  74254. */
  74255. _this.excludedMeshes = new Array();
  74256. /**
  74257. * Controls the overall intensity of the post-process
  74258. */
  74259. _this.exposure = 0.3;
  74260. /**
  74261. * Dissipates each sample's contribution in range [0, 1]
  74262. */
  74263. _this.decay = 0.96815;
  74264. /**
  74265. * Controls the overall intensity of each sample
  74266. */
  74267. _this.weight = 0.58767;
  74268. /**
  74269. * Controls the density of each sample
  74270. */
  74271. _this.density = 0.926;
  74272. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  74273. engine = scene.getEngine();
  74274. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  74275. // Configure mesh
  74276. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  74277. // Configure
  74278. _this._createPass(scene, ratio.passRatio || ratio);
  74279. _this.onActivate = function (camera) {
  74280. if (!_this.isSupported) {
  74281. _this.dispose(camera);
  74282. }
  74283. _this.onActivate = null;
  74284. };
  74285. _this.onApplyObservable.add(function (effect) {
  74286. _this._updateMeshScreenCoordinates(scene);
  74287. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  74288. effect.setFloat("exposure", _this.exposure);
  74289. effect.setFloat("decay", _this.decay);
  74290. effect.setFloat("weight", _this.weight);
  74291. effect.setFloat("density", _this.density);
  74292. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  74293. });
  74294. return _this;
  74295. }
  74296. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  74297. get: function () {
  74298. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74299. return false;
  74300. },
  74301. set: function (useDiffuseColor) {
  74302. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74303. },
  74304. enumerable: true,
  74305. configurable: true
  74306. });
  74307. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  74308. return "VolumetricLightScatteringPostProcess";
  74309. };
  74310. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  74311. var mesh = subMesh.getMesh();
  74312. // Render this.mesh as default
  74313. if (mesh === this.mesh && mesh.material) {
  74314. return mesh.material.isReady(mesh);
  74315. }
  74316. var defines = [];
  74317. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74318. var material = subMesh.getMaterial();
  74319. // Alpha test
  74320. if (material) {
  74321. if (material.needAlphaTesting()) {
  74322. defines.push("#define ALPHATEST");
  74323. }
  74324. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74325. attribs.push(BABYLON.VertexBuffer.UVKind);
  74326. defines.push("#define UV1");
  74327. }
  74328. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74329. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74330. defines.push("#define UV2");
  74331. }
  74332. }
  74333. // Bones
  74334. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74335. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74336. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74337. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74338. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  74339. }
  74340. else {
  74341. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74342. }
  74343. // Instances
  74344. if (useInstances) {
  74345. defines.push("#define INSTANCES");
  74346. attribs.push("world0");
  74347. attribs.push("world1");
  74348. attribs.push("world2");
  74349. attribs.push("world3");
  74350. }
  74351. // Get correct effect
  74352. var join = defines.join("\n");
  74353. if (this._cachedDefines !== join) {
  74354. this._cachedDefines = join;
  74355. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  74356. }
  74357. return this._volumetricLightScatteringPass.isReady();
  74358. };
  74359. /**
  74360. * Sets the new light position for light scattering effect
  74361. * @param {BABYLON.Vector3} The new custom light position
  74362. */
  74363. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  74364. this.customMeshPosition = position;
  74365. };
  74366. /**
  74367. * Returns the light position for light scattering effect
  74368. * @return {BABYLON.Vector3} The custom light position
  74369. */
  74370. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  74371. return this.customMeshPosition;
  74372. };
  74373. /**
  74374. * Disposes the internal assets and detaches the post-process from the camera
  74375. */
  74376. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  74377. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  74378. if (rttIndex !== -1) {
  74379. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  74380. }
  74381. this._volumetricLightScatteringRTT.dispose();
  74382. _super.prototype.dispose.call(this, camera);
  74383. };
  74384. /**
  74385. * Returns the render target texture used by the post-process
  74386. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  74387. */
  74388. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  74389. return this._volumetricLightScatteringRTT;
  74390. };
  74391. // Private methods
  74392. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  74393. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  74394. return true;
  74395. }
  74396. return false;
  74397. };
  74398. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  74399. var _this = this;
  74400. var engine = scene.getEngine();
  74401. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74402. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74403. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74404. this._volumetricLightScatteringRTT.renderList = null;
  74405. this._volumetricLightScatteringRTT.renderParticles = false;
  74406. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  74407. var camera = this.getCamera();
  74408. if (camera) {
  74409. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74410. }
  74411. else {
  74412. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74413. }
  74414. // Custom render function for submeshes
  74415. var renderSubMesh = function (subMesh) {
  74416. var mesh = subMesh.getRenderingMesh();
  74417. if (_this._meshExcluded(mesh)) {
  74418. return;
  74419. }
  74420. var material = subMesh.getMaterial();
  74421. if (!material) {
  74422. return;
  74423. }
  74424. var scene = mesh.getScene();
  74425. var engine = scene.getEngine();
  74426. // Culling
  74427. engine.setState(material.backFaceCulling);
  74428. // Managing instances
  74429. var batch = mesh._getInstancesRenderList(subMesh._id);
  74430. if (batch.mustReturn) {
  74431. return;
  74432. }
  74433. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74434. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  74435. var effect = _this._volumetricLightScatteringPass;
  74436. if (mesh === _this.mesh) {
  74437. if (subMesh.effect) {
  74438. effect = subMesh.effect;
  74439. }
  74440. else {
  74441. effect = material.getEffect();
  74442. }
  74443. }
  74444. engine.enableEffect(effect);
  74445. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  74446. if (mesh === _this.mesh) {
  74447. material.bind(mesh.getWorldMatrix(), mesh);
  74448. }
  74449. else {
  74450. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  74451. // Alpha test
  74452. if (material && material.needAlphaTesting()) {
  74453. var alphaTexture = material.getAlphaTestTexture();
  74454. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  74455. if (alphaTexture) {
  74456. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74457. }
  74458. }
  74459. // Bones
  74460. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74461. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74462. }
  74463. }
  74464. // Draw
  74465. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  74466. }
  74467. };
  74468. // Render target texture callbacks
  74469. var savedSceneClearColor;
  74470. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  74471. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  74472. savedSceneClearColor = scene.clearColor;
  74473. scene.clearColor = sceneClearColor;
  74474. });
  74475. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  74476. scene.clearColor = savedSceneClearColor;
  74477. });
  74478. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74479. var engine = scene.getEngine();
  74480. var index;
  74481. if (depthOnlySubMeshes.length) {
  74482. engine.setColorWrite(false);
  74483. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74484. renderSubMesh(depthOnlySubMeshes.data[index]);
  74485. }
  74486. engine.setColorWrite(true);
  74487. }
  74488. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74489. renderSubMesh(opaqueSubMeshes.data[index]);
  74490. }
  74491. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74492. renderSubMesh(alphaTestSubMeshes.data[index]);
  74493. }
  74494. if (transparentSubMeshes.length) {
  74495. // Sort sub meshes
  74496. for (index = 0; index < transparentSubMeshes.length; index++) {
  74497. var submesh = transparentSubMeshes.data[index];
  74498. var boundingInfo = submesh.getBoundingInfo();
  74499. if (boundingInfo && scene.activeCamera) {
  74500. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  74501. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  74502. }
  74503. }
  74504. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  74505. sortedArray.sort(function (a, b) {
  74506. // Alpha index first
  74507. if (a._alphaIndex > b._alphaIndex) {
  74508. return 1;
  74509. }
  74510. if (a._alphaIndex < b._alphaIndex) {
  74511. return -1;
  74512. }
  74513. // Then distance to camera
  74514. if (a._distanceToCamera < b._distanceToCamera) {
  74515. return 1;
  74516. }
  74517. if (a._distanceToCamera > b._distanceToCamera) {
  74518. return -1;
  74519. }
  74520. return 0;
  74521. });
  74522. // Render sub meshes
  74523. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  74524. for (index = 0; index < sortedArray.length; index++) {
  74525. renderSubMesh(sortedArray[index]);
  74526. }
  74527. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74528. }
  74529. };
  74530. };
  74531. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  74532. var transform = scene.getTransformMatrix();
  74533. var meshPosition;
  74534. if (this.useCustomMeshPosition) {
  74535. meshPosition = this.customMeshPosition;
  74536. }
  74537. else if (this.attachedNode) {
  74538. meshPosition = this.attachedNode.position;
  74539. }
  74540. else {
  74541. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  74542. }
  74543. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  74544. this._screenCoordinates.x = pos.x / this._viewPort.width;
  74545. this._screenCoordinates.y = pos.y / this._viewPort.height;
  74546. if (this.invert)
  74547. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  74548. };
  74549. // Static methods
  74550. /**
  74551. * Creates a default mesh for the Volumeric Light Scattering post-process
  74552. * @param {string} The mesh name
  74553. * @param {BABYLON.Scene} The scene where to create the mesh
  74554. * @return {BABYLON.Mesh} the default mesh
  74555. */
  74556. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  74557. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  74558. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  74559. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  74560. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  74561. mesh.material = material;
  74562. return mesh;
  74563. };
  74564. __decorate([
  74565. BABYLON.serializeAsVector3()
  74566. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  74567. __decorate([
  74568. BABYLON.serialize()
  74569. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  74570. __decorate([
  74571. BABYLON.serialize()
  74572. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  74573. __decorate([
  74574. BABYLON.serializeAsMeshReference()
  74575. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  74576. __decorate([
  74577. BABYLON.serialize()
  74578. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  74579. __decorate([
  74580. BABYLON.serialize()
  74581. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  74582. __decorate([
  74583. BABYLON.serialize()
  74584. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  74585. __decorate([
  74586. BABYLON.serialize()
  74587. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  74588. __decorate([
  74589. BABYLON.serialize()
  74590. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  74591. return VolumetricLightScatteringPostProcess;
  74592. }(BABYLON.PostProcess));
  74593. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  74594. })(BABYLON || (BABYLON = {}));
  74595. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  74596. "use strict";
  74597. //
  74598. // This post-process allows the modification of rendered colors by using
  74599. // a 'look-up table' (LUT). This effect is also called Color Grading.
  74600. //
  74601. // The object needs to be provided an url to a texture containing the color
  74602. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  74603. // Use an image editing software to tweak the LUT to match your needs.
  74604. //
  74605. // For an example of a color LUT, see here:
  74606. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  74607. // For explanations on color grading, see here:
  74608. // http://udn.epicgames.com/Three/ColorGrading.html
  74609. //
  74610. var BABYLON;
  74611. (function (BABYLON) {
  74612. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  74613. __extends(ColorCorrectionPostProcess, _super);
  74614. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  74615. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  74616. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74617. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  74618. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74619. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74620. _this.onApply = function (effect) {
  74621. effect.setTexture("colorTable", _this._colorTableTexture);
  74622. };
  74623. return _this;
  74624. }
  74625. return ColorCorrectionPostProcess;
  74626. }(BABYLON.PostProcess));
  74627. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  74628. })(BABYLON || (BABYLON = {}));
  74629. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  74630. "use strict";
  74631. var BABYLON;
  74632. (function (BABYLON) {
  74633. var TonemappingOperator;
  74634. (function (TonemappingOperator) {
  74635. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  74636. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  74637. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  74638. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  74639. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  74640. ;
  74641. var TonemapPostProcess = /** @class */ (function (_super) {
  74642. __extends(TonemapPostProcess, _super);
  74643. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  74644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74645. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74646. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  74647. _this._operator = _operator;
  74648. _this.exposureAdjustment = exposureAdjustment;
  74649. var defines = "#define ";
  74650. if (_this._operator === TonemappingOperator.Hable)
  74651. defines += "HABLE_TONEMAPPING";
  74652. else if (_this._operator === TonemappingOperator.Reinhard)
  74653. defines += "REINHARD_TONEMAPPING";
  74654. else if (_this._operator === TonemappingOperator.HejiDawson)
  74655. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  74656. else if (_this._operator === TonemappingOperator.Photographic)
  74657. defines += "PHOTOGRAPHIC_TONEMAPPING";
  74658. //sadly a second call to create the effect.
  74659. _this.updateEffect(defines);
  74660. _this.onApply = function (effect) {
  74661. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  74662. };
  74663. return _this;
  74664. }
  74665. return TonemapPostProcess;
  74666. }(BABYLON.PostProcess));
  74667. BABYLON.TonemapPostProcess = TonemapPostProcess;
  74668. })(BABYLON || (BABYLON = {}));
  74669. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  74670. "use strict";
  74671. var BABYLON;
  74672. (function (BABYLON) {
  74673. var DisplayPassPostProcess = /** @class */ (function (_super) {
  74674. __extends(DisplayPassPostProcess, _super);
  74675. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  74676. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  74677. }
  74678. return DisplayPassPostProcess;
  74679. }(BABYLON.PostProcess));
  74680. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  74681. })(BABYLON || (BABYLON = {}));
  74682. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  74683. "use strict";
  74684. var BABYLON;
  74685. (function (BABYLON) {
  74686. var HighlightsPostProcess = /** @class */ (function (_super) {
  74687. __extends(HighlightsPostProcess, _super);
  74688. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74689. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74690. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74691. }
  74692. return HighlightsPostProcess;
  74693. }(BABYLON.PostProcess));
  74694. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  74695. })(BABYLON || (BABYLON = {}));
  74696. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  74697. "use strict";
  74698. var BABYLON;
  74699. (function (BABYLON) {
  74700. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  74701. __extends(ImageProcessingPostProcess, _super);
  74702. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  74703. if (camera === void 0) { camera = null; }
  74704. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74705. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  74706. _this._fromLinearSpace = true;
  74707. /**
  74708. * Defines cache preventing GC.
  74709. */
  74710. _this._defines = {
  74711. IMAGEPROCESSING: false,
  74712. VIGNETTE: false,
  74713. VIGNETTEBLENDMODEMULTIPLY: false,
  74714. VIGNETTEBLENDMODEOPAQUE: false,
  74715. TONEMAPPING: false,
  74716. CONTRAST: false,
  74717. COLORCURVES: false,
  74718. COLORGRADING: false,
  74719. COLORGRADING3D: false,
  74720. FROMLINEARSPACE: false,
  74721. SAMPLER3DGREENDEPTH: false,
  74722. SAMPLER3DBGRMAP: false,
  74723. IMAGEPROCESSINGPOSTPROCESS: false,
  74724. EXPOSURE: false,
  74725. };
  74726. // Setup the configuration as forced by the constructor. This would then not force the
  74727. // scene materials output in linear space and let untouched the default forward pass.
  74728. if (imageProcessingConfiguration) {
  74729. imageProcessingConfiguration.applyByPostProcess = true;
  74730. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  74731. // This will cause the shader to be compiled
  74732. _this.fromLinearSpace = false;
  74733. }
  74734. else {
  74735. _this._attachImageProcessingConfiguration(null, true);
  74736. _this.imageProcessingConfiguration.applyByPostProcess = true;
  74737. }
  74738. _this.onApply = function (effect) {
  74739. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  74740. };
  74741. return _this;
  74742. }
  74743. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  74744. /**
  74745. * Gets the image processing configuration used either in this material.
  74746. */
  74747. get: function () {
  74748. return this._imageProcessingConfiguration;
  74749. },
  74750. /**
  74751. * Sets the Default image processing configuration used either in the this material.
  74752. *
  74753. * If sets to null, the scene one is in use.
  74754. */
  74755. set: function (value) {
  74756. this._attachImageProcessingConfiguration(value);
  74757. },
  74758. enumerable: true,
  74759. configurable: true
  74760. });
  74761. /**
  74762. * Attaches a new image processing configuration to the PBR Material.
  74763. * @param configuration
  74764. */
  74765. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  74766. var _this = this;
  74767. if (doNotBuild === void 0) { doNotBuild = false; }
  74768. if (configuration === this._imageProcessingConfiguration) {
  74769. return;
  74770. }
  74771. // Detaches observer.
  74772. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  74773. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  74774. }
  74775. // Pick the scene configuration if needed.
  74776. if (!configuration) {
  74777. var scene = null;
  74778. var engine = this.getEngine();
  74779. var camera = this.getCamera();
  74780. if (camera) {
  74781. scene = camera.getScene();
  74782. }
  74783. else if (engine && engine.scenes) {
  74784. var scenes = engine.scenes;
  74785. scene = scenes[scenes.length - 1];
  74786. }
  74787. else {
  74788. scene = BABYLON.Engine.LastCreatedScene;
  74789. }
  74790. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  74791. }
  74792. else {
  74793. this._imageProcessingConfiguration = configuration;
  74794. }
  74795. // Attaches observer.
  74796. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  74797. _this._updateParameters();
  74798. });
  74799. // Ensure the effect will be rebuilt.
  74800. if (!doNotBuild) {
  74801. this._updateParameters();
  74802. }
  74803. };
  74804. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  74805. /**
  74806. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  74807. */
  74808. get: function () {
  74809. return this.imageProcessingConfiguration.colorCurves;
  74810. },
  74811. /**
  74812. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  74813. */
  74814. set: function (value) {
  74815. this.imageProcessingConfiguration.colorCurves = value;
  74816. },
  74817. enumerable: true,
  74818. configurable: true
  74819. });
  74820. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  74821. /**
  74822. * Gets wether the color curves effect is enabled.
  74823. */
  74824. get: function () {
  74825. return this.imageProcessingConfiguration.colorCurvesEnabled;
  74826. },
  74827. /**
  74828. * Sets wether the color curves effect is enabled.
  74829. */
  74830. set: function (value) {
  74831. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  74832. },
  74833. enumerable: true,
  74834. configurable: true
  74835. });
  74836. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  74837. /**
  74838. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  74839. */
  74840. get: function () {
  74841. return this.imageProcessingConfiguration.colorGradingTexture;
  74842. },
  74843. /**
  74844. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  74845. */
  74846. set: function (value) {
  74847. this.imageProcessingConfiguration.colorGradingTexture = value;
  74848. },
  74849. enumerable: true,
  74850. configurable: true
  74851. });
  74852. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  74853. /**
  74854. * Gets wether the color grading effect is enabled.
  74855. */
  74856. get: function () {
  74857. return this.imageProcessingConfiguration.colorGradingEnabled;
  74858. },
  74859. /**
  74860. * Gets wether the color grading effect is enabled.
  74861. */
  74862. set: function (value) {
  74863. this.imageProcessingConfiguration.colorGradingEnabled = value;
  74864. },
  74865. enumerable: true,
  74866. configurable: true
  74867. });
  74868. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  74869. /**
  74870. * Gets exposure used in the effect.
  74871. */
  74872. get: function () {
  74873. return this.imageProcessingConfiguration.exposure;
  74874. },
  74875. /**
  74876. * Sets exposure used in the effect.
  74877. */
  74878. set: function (value) {
  74879. this.imageProcessingConfiguration.exposure = value;
  74880. },
  74881. enumerable: true,
  74882. configurable: true
  74883. });
  74884. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  74885. /**
  74886. * Gets wether tonemapping is enabled or not.
  74887. */
  74888. get: function () {
  74889. return this._imageProcessingConfiguration.toneMappingEnabled;
  74890. },
  74891. /**
  74892. * Sets wether tonemapping is enabled or not
  74893. */
  74894. set: function (value) {
  74895. this._imageProcessingConfiguration.toneMappingEnabled = value;
  74896. },
  74897. enumerable: true,
  74898. configurable: true
  74899. });
  74900. ;
  74901. ;
  74902. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  74903. /**
  74904. * Gets contrast used in the effect.
  74905. */
  74906. get: function () {
  74907. return this.imageProcessingConfiguration.contrast;
  74908. },
  74909. /**
  74910. * Sets contrast used in the effect.
  74911. */
  74912. set: function (value) {
  74913. this.imageProcessingConfiguration.contrast = value;
  74914. },
  74915. enumerable: true,
  74916. configurable: true
  74917. });
  74918. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  74919. /**
  74920. * Gets Vignette stretch size.
  74921. */
  74922. get: function () {
  74923. return this.imageProcessingConfiguration.vignetteStretch;
  74924. },
  74925. /**
  74926. * Sets Vignette stretch size.
  74927. */
  74928. set: function (value) {
  74929. this.imageProcessingConfiguration.vignetteStretch = value;
  74930. },
  74931. enumerable: true,
  74932. configurable: true
  74933. });
  74934. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  74935. /**
  74936. * Gets Vignette centre X Offset.
  74937. */
  74938. get: function () {
  74939. return this.imageProcessingConfiguration.vignetteCentreX;
  74940. },
  74941. /**
  74942. * Sets Vignette centre X Offset.
  74943. */
  74944. set: function (value) {
  74945. this.imageProcessingConfiguration.vignetteCentreX = value;
  74946. },
  74947. enumerable: true,
  74948. configurable: true
  74949. });
  74950. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  74951. /**
  74952. * Gets Vignette centre Y Offset.
  74953. */
  74954. get: function () {
  74955. return this.imageProcessingConfiguration.vignetteCentreY;
  74956. },
  74957. /**
  74958. * Sets Vignette centre Y Offset.
  74959. */
  74960. set: function (value) {
  74961. this.imageProcessingConfiguration.vignetteCentreY = value;
  74962. },
  74963. enumerable: true,
  74964. configurable: true
  74965. });
  74966. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  74967. /**
  74968. * Gets Vignette weight or intensity of the vignette effect.
  74969. */
  74970. get: function () {
  74971. return this.imageProcessingConfiguration.vignetteWeight;
  74972. },
  74973. /**
  74974. * Sets Vignette weight or intensity of the vignette effect.
  74975. */
  74976. set: function (value) {
  74977. this.imageProcessingConfiguration.vignetteWeight = value;
  74978. },
  74979. enumerable: true,
  74980. configurable: true
  74981. });
  74982. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  74983. /**
  74984. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  74985. * if vignetteEnabled is set to true.
  74986. */
  74987. get: function () {
  74988. return this.imageProcessingConfiguration.vignetteColor;
  74989. },
  74990. /**
  74991. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  74992. * if vignetteEnabled is set to true.
  74993. */
  74994. set: function (value) {
  74995. this.imageProcessingConfiguration.vignetteColor = value;
  74996. },
  74997. enumerable: true,
  74998. configurable: true
  74999. });
  75000. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  75001. /**
  75002. * Gets Camera field of view used by the Vignette effect.
  75003. */
  75004. get: function () {
  75005. return this.imageProcessingConfiguration.vignetteCameraFov;
  75006. },
  75007. /**
  75008. * Sets Camera field of view used by the Vignette effect.
  75009. */
  75010. set: function (value) {
  75011. this.imageProcessingConfiguration.vignetteCameraFov = value;
  75012. },
  75013. enumerable: true,
  75014. configurable: true
  75015. });
  75016. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  75017. /**
  75018. * Gets the vignette blend mode allowing different kind of effect.
  75019. */
  75020. get: function () {
  75021. return this.imageProcessingConfiguration.vignetteBlendMode;
  75022. },
  75023. /**
  75024. * Sets the vignette blend mode allowing different kind of effect.
  75025. */
  75026. set: function (value) {
  75027. this.imageProcessingConfiguration.vignetteBlendMode = value;
  75028. },
  75029. enumerable: true,
  75030. configurable: true
  75031. });
  75032. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  75033. /**
  75034. * Gets wether the vignette effect is enabled.
  75035. */
  75036. get: function () {
  75037. return this.imageProcessingConfiguration.vignetteEnabled;
  75038. },
  75039. /**
  75040. * Sets wether the vignette effect is enabled.
  75041. */
  75042. set: function (value) {
  75043. this.imageProcessingConfiguration.vignetteEnabled = value;
  75044. },
  75045. enumerable: true,
  75046. configurable: true
  75047. });
  75048. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  75049. /**
  75050. * Gets wether the input of the processing is in Gamma or Linear Space.
  75051. */
  75052. get: function () {
  75053. return this._fromLinearSpace;
  75054. },
  75055. /**
  75056. * Sets wether the input of the processing is in Gamma or Linear Space.
  75057. */
  75058. set: function (value) {
  75059. if (this._fromLinearSpace === value) {
  75060. return;
  75061. }
  75062. this._fromLinearSpace = value;
  75063. this._updateParameters();
  75064. },
  75065. enumerable: true,
  75066. configurable: true
  75067. });
  75068. ImageProcessingPostProcess.prototype.getClassName = function () {
  75069. return "ImageProcessingPostProcess";
  75070. };
  75071. ImageProcessingPostProcess.prototype._updateParameters = function () {
  75072. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  75073. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  75074. var defines = "";
  75075. for (var define in this._defines) {
  75076. if (this._defines[define]) {
  75077. defines += "#define " + define + ";\r\n";
  75078. }
  75079. }
  75080. var samplers = ["textureSampler"];
  75081. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  75082. var uniforms = ["scale"];
  75083. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  75084. this.updateEffect(defines, uniforms, samplers);
  75085. };
  75086. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  75087. _super.prototype.dispose.call(this, camera);
  75088. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75089. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75090. }
  75091. this.imageProcessingConfiguration.applyByPostProcess = false;
  75092. };
  75093. __decorate([
  75094. BABYLON.serialize()
  75095. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  75096. return ImageProcessingPostProcess;
  75097. }(BABYLON.PostProcess));
  75098. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  75099. })(BABYLON || (BABYLON = {}));
  75100. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  75101. "use strict";
  75102. var BABYLON;
  75103. (function (BABYLON) {
  75104. var Bone = /** @class */ (function (_super) {
  75105. __extends(Bone, _super);
  75106. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  75107. if (parentBone === void 0) { parentBone = null; }
  75108. if (localMatrix === void 0) { localMatrix = null; }
  75109. if (restPose === void 0) { restPose = null; }
  75110. if (baseMatrix === void 0) { baseMatrix = null; }
  75111. if (index === void 0) { index = null; }
  75112. var _this = _super.call(this, name, skeleton.getScene()) || this;
  75113. _this.name = name;
  75114. _this.children = new Array();
  75115. _this.animations = new Array();
  75116. // Set this value to map this bone to a different index in the transform matrices.
  75117. // Set this value to -1 to exclude the bone from the transform matrices.
  75118. _this._index = null;
  75119. _this._worldTransform = new BABYLON.Matrix();
  75120. _this._absoluteTransform = new BABYLON.Matrix();
  75121. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  75122. _this._scaleMatrix = BABYLON.Matrix.Identity();
  75123. _this._scaleVector = BABYLON.Vector3.One();
  75124. _this._negateScaleChildren = BABYLON.Vector3.One();
  75125. _this._scalingDeterminant = 1;
  75126. _this._skeleton = skeleton;
  75127. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  75128. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  75129. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  75130. _this._index = index;
  75131. skeleton.bones.push(_this);
  75132. _this.setParent(parentBone, false);
  75133. _this._updateDifferenceMatrix();
  75134. return _this;
  75135. }
  75136. Object.defineProperty(Bone.prototype, "_matrix", {
  75137. get: function () {
  75138. return this._localMatrix;
  75139. },
  75140. set: function (val) {
  75141. if (this._localMatrix) {
  75142. this._localMatrix.copyFrom(val);
  75143. }
  75144. else {
  75145. this._localMatrix = val;
  75146. }
  75147. },
  75148. enumerable: true,
  75149. configurable: true
  75150. });
  75151. // Members
  75152. Bone.prototype.getSkeleton = function () {
  75153. return this._skeleton;
  75154. };
  75155. Bone.prototype.getParent = function () {
  75156. return this._parent;
  75157. };
  75158. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  75159. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75160. if (this._parent === parent) {
  75161. return;
  75162. }
  75163. if (this._parent) {
  75164. var index = this._parent.children.indexOf(this);
  75165. if (index !== -1) {
  75166. this._parent.children.splice(index, 1);
  75167. }
  75168. }
  75169. this._parent = parent;
  75170. if (this._parent) {
  75171. this._parent.children.push(this);
  75172. }
  75173. if (updateDifferenceMatrix) {
  75174. this._updateDifferenceMatrix();
  75175. }
  75176. };
  75177. Bone.prototype.getLocalMatrix = function () {
  75178. return this._localMatrix;
  75179. };
  75180. Bone.prototype.getBaseMatrix = function () {
  75181. return this._baseMatrix;
  75182. };
  75183. Bone.prototype.getRestPose = function () {
  75184. return this._restPose;
  75185. };
  75186. Bone.prototype.returnToRest = function () {
  75187. this.updateMatrix(this._restPose.clone());
  75188. };
  75189. Bone.prototype.getWorldMatrix = function () {
  75190. return this._worldTransform;
  75191. };
  75192. Bone.prototype.getInvertedAbsoluteTransform = function () {
  75193. return this._invertedAbsoluteTransform;
  75194. };
  75195. Bone.prototype.getAbsoluteTransform = function () {
  75196. return this._absoluteTransform;
  75197. };
  75198. Object.defineProperty(Bone.prototype, "position", {
  75199. // Properties (matches AbstractMesh properties)
  75200. get: function () {
  75201. return this.getPosition();
  75202. },
  75203. set: function (newPosition) {
  75204. this.setPosition(newPosition);
  75205. },
  75206. enumerable: true,
  75207. configurable: true
  75208. });
  75209. Object.defineProperty(Bone.prototype, "rotation", {
  75210. get: function () {
  75211. return this.getRotation();
  75212. },
  75213. set: function (newRotation) {
  75214. this.setRotation(newRotation);
  75215. },
  75216. enumerable: true,
  75217. configurable: true
  75218. });
  75219. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  75220. get: function () {
  75221. return this.getRotationQuaternion();
  75222. },
  75223. set: function (newRotation) {
  75224. this.setRotationQuaternion(newRotation);
  75225. },
  75226. enumerable: true,
  75227. configurable: true
  75228. });
  75229. Object.defineProperty(Bone.prototype, "scaling", {
  75230. get: function () {
  75231. return this.getScale();
  75232. },
  75233. set: function (newScaling) {
  75234. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  75235. },
  75236. enumerable: true,
  75237. configurable: true
  75238. });
  75239. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  75240. /**
  75241. * Gets the animation properties override
  75242. */
  75243. get: function () {
  75244. return this._skeleton.animationPropertiesOverride;
  75245. },
  75246. enumerable: true,
  75247. configurable: true
  75248. });
  75249. // Methods
  75250. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  75251. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75252. this._baseMatrix = matrix.clone();
  75253. this._localMatrix = matrix.clone();
  75254. this._skeleton._markAsDirty();
  75255. if (updateDifferenceMatrix) {
  75256. this._updateDifferenceMatrix();
  75257. }
  75258. };
  75259. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  75260. if (!rootMatrix) {
  75261. rootMatrix = this._baseMatrix;
  75262. }
  75263. if (this._parent) {
  75264. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  75265. }
  75266. else {
  75267. this._absoluteTransform.copyFrom(rootMatrix);
  75268. }
  75269. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  75270. for (var index = 0; index < this.children.length; index++) {
  75271. this.children[index]._updateDifferenceMatrix();
  75272. }
  75273. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  75274. };
  75275. Bone.prototype.markAsDirty = function () {
  75276. this._currentRenderId++;
  75277. this._childRenderId++;
  75278. this._skeleton._markAsDirty();
  75279. };
  75280. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  75281. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  75282. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  75283. // all animation may be coming from a library skeleton, so may need to create animation
  75284. if (this.animations.length === 0) {
  75285. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  75286. this.animations[0].setKeys([]);
  75287. }
  75288. // get animation info / verify there is such a range from the source bone
  75289. var sourceRange = source.animations[0].getRange(rangeName);
  75290. if (!sourceRange) {
  75291. return false;
  75292. }
  75293. var from = sourceRange.from;
  75294. var to = sourceRange.to;
  75295. var sourceKeys = source.animations[0].getKeys();
  75296. // rescaling prep
  75297. var sourceBoneLength = source.length;
  75298. var sourceParent = source.getParent();
  75299. var parent = this.getParent();
  75300. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  75301. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  75302. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  75303. var destKeys = this.animations[0].getKeys();
  75304. // loop vars declaration
  75305. var orig;
  75306. var origTranslation;
  75307. var mat;
  75308. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  75309. orig = sourceKeys[key];
  75310. if (orig.frame >= from && orig.frame <= to) {
  75311. if (rescaleAsRequired) {
  75312. mat = orig.value.clone();
  75313. // scale based on parent ratio, when bone has parent
  75314. if (parentScalingReqd) {
  75315. origTranslation = mat.getTranslation();
  75316. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  75317. // scale based on skeleton dimension ratio when root bone, and value is passed
  75318. }
  75319. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  75320. origTranslation = mat.getTranslation();
  75321. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  75322. // use original when root bone, and no data for skelDimensionsRatio
  75323. }
  75324. else {
  75325. mat = orig.value;
  75326. }
  75327. }
  75328. else {
  75329. mat = orig.value;
  75330. }
  75331. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  75332. }
  75333. }
  75334. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  75335. return true;
  75336. };
  75337. /**
  75338. * Translate the bone in local or world space.
  75339. * @param vec The amount to translate the bone.
  75340. * @param space The space that the translation is in.
  75341. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75342. */
  75343. Bone.prototype.translate = function (vec, space, mesh) {
  75344. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75345. var lm = this.getLocalMatrix();
  75346. if (space == BABYLON.Space.LOCAL) {
  75347. lm.m[12] += vec.x;
  75348. lm.m[13] += vec.y;
  75349. lm.m[14] += vec.z;
  75350. }
  75351. else {
  75352. var wm = null;
  75353. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75354. if (mesh) {
  75355. wm = mesh.getWorldMatrix();
  75356. }
  75357. this._skeleton.computeAbsoluteTransforms();
  75358. var tmat = Bone._tmpMats[0];
  75359. var tvec = Bone._tmpVecs[0];
  75360. if (this._parent) {
  75361. if (mesh && wm) {
  75362. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75363. tmat.multiplyToRef(wm, tmat);
  75364. }
  75365. else {
  75366. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75367. }
  75368. }
  75369. tmat.m[12] = 0;
  75370. tmat.m[13] = 0;
  75371. tmat.m[14] = 0;
  75372. tmat.invert();
  75373. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  75374. lm.m[12] += tvec.x;
  75375. lm.m[13] += tvec.y;
  75376. lm.m[14] += tvec.z;
  75377. }
  75378. this.markAsDirty();
  75379. };
  75380. /**
  75381. * Set the postion of the bone in local or world space.
  75382. * @param position The position to set the bone.
  75383. * @param space The space that the position is in.
  75384. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75385. */
  75386. Bone.prototype.setPosition = function (position, space, mesh) {
  75387. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75388. var lm = this.getLocalMatrix();
  75389. if (space == BABYLON.Space.LOCAL) {
  75390. lm.m[12] = position.x;
  75391. lm.m[13] = position.y;
  75392. lm.m[14] = position.z;
  75393. }
  75394. else {
  75395. var wm = null;
  75396. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75397. if (mesh) {
  75398. wm = mesh.getWorldMatrix();
  75399. }
  75400. this._skeleton.computeAbsoluteTransforms();
  75401. var tmat = Bone._tmpMats[0];
  75402. var vec = Bone._tmpVecs[0];
  75403. if (this._parent) {
  75404. if (mesh && wm) {
  75405. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75406. tmat.multiplyToRef(wm, tmat);
  75407. }
  75408. else {
  75409. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75410. }
  75411. }
  75412. tmat.invert();
  75413. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  75414. lm.m[12] = vec.x;
  75415. lm.m[13] = vec.y;
  75416. lm.m[14] = vec.z;
  75417. }
  75418. this.markAsDirty();
  75419. };
  75420. /**
  75421. * Set the absolute postion of the bone (world space).
  75422. * @param position The position to set the bone.
  75423. * @param mesh The mesh that this bone is attached to.
  75424. */
  75425. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  75426. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  75427. };
  75428. /**
  75429. * Set the scale of the bone on the x, y and z axes.
  75430. * @param x The scale of the bone on the x axis.
  75431. * @param x The scale of the bone on the y axis.
  75432. * @param z The scale of the bone on the z axis.
  75433. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75434. */
  75435. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  75436. if (scaleChildren === void 0) { scaleChildren = false; }
  75437. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  75438. if (!scaleChildren) {
  75439. this._negateScaleChildren.x = 1 / x;
  75440. this._negateScaleChildren.y = 1 / y;
  75441. this._negateScaleChildren.z = 1 / z;
  75442. }
  75443. this._syncScaleVector();
  75444. }
  75445. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  75446. };
  75447. /**
  75448. * Scale the bone on the x, y and z axes.
  75449. * @param x The amount to scale the bone on the x axis.
  75450. * @param x The amount to scale the bone on the y axis.
  75451. * @param z The amount to scale the bone on the z axis.
  75452. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75453. */
  75454. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  75455. if (scaleChildren === void 0) { scaleChildren = false; }
  75456. var locMat = this.getLocalMatrix();
  75457. var origLocMat = Bone._tmpMats[0];
  75458. origLocMat.copyFrom(locMat);
  75459. var origLocMatInv = Bone._tmpMats[1];
  75460. origLocMatInv.copyFrom(origLocMat);
  75461. origLocMatInv.invert();
  75462. var scaleMat = Bone._tmpMats[2];
  75463. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  75464. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  75465. this._scaleVector.x *= x;
  75466. this._scaleVector.y *= y;
  75467. this._scaleVector.z *= z;
  75468. locMat.multiplyToRef(origLocMatInv, locMat);
  75469. locMat.multiplyToRef(scaleMat, locMat);
  75470. locMat.multiplyToRef(origLocMat, locMat);
  75471. var parent = this.getParent();
  75472. if (parent) {
  75473. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  75474. }
  75475. else {
  75476. this.getAbsoluteTransform().copyFrom(locMat);
  75477. }
  75478. var len = this.children.length;
  75479. scaleMat.invert();
  75480. for (var i = 0; i < len; i++) {
  75481. var child = this.children[i];
  75482. var cm = child.getLocalMatrix();
  75483. cm.multiplyToRef(scaleMat, cm);
  75484. var lm = child.getLocalMatrix();
  75485. lm.m[12] *= x;
  75486. lm.m[13] *= y;
  75487. lm.m[14] *= z;
  75488. }
  75489. this.computeAbsoluteTransforms();
  75490. if (scaleChildren) {
  75491. for (var i = 0; i < len; i++) {
  75492. this.children[i].scale(x, y, z, scaleChildren);
  75493. }
  75494. }
  75495. this.markAsDirty();
  75496. };
  75497. /**
  75498. * Set the yaw, pitch, and roll of the bone in local or world space.
  75499. * @param yaw The rotation of the bone on the y axis.
  75500. * @param pitch The rotation of the bone on the x axis.
  75501. * @param roll The rotation of the bone on the z axis.
  75502. * @param space The space that the axes of rotation are in.
  75503. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75504. */
  75505. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  75506. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75507. var rotMat = Bone._tmpMats[0];
  75508. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  75509. var rotMatInv = Bone._tmpMats[1];
  75510. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75511. rotMatInv.multiplyToRef(rotMat, rotMat);
  75512. this._rotateWithMatrix(rotMat, space, mesh);
  75513. };
  75514. /**
  75515. * Rotate the bone on an axis in local or world space.
  75516. * @param axis The axis to rotate the bone on.
  75517. * @param amount The amount to rotate the bone.
  75518. * @param space The space that the axis is in.
  75519. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75520. */
  75521. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  75522. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75523. var rmat = Bone._tmpMats[0];
  75524. rmat.m[12] = 0;
  75525. rmat.m[13] = 0;
  75526. rmat.m[14] = 0;
  75527. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  75528. this._rotateWithMatrix(rmat, space, mesh);
  75529. };
  75530. /**
  75531. * Set the rotation of the bone to a particular axis angle in local or world space.
  75532. * @param axis The axis to rotate the bone on.
  75533. * @param angle The angle that the bone should be rotated to.
  75534. * @param space The space that the axis is in.
  75535. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75536. */
  75537. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  75538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75539. var rotMat = Bone._tmpMats[0];
  75540. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  75541. var rotMatInv = Bone._tmpMats[1];
  75542. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75543. rotMatInv.multiplyToRef(rotMat, rotMat);
  75544. this._rotateWithMatrix(rotMat, space, mesh);
  75545. };
  75546. /**
  75547. * Set the euler rotation of the bone in local of world space.
  75548. * @param rotation The euler rotation that the bone should be set to.
  75549. * @param space The space that the rotation is in.
  75550. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75551. */
  75552. Bone.prototype.setRotation = function (rotation, space, mesh) {
  75553. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75554. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  75555. };
  75556. /**
  75557. * Set the quaternion rotation of the bone in local of world space.
  75558. * @param quat The quaternion rotation that the bone should be set to.
  75559. * @param space The space that the rotation is in.
  75560. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75561. */
  75562. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  75563. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75564. var rotMatInv = Bone._tmpMats[0];
  75565. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75566. var rotMat = Bone._tmpMats[1];
  75567. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  75568. rotMatInv.multiplyToRef(rotMat, rotMat);
  75569. this._rotateWithMatrix(rotMat, space, mesh);
  75570. };
  75571. /**
  75572. * Set the rotation matrix of the bone in local of world space.
  75573. * @param rotMat The rotation matrix that the bone should be set to.
  75574. * @param space The space that the rotation is in.
  75575. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75576. */
  75577. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  75578. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75579. var rotMatInv = Bone._tmpMats[0];
  75580. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  75581. var rotMat2 = Bone._tmpMats[1];
  75582. rotMat2.copyFrom(rotMat);
  75583. rotMatInv.multiplyToRef(rotMat, rotMat2);
  75584. this._rotateWithMatrix(rotMat2, space, mesh);
  75585. };
  75586. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  75587. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75588. var lmat = this.getLocalMatrix();
  75589. var lx = lmat.m[12];
  75590. var ly = lmat.m[13];
  75591. var lz = lmat.m[14];
  75592. var parent = this.getParent();
  75593. var parentScale = Bone._tmpMats[3];
  75594. var parentScaleInv = Bone._tmpMats[4];
  75595. if (parent) {
  75596. if (space == BABYLON.Space.WORLD) {
  75597. if (mesh) {
  75598. parentScale.copyFrom(mesh.getWorldMatrix());
  75599. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  75600. }
  75601. else {
  75602. parentScale.copyFrom(parent.getAbsoluteTransform());
  75603. }
  75604. }
  75605. else {
  75606. parentScale = parent._scaleMatrix;
  75607. }
  75608. parentScaleInv.copyFrom(parentScale);
  75609. parentScaleInv.invert();
  75610. lmat.multiplyToRef(parentScale, lmat);
  75611. lmat.multiplyToRef(rmat, lmat);
  75612. lmat.multiplyToRef(parentScaleInv, lmat);
  75613. }
  75614. else {
  75615. if (space == BABYLON.Space.WORLD && mesh) {
  75616. parentScale.copyFrom(mesh.getWorldMatrix());
  75617. parentScaleInv.copyFrom(parentScale);
  75618. parentScaleInv.invert();
  75619. lmat.multiplyToRef(parentScale, lmat);
  75620. lmat.multiplyToRef(rmat, lmat);
  75621. lmat.multiplyToRef(parentScaleInv, lmat);
  75622. }
  75623. else {
  75624. lmat.multiplyToRef(rmat, lmat);
  75625. }
  75626. }
  75627. lmat.m[12] = lx;
  75628. lmat.m[13] = ly;
  75629. lmat.m[14] = lz;
  75630. this.computeAbsoluteTransforms();
  75631. this.markAsDirty();
  75632. };
  75633. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  75634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75635. if (space == BABYLON.Space.WORLD) {
  75636. var scaleMatrix = Bone._tmpMats[2];
  75637. scaleMatrix.copyFrom(this._scaleMatrix);
  75638. rotMatInv.copyFrom(this.getAbsoluteTransform());
  75639. if (mesh) {
  75640. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  75641. var meshScale = Bone._tmpMats[3];
  75642. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  75643. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  75644. }
  75645. rotMatInv.invert();
  75646. scaleMatrix.m[0] *= this._scalingDeterminant;
  75647. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  75648. }
  75649. else {
  75650. rotMatInv.copyFrom(this.getLocalMatrix());
  75651. rotMatInv.invert();
  75652. var scaleMatrix = Bone._tmpMats[2];
  75653. scaleMatrix.copyFrom(this._scaleMatrix);
  75654. if (this._parent) {
  75655. var pscaleMatrix = Bone._tmpMats[3];
  75656. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  75657. pscaleMatrix.invert();
  75658. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  75659. }
  75660. else {
  75661. scaleMatrix.m[0] *= this._scalingDeterminant;
  75662. }
  75663. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  75664. }
  75665. };
  75666. /**
  75667. * Get the scale of the bone
  75668. * @returns the scale of the bone
  75669. */
  75670. Bone.prototype.getScale = function () {
  75671. return this._scaleVector.clone();
  75672. };
  75673. /**
  75674. * Copy the scale of the bone to a vector3.
  75675. * @param result The vector3 to copy the scale to
  75676. */
  75677. Bone.prototype.getScaleToRef = function (result) {
  75678. result.copyFrom(this._scaleVector);
  75679. };
  75680. /**
  75681. * Get the position of the bone in local or world space.
  75682. * @param space The space that the returned position is in.
  75683. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75684. * @returns The position of the bone
  75685. */
  75686. Bone.prototype.getPosition = function (space, mesh) {
  75687. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75688. if (mesh === void 0) { mesh = null; }
  75689. var pos = BABYLON.Vector3.Zero();
  75690. this.getPositionToRef(space, mesh, pos);
  75691. return pos;
  75692. };
  75693. /**
  75694. * Copy the position of the bone to a vector3 in local or world space.
  75695. * @param space The space that the returned position is in.
  75696. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75697. * @param result The vector3 to copy the position to.
  75698. */
  75699. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  75700. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75701. if (space == BABYLON.Space.LOCAL) {
  75702. var lm = this.getLocalMatrix();
  75703. result.x = lm.m[12];
  75704. result.y = lm.m[13];
  75705. result.z = lm.m[14];
  75706. }
  75707. else {
  75708. var wm = null;
  75709. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75710. if (mesh) {
  75711. wm = mesh.getWorldMatrix();
  75712. }
  75713. this._skeleton.computeAbsoluteTransforms();
  75714. var tmat = Bone._tmpMats[0];
  75715. if (mesh && wm) {
  75716. tmat.copyFrom(this.getAbsoluteTransform());
  75717. tmat.multiplyToRef(wm, tmat);
  75718. }
  75719. else {
  75720. tmat = this.getAbsoluteTransform();
  75721. }
  75722. result.x = tmat.m[12];
  75723. result.y = tmat.m[13];
  75724. result.z = tmat.m[14];
  75725. }
  75726. };
  75727. /**
  75728. * Get the absolute position of the bone (world space).
  75729. * @param mesh The mesh that this bone is attached to.
  75730. * @returns The absolute position of the bone
  75731. */
  75732. Bone.prototype.getAbsolutePosition = function (mesh) {
  75733. if (mesh === void 0) { mesh = null; }
  75734. var pos = BABYLON.Vector3.Zero();
  75735. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  75736. return pos;
  75737. };
  75738. /**
  75739. * Copy the absolute position of the bone (world space) to the result param.
  75740. * @param mesh The mesh that this bone is attached to.
  75741. * @param result The vector3 to copy the absolute position to.
  75742. */
  75743. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  75744. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  75745. };
  75746. /**
  75747. * Compute the absolute transforms of this bone and its children.
  75748. */
  75749. Bone.prototype.computeAbsoluteTransforms = function () {
  75750. if (this._parent) {
  75751. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  75752. }
  75753. else {
  75754. this._absoluteTransform.copyFrom(this._localMatrix);
  75755. var poseMatrix = this._skeleton.getPoseMatrix();
  75756. if (poseMatrix) {
  75757. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  75758. }
  75759. }
  75760. var children = this.children;
  75761. var len = children.length;
  75762. for (var i = 0; i < len; i++) {
  75763. children[i].computeAbsoluteTransforms();
  75764. }
  75765. };
  75766. Bone.prototype._syncScaleVector = function () {
  75767. var lm = this.getLocalMatrix();
  75768. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  75769. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  75770. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  75771. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  75772. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  75773. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  75774. this._scaleVector.x = xs * Math.sqrt(xsq);
  75775. this._scaleVector.y = ys * Math.sqrt(ysq);
  75776. this._scaleVector.z = zs * Math.sqrt(zsq);
  75777. if (this._parent) {
  75778. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  75779. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  75780. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  75781. }
  75782. 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);
  75783. };
  75784. /**
  75785. * Get the world direction from an axis that is in the local space of the bone.
  75786. * @param localAxis The local direction that is used to compute the world direction.
  75787. * @param mesh The mesh that this bone is attached to.
  75788. * @returns The world direction
  75789. */
  75790. Bone.prototype.getDirection = function (localAxis, mesh) {
  75791. if (mesh === void 0) { mesh = null; }
  75792. var result = BABYLON.Vector3.Zero();
  75793. this.getDirectionToRef(localAxis, mesh, result);
  75794. return result;
  75795. };
  75796. /**
  75797. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  75798. * @param localAxis The local direction that is used to compute the world direction.
  75799. * @param mesh The mesh that this bone is attached to.
  75800. * @param result The vector3 that the world direction will be copied to.
  75801. */
  75802. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  75803. if (mesh === void 0) { mesh = null; }
  75804. var wm = null;
  75805. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75806. if (mesh) {
  75807. wm = mesh.getWorldMatrix();
  75808. }
  75809. this._skeleton.computeAbsoluteTransforms();
  75810. var mat = Bone._tmpMats[0];
  75811. mat.copyFrom(this.getAbsoluteTransform());
  75812. if (mesh && wm) {
  75813. mat.multiplyToRef(wm, mat);
  75814. }
  75815. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  75816. result.normalize();
  75817. };
  75818. /**
  75819. * Get the euler rotation of the bone in local or world space.
  75820. * @param space The space that the rotation should be in.
  75821. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75822. * @returns The euler rotation
  75823. */
  75824. Bone.prototype.getRotation = function (space, mesh) {
  75825. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75826. if (mesh === void 0) { mesh = null; }
  75827. var result = BABYLON.Vector3.Zero();
  75828. this.getRotationToRef(space, mesh, result);
  75829. return result;
  75830. };
  75831. /**
  75832. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  75833. * @param space The space that the rotation should be in.
  75834. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75835. * @param result The vector3 that the rotation should be copied to.
  75836. */
  75837. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  75838. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75839. if (mesh === void 0) { mesh = null; }
  75840. var quat = Bone._tmpQuat;
  75841. this.getRotationQuaternionToRef(space, mesh, quat);
  75842. quat.toEulerAnglesToRef(result);
  75843. };
  75844. /**
  75845. * Get the quaternion rotation of the bone in either local or world space.
  75846. * @param space The space that the rotation should be in.
  75847. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75848. * @returns The quaternion rotation
  75849. */
  75850. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  75851. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75852. if (mesh === void 0) { mesh = null; }
  75853. var result = BABYLON.Quaternion.Identity();
  75854. this.getRotationQuaternionToRef(space, mesh, result);
  75855. return result;
  75856. };
  75857. /**
  75858. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  75859. * @param space The space that the rotation should be in.
  75860. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75861. * @param result The quaternion that the rotation should be copied to.
  75862. */
  75863. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  75864. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75865. if (mesh === void 0) { mesh = null; }
  75866. if (space == BABYLON.Space.LOCAL) {
  75867. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  75868. }
  75869. else {
  75870. var mat = Bone._tmpMats[0];
  75871. var amat = this.getAbsoluteTransform();
  75872. if (mesh) {
  75873. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  75874. }
  75875. else {
  75876. mat.copyFrom(amat);
  75877. }
  75878. mat.m[0] *= this._scalingDeterminant;
  75879. mat.m[1] *= this._scalingDeterminant;
  75880. mat.m[2] *= this._scalingDeterminant;
  75881. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  75882. }
  75883. };
  75884. /**
  75885. * Get the rotation matrix of the bone in local or world space.
  75886. * @param space The space that the rotation should be in.
  75887. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75888. * @returns The rotation matrix
  75889. */
  75890. Bone.prototype.getRotationMatrix = function (space, mesh) {
  75891. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75892. var result = BABYLON.Matrix.Identity();
  75893. this.getRotationMatrixToRef(space, mesh, result);
  75894. return result;
  75895. };
  75896. /**
  75897. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  75898. * @param space The space that the rotation should be in.
  75899. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75900. * @param result The quaternion that the rotation should be copied to.
  75901. */
  75902. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  75903. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75904. if (space == BABYLON.Space.LOCAL) {
  75905. this.getLocalMatrix().getRotationMatrixToRef(result);
  75906. }
  75907. else {
  75908. var mat = Bone._tmpMats[0];
  75909. var amat = this.getAbsoluteTransform();
  75910. if (mesh) {
  75911. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  75912. }
  75913. else {
  75914. mat.copyFrom(amat);
  75915. }
  75916. mat.m[0] *= this._scalingDeterminant;
  75917. mat.m[1] *= this._scalingDeterminant;
  75918. mat.m[2] *= this._scalingDeterminant;
  75919. mat.getRotationMatrixToRef(result);
  75920. }
  75921. };
  75922. /**
  75923. * Get the world position of a point that is in the local space of the bone.
  75924. * @param position The local position
  75925. * @param mesh The mesh that this bone is attached to.
  75926. * @returns The world position
  75927. */
  75928. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  75929. if (mesh === void 0) { mesh = null; }
  75930. var result = BABYLON.Vector3.Zero();
  75931. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  75932. return result;
  75933. };
  75934. /**
  75935. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  75936. * @param position The local position
  75937. * @param mesh The mesh that this bone is attached to.
  75938. * @param result The vector3 that the world position should be copied to.
  75939. */
  75940. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  75941. if (mesh === void 0) { mesh = null; }
  75942. var wm = null;
  75943. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75944. if (mesh) {
  75945. wm = mesh.getWorldMatrix();
  75946. }
  75947. this._skeleton.computeAbsoluteTransforms();
  75948. var tmat = Bone._tmpMats[0];
  75949. if (mesh && wm) {
  75950. tmat.copyFrom(this.getAbsoluteTransform());
  75951. tmat.multiplyToRef(wm, tmat);
  75952. }
  75953. else {
  75954. tmat = this.getAbsoluteTransform();
  75955. }
  75956. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  75957. };
  75958. /**
  75959. * Get the local position of a point that is in world space.
  75960. * @param position The world position
  75961. * @param mesh The mesh that this bone is attached to.
  75962. * @returns The local position
  75963. */
  75964. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  75965. if (mesh === void 0) { mesh = null; }
  75966. var result = BABYLON.Vector3.Zero();
  75967. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  75968. return result;
  75969. };
  75970. /**
  75971. * Get the local position of a point that is in world space and copy it to the result param.
  75972. * @param position The world position
  75973. * @param mesh The mesh that this bone is attached to.
  75974. * @param result The vector3 that the local position should be copied to.
  75975. */
  75976. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  75977. if (mesh === void 0) { mesh = null; }
  75978. var wm = null;
  75979. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75980. if (mesh) {
  75981. wm = mesh.getWorldMatrix();
  75982. }
  75983. this._skeleton.computeAbsoluteTransforms();
  75984. var tmat = Bone._tmpMats[0];
  75985. tmat.copyFrom(this.getAbsoluteTransform());
  75986. if (mesh && wm) {
  75987. tmat.multiplyToRef(wm, tmat);
  75988. }
  75989. tmat.invert();
  75990. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  75991. };
  75992. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75993. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  75994. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  75995. return Bone;
  75996. }(BABYLON.Node));
  75997. BABYLON.Bone = Bone;
  75998. })(BABYLON || (BABYLON = {}));
  75999. //# sourceMappingURL=babylon.bone.js.map
  76000. "use strict";
  76001. var BABYLON;
  76002. (function (BABYLON) {
  76003. var BoneIKController = /** @class */ (function () {
  76004. function BoneIKController(mesh, bone, options) {
  76005. this.targetPosition = BABYLON.Vector3.Zero();
  76006. this.poleTargetPosition = BABYLON.Vector3.Zero();
  76007. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  76008. this.poleAngle = 0;
  76009. this.slerpAmount = 1;
  76010. this._bone1Quat = BABYLON.Quaternion.Identity();
  76011. this._bone1Mat = BABYLON.Matrix.Identity();
  76012. this._bone2Ang = Math.PI;
  76013. this._maxAngle = Math.PI;
  76014. this._rightHandedSystem = false;
  76015. this._bendAxis = BABYLON.Vector3.Right();
  76016. this._slerping = false;
  76017. this._adjustRoll = 0;
  76018. this._bone2 = bone;
  76019. this._bone1 = bone.getParent();
  76020. if (!this._bone1) {
  76021. return;
  76022. }
  76023. this.mesh = mesh;
  76024. var bonePos = bone.getPosition();
  76025. if (bone.getAbsoluteTransform().determinant() > 0) {
  76026. this._rightHandedSystem = true;
  76027. this._bendAxis.x = 0;
  76028. this._bendAxis.y = 0;
  76029. this._bendAxis.z = -1;
  76030. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  76031. this._adjustRoll = Math.PI * .5;
  76032. this._bendAxis.z = 1;
  76033. }
  76034. }
  76035. if (this._bone1.length) {
  76036. var boneScale1 = this._bone1.getScale();
  76037. var boneScale2 = this._bone2.getScale();
  76038. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  76039. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  76040. }
  76041. else if (this._bone1.children[0]) {
  76042. mesh.computeWorldMatrix(true);
  76043. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  76044. var pos2 = this._bone2.getAbsolutePosition(mesh);
  76045. var pos3 = this._bone1.getAbsolutePosition(mesh);
  76046. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  76047. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  76048. }
  76049. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  76050. this.maxAngle = Math.PI;
  76051. if (options) {
  76052. if (options.targetMesh) {
  76053. this.targetMesh = options.targetMesh;
  76054. this.targetMesh.computeWorldMatrix(true);
  76055. }
  76056. if (options.poleTargetMesh) {
  76057. this.poleTargetMesh = options.poleTargetMesh;
  76058. this.poleTargetMesh.computeWorldMatrix(true);
  76059. }
  76060. else if (options.poleTargetBone) {
  76061. this.poleTargetBone = options.poleTargetBone;
  76062. }
  76063. else if (this._bone1.getParent()) {
  76064. this.poleTargetBone = this._bone1.getParent();
  76065. }
  76066. if (options.poleTargetLocalOffset) {
  76067. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  76068. }
  76069. if (options.poleAngle) {
  76070. this.poleAngle = options.poleAngle;
  76071. }
  76072. if (options.bendAxis) {
  76073. this._bendAxis.copyFrom(options.bendAxis);
  76074. }
  76075. if (options.maxAngle) {
  76076. this.maxAngle = options.maxAngle;
  76077. }
  76078. if (options.slerpAmount) {
  76079. this.slerpAmount = options.slerpAmount;
  76080. }
  76081. }
  76082. }
  76083. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  76084. get: function () {
  76085. return this._maxAngle;
  76086. },
  76087. set: function (value) {
  76088. this._setMaxAngle(value);
  76089. },
  76090. enumerable: true,
  76091. configurable: true
  76092. });
  76093. BoneIKController.prototype._setMaxAngle = function (ang) {
  76094. if (ang < 0) {
  76095. ang = 0;
  76096. }
  76097. if (ang > Math.PI || ang == undefined) {
  76098. ang = Math.PI;
  76099. }
  76100. this._maxAngle = ang;
  76101. var a = this._bone1Length;
  76102. var b = this._bone2Length;
  76103. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  76104. };
  76105. BoneIKController.prototype.update = function () {
  76106. var bone1 = this._bone1;
  76107. if (!bone1) {
  76108. return;
  76109. }
  76110. var target = this.targetPosition;
  76111. var poleTarget = this.poleTargetPosition;
  76112. var mat1 = BoneIKController._tmpMats[0];
  76113. var mat2 = BoneIKController._tmpMats[1];
  76114. if (this.targetMesh) {
  76115. target.copyFrom(this.targetMesh.getAbsolutePosition());
  76116. }
  76117. if (this.poleTargetBone) {
  76118. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  76119. }
  76120. else if (this.poleTargetMesh) {
  76121. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  76122. }
  76123. var bonePos = BoneIKController._tmpVecs[0];
  76124. var zaxis = BoneIKController._tmpVecs[1];
  76125. var xaxis = BoneIKController._tmpVecs[2];
  76126. var yaxis = BoneIKController._tmpVecs[3];
  76127. var upAxis = BoneIKController._tmpVecs[4];
  76128. var _tmpQuat = BoneIKController._tmpQuat;
  76129. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  76130. poleTarget.subtractToRef(bonePos, upAxis);
  76131. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  76132. upAxis.y = 1;
  76133. }
  76134. else {
  76135. upAxis.normalize();
  76136. }
  76137. target.subtractToRef(bonePos, yaxis);
  76138. yaxis.normalize();
  76139. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  76140. zaxis.normalize();
  76141. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  76142. xaxis.normalize();
  76143. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  76144. var a = this._bone1Length;
  76145. var b = this._bone2Length;
  76146. var c = BABYLON.Vector3.Distance(bonePos, target);
  76147. if (this._maxReach > 0) {
  76148. c = Math.min(this._maxReach, c);
  76149. }
  76150. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  76151. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  76152. if (acosa > 1) {
  76153. acosa = 1;
  76154. }
  76155. if (acosb > 1) {
  76156. acosb = 1;
  76157. }
  76158. if (acosa < -1) {
  76159. acosa = -1;
  76160. }
  76161. if (acosb < -1) {
  76162. acosb = -1;
  76163. }
  76164. var angA = Math.acos(acosa);
  76165. var angB = Math.acos(acosb);
  76166. var angC = -angA - angB;
  76167. if (this._rightHandedSystem) {
  76168. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  76169. mat2.multiplyToRef(mat1, mat1);
  76170. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  76171. mat2.multiplyToRef(mat1, mat1);
  76172. }
  76173. else {
  76174. var _tmpVec = BoneIKController._tmpVecs[5];
  76175. _tmpVec.copyFrom(this._bendAxis);
  76176. _tmpVec.x *= -1;
  76177. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  76178. mat2.multiplyToRef(mat1, mat1);
  76179. }
  76180. if (this.poleAngle) {
  76181. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  76182. mat1.multiplyToRef(mat2, mat1);
  76183. }
  76184. if (this._bone1) {
  76185. if (this.slerpAmount < 1) {
  76186. if (!this._slerping) {
  76187. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  76188. }
  76189. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  76190. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  76191. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  76192. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  76193. this._slerping = true;
  76194. }
  76195. else {
  76196. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  76197. this._bone1Mat.copyFrom(mat1);
  76198. this._slerping = false;
  76199. }
  76200. }
  76201. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  76202. this._bone2Ang = angC;
  76203. };
  76204. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76205. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  76206. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76207. return BoneIKController;
  76208. }());
  76209. BABYLON.BoneIKController = BoneIKController;
  76210. })(BABYLON || (BABYLON = {}));
  76211. //# sourceMappingURL=babylon.boneIKController.js.map
  76212. "use strict";
  76213. var BABYLON;
  76214. (function (BABYLON) {
  76215. var BoneLookController = /** @class */ (function () {
  76216. /**
  76217. * Create a BoneLookController
  76218. * @param mesh the mesh that the bone belongs to
  76219. * @param bone the bone that will be looking to the target
  76220. * @param target the target Vector3 to look at
  76221. * @param settings optional settings:
  76222. * - maxYaw: the maximum angle the bone will yaw to
  76223. * - minYaw: the minimum angle the bone will yaw to
  76224. * - maxPitch: the maximum angle the bone will pitch to
  76225. * - minPitch: the minimum angle the bone will yaw to
  76226. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  76227. * - upAxis: the up axis of the coordinate system
  76228. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76229. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  76230. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  76231. * - adjustYaw: used to make an adjustment to the yaw of the bone
  76232. * - adjustPitch: used to make an adjustment to the pitch of the bone
  76233. * - adjustRoll: used to make an adjustment to the roll of the bone
  76234. **/
  76235. function BoneLookController(mesh, bone, target, options) {
  76236. /**
  76237. * The up axis of the coordinate system that is used when the bone is rotated.
  76238. */
  76239. this.upAxis = BABYLON.Vector3.Up();
  76240. /**
  76241. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76242. */
  76243. this.upAxisSpace = BABYLON.Space.LOCAL;
  76244. /**
  76245. * Used to make an adjustment to the yaw of the bone.
  76246. */
  76247. this.adjustYaw = 0;
  76248. /**
  76249. * Used to make an adjustment to the pitch of the bone.
  76250. */
  76251. this.adjustPitch = 0;
  76252. /**
  76253. * Used to make an adjustment to the roll of the bone.
  76254. */
  76255. this.adjustRoll = 0;
  76256. /**
  76257. * 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).
  76258. */
  76259. this.slerpAmount = 1;
  76260. this._boneQuat = BABYLON.Quaternion.Identity();
  76261. this._slerping = false;
  76262. this._firstFrameSkipped = false;
  76263. this._fowardAxis = BABYLON.Vector3.Forward();
  76264. this.mesh = mesh;
  76265. this.bone = bone;
  76266. this.target = target;
  76267. if (options) {
  76268. if (options.adjustYaw) {
  76269. this.adjustYaw = options.adjustYaw;
  76270. }
  76271. if (options.adjustPitch) {
  76272. this.adjustPitch = options.adjustPitch;
  76273. }
  76274. if (options.adjustRoll) {
  76275. this.adjustRoll = options.adjustRoll;
  76276. }
  76277. if (options.maxYaw != null) {
  76278. this.maxYaw = options.maxYaw;
  76279. }
  76280. else {
  76281. this.maxYaw = Math.PI;
  76282. }
  76283. if (options.minYaw != null) {
  76284. this.minYaw = options.minYaw;
  76285. }
  76286. else {
  76287. this.minYaw = -Math.PI;
  76288. }
  76289. if (options.maxPitch != null) {
  76290. this.maxPitch = options.maxPitch;
  76291. }
  76292. else {
  76293. this.maxPitch = Math.PI;
  76294. }
  76295. if (options.minPitch != null) {
  76296. this.minPitch = options.minPitch;
  76297. }
  76298. else {
  76299. this.minPitch = -Math.PI;
  76300. }
  76301. if (options.slerpAmount != null) {
  76302. this.slerpAmount = options.slerpAmount;
  76303. }
  76304. if (options.upAxis != null) {
  76305. this.upAxis = options.upAxis;
  76306. }
  76307. if (options.upAxisSpace != null) {
  76308. this.upAxisSpace = options.upAxisSpace;
  76309. }
  76310. if (options.yawAxis != null || options.pitchAxis != null) {
  76311. var newYawAxis = BABYLON.Axis.Y;
  76312. var newPitchAxis = BABYLON.Axis.X;
  76313. if (options.yawAxis != null) {
  76314. newYawAxis = options.yawAxis.clone();
  76315. newYawAxis.normalize();
  76316. }
  76317. if (options.pitchAxis != null) {
  76318. newPitchAxis = options.pitchAxis.clone();
  76319. newPitchAxis.normalize();
  76320. }
  76321. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  76322. this._transformYawPitch = BABYLON.Matrix.Identity();
  76323. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  76324. this._transformYawPitchInv = this._transformYawPitch.clone();
  76325. this._transformYawPitch.invert();
  76326. }
  76327. }
  76328. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  76329. this.upAxisSpace = BABYLON.Space.LOCAL;
  76330. }
  76331. }
  76332. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  76333. /**
  76334. * Get/set the minimum yaw angle that the bone can look to.
  76335. */
  76336. get: function () {
  76337. return this._minYaw;
  76338. },
  76339. set: function (value) {
  76340. this._minYaw = value;
  76341. this._minYawSin = Math.sin(value);
  76342. this._minYawCos = Math.cos(value);
  76343. if (this._maxYaw != null) {
  76344. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76345. this._yawRange = this._maxYaw - this._minYaw;
  76346. }
  76347. },
  76348. enumerable: true,
  76349. configurable: true
  76350. });
  76351. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  76352. /**
  76353. * Get/set the maximum yaw angle that the bone can look to.
  76354. */
  76355. get: function () {
  76356. return this._maxYaw;
  76357. },
  76358. set: function (value) {
  76359. this._maxYaw = value;
  76360. this._maxYawSin = Math.sin(value);
  76361. this._maxYawCos = Math.cos(value);
  76362. if (this._minYaw != null) {
  76363. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76364. this._yawRange = this._maxYaw - this._minYaw;
  76365. }
  76366. },
  76367. enumerable: true,
  76368. configurable: true
  76369. });
  76370. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  76371. /**
  76372. * Get/set the minimum pitch angle that the bone can look to.
  76373. */
  76374. get: function () {
  76375. return this._minPitch;
  76376. },
  76377. set: function (value) {
  76378. this._minPitch = value;
  76379. this._minPitchTan = Math.tan(value);
  76380. },
  76381. enumerable: true,
  76382. configurable: true
  76383. });
  76384. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  76385. /**
  76386. * Get/set the maximum pitch angle that the bone can look to.
  76387. */
  76388. get: function () {
  76389. return this._maxPitch;
  76390. },
  76391. set: function (value) {
  76392. this._maxPitch = value;
  76393. this._maxPitchTan = Math.tan(value);
  76394. },
  76395. enumerable: true,
  76396. configurable: true
  76397. });
  76398. /**
  76399. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  76400. */
  76401. BoneLookController.prototype.update = function () {
  76402. //skip the first frame when slerping so that the mesh rotation is correct
  76403. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  76404. this._firstFrameSkipped = true;
  76405. return;
  76406. }
  76407. var bone = this.bone;
  76408. var bonePos = BoneLookController._tmpVecs[0];
  76409. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  76410. var target = this.target;
  76411. var _tmpMat1 = BoneLookController._tmpMats[0];
  76412. var _tmpMat2 = BoneLookController._tmpMats[1];
  76413. var mesh = this.mesh;
  76414. var parentBone = bone.getParent();
  76415. var upAxis = BoneLookController._tmpVecs[1];
  76416. upAxis.copyFrom(this.upAxis);
  76417. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  76418. if (this._transformYawPitch) {
  76419. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  76420. }
  76421. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  76422. }
  76423. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  76424. mesh.getDirectionToRef(upAxis, upAxis);
  76425. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  76426. upAxis.normalize();
  76427. }
  76428. }
  76429. var checkYaw = false;
  76430. var checkPitch = false;
  76431. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  76432. checkYaw = true;
  76433. }
  76434. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  76435. checkPitch = true;
  76436. }
  76437. if (checkYaw || checkPitch) {
  76438. var spaceMat = BoneLookController._tmpMats[2];
  76439. var spaceMatInv = BoneLookController._tmpMats[3];
  76440. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  76441. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  76442. }
  76443. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  76444. spaceMat.copyFrom(mesh.getWorldMatrix());
  76445. }
  76446. else {
  76447. var forwardAxis = BoneLookController._tmpVecs[2];
  76448. forwardAxis.copyFrom(this._fowardAxis);
  76449. if (this._transformYawPitch) {
  76450. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  76451. }
  76452. if (parentBone) {
  76453. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  76454. }
  76455. else {
  76456. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  76457. }
  76458. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  76459. rightAxis.normalize();
  76460. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  76461. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  76462. }
  76463. spaceMat.invertToRef(spaceMatInv);
  76464. var xzlen = null;
  76465. if (checkPitch) {
  76466. var localTarget = BoneLookController._tmpVecs[3];
  76467. target.subtractToRef(bonePos, localTarget);
  76468. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  76469. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76470. var pitch = Math.atan2(localTarget.y, xzlen);
  76471. var newPitch = pitch;
  76472. if (pitch > this._maxPitch) {
  76473. localTarget.y = this._maxPitchTan * xzlen;
  76474. newPitch = this._maxPitch;
  76475. }
  76476. else if (pitch < this._minPitch) {
  76477. localTarget.y = this._minPitchTan * xzlen;
  76478. newPitch = this._minPitch;
  76479. }
  76480. if (pitch != newPitch) {
  76481. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  76482. localTarget.addInPlace(bonePos);
  76483. target = localTarget;
  76484. }
  76485. }
  76486. if (checkYaw) {
  76487. var localTarget = BoneLookController._tmpVecs[4];
  76488. target.subtractToRef(bonePos, localTarget);
  76489. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  76490. var yaw = Math.atan2(localTarget.x, localTarget.z);
  76491. var newYaw = yaw;
  76492. if (yaw > this._maxYaw || yaw < this._minYaw) {
  76493. if (xzlen == null) {
  76494. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76495. }
  76496. if (this._yawRange > Math.PI) {
  76497. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  76498. localTarget.z = this._maxYawCos * xzlen;
  76499. localTarget.x = this._maxYawSin * xzlen;
  76500. newYaw = this._maxYaw;
  76501. }
  76502. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  76503. localTarget.z = this._minYawCos * xzlen;
  76504. localTarget.x = this._minYawSin * xzlen;
  76505. newYaw = this._minYaw;
  76506. }
  76507. }
  76508. else {
  76509. if (yaw > this._maxYaw) {
  76510. localTarget.z = this._maxYawCos * xzlen;
  76511. localTarget.x = this._maxYawSin * xzlen;
  76512. newYaw = this._maxYaw;
  76513. }
  76514. else if (yaw < this._minYaw) {
  76515. localTarget.z = this._minYawCos * xzlen;
  76516. localTarget.x = this._minYawSin * xzlen;
  76517. newYaw = this._minYaw;
  76518. }
  76519. }
  76520. }
  76521. if (this._slerping && this._yawRange > Math.PI) {
  76522. //are we going to be crossing into the min/max region?
  76523. var boneFwd = BoneLookController._tmpVecs[8];
  76524. boneFwd.copyFrom(BABYLON.Axis.Z);
  76525. if (this._transformYawPitch) {
  76526. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  76527. }
  76528. var boneRotMat = BoneLookController._tmpMats[4];
  76529. this._boneQuat.toRotationMatrix(boneRotMat);
  76530. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  76531. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  76532. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  76533. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  76534. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  76535. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  76536. if (angBtwTar > angBtwMidYaw) {
  76537. if (xzlen == null) {
  76538. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76539. }
  76540. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  76541. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  76542. if (angBtwMin < angBtwMax) {
  76543. newYaw = boneYaw + Math.PI * .75;
  76544. localTarget.z = Math.cos(newYaw) * xzlen;
  76545. localTarget.x = Math.sin(newYaw) * xzlen;
  76546. }
  76547. else {
  76548. newYaw = boneYaw - Math.PI * .75;
  76549. localTarget.z = Math.cos(newYaw) * xzlen;
  76550. localTarget.x = Math.sin(newYaw) * xzlen;
  76551. }
  76552. }
  76553. }
  76554. if (yaw != newYaw) {
  76555. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  76556. localTarget.addInPlace(bonePos);
  76557. target = localTarget;
  76558. }
  76559. }
  76560. }
  76561. var zaxis = BoneLookController._tmpVecs[5];
  76562. var xaxis = BoneLookController._tmpVecs[6];
  76563. var yaxis = BoneLookController._tmpVecs[7];
  76564. var _tmpQuat = BoneLookController._tmpQuat;
  76565. target.subtractToRef(bonePos, zaxis);
  76566. zaxis.normalize();
  76567. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  76568. xaxis.normalize();
  76569. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  76570. yaxis.normalize();
  76571. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  76572. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  76573. return;
  76574. }
  76575. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  76576. return;
  76577. }
  76578. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  76579. return;
  76580. }
  76581. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  76582. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  76583. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  76584. }
  76585. if (this.slerpAmount < 1) {
  76586. if (!this._slerping) {
  76587. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  76588. }
  76589. if (this._transformYawPitch) {
  76590. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  76591. }
  76592. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  76593. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  76594. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  76595. this._slerping = true;
  76596. }
  76597. else {
  76598. if (this._transformYawPitch) {
  76599. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  76600. }
  76601. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  76602. this._slerping = false;
  76603. }
  76604. };
  76605. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  76606. var angDiff = ang2 - ang1;
  76607. angDiff %= Math.PI * 2;
  76608. if (angDiff > Math.PI) {
  76609. angDiff -= Math.PI * 2;
  76610. }
  76611. else if (angDiff < -Math.PI) {
  76612. angDiff += Math.PI * 2;
  76613. }
  76614. return angDiff;
  76615. };
  76616. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  76617. ang1 %= (2 * Math.PI);
  76618. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  76619. ang2 %= (2 * Math.PI);
  76620. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  76621. var ab = 0;
  76622. if (ang1 < ang2) {
  76623. ab = ang2 - ang1;
  76624. }
  76625. else {
  76626. ab = ang1 - ang2;
  76627. }
  76628. if (ab > Math.PI) {
  76629. ab = Math.PI * 2 - ab;
  76630. }
  76631. return ab;
  76632. };
  76633. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  76634. ang %= (2 * Math.PI);
  76635. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  76636. ang1 %= (2 * Math.PI);
  76637. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  76638. ang2 %= (2 * Math.PI);
  76639. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  76640. if (ang1 < ang2) {
  76641. if (ang > ang1 && ang < ang2) {
  76642. return true;
  76643. }
  76644. }
  76645. else {
  76646. if (ang > ang2 && ang < ang1) {
  76647. return true;
  76648. }
  76649. }
  76650. return false;
  76651. };
  76652. 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()];
  76653. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  76654. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76655. return BoneLookController;
  76656. }());
  76657. BABYLON.BoneLookController = BoneLookController;
  76658. })(BABYLON || (BABYLON = {}));
  76659. //# sourceMappingURL=babylon.boneLookController.js.map
  76660. "use strict";
  76661. var BABYLON;
  76662. (function (BABYLON) {
  76663. var Skeleton = /** @class */ (function () {
  76664. function Skeleton(name, id, scene) {
  76665. this.name = name;
  76666. this.id = id;
  76667. this.bones = new Array();
  76668. this.needInitialSkinMatrix = false;
  76669. this._isDirty = true;
  76670. this._meshesWithPoseMatrix = new Array();
  76671. this._identity = BABYLON.Matrix.Identity();
  76672. this._ranges = {};
  76673. this._lastAbsoluteTransformsUpdateId = -1;
  76674. /**
  76675. * Specifies if the skeleton should be serialized.
  76676. */
  76677. this.doNotSerialize = false;
  76678. // Events
  76679. /**
  76680. * An event triggered before computing the skeleton's matrices
  76681. */
  76682. this.onBeforeComputeObservable = new BABYLON.Observable();
  76683. this.bones = [];
  76684. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76685. scene.skeletons.push(this);
  76686. //make sure it will recalculate the matrix next time prepare is called.
  76687. this._isDirty = true;
  76688. }
  76689. // Members
  76690. Skeleton.prototype.getTransformMatrices = function (mesh) {
  76691. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  76692. return mesh._bonesTransformMatrices;
  76693. }
  76694. if (!this._transformMatrices) {
  76695. this.prepare();
  76696. }
  76697. return this._transformMatrices;
  76698. };
  76699. Skeleton.prototype.getScene = function () {
  76700. return this._scene;
  76701. };
  76702. // Methods
  76703. /**
  76704. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  76705. */
  76706. Skeleton.prototype.toString = function (fullDetails) {
  76707. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  76708. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  76709. if (fullDetails) {
  76710. ret += ", Ranges: {";
  76711. var first = true;
  76712. for (var name_1 in this._ranges) {
  76713. if (first) {
  76714. ret += ", ";
  76715. first = false;
  76716. }
  76717. ret += name_1;
  76718. }
  76719. ret += "}";
  76720. }
  76721. return ret;
  76722. };
  76723. /**
  76724. * Get bone's index searching by name
  76725. * @param {string} name is bone's name to search for
  76726. * @return {number} Indice of the bone. Returns -1 if not found
  76727. */
  76728. Skeleton.prototype.getBoneIndexByName = function (name) {
  76729. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  76730. if (this.bones[boneIndex].name === name) {
  76731. return boneIndex;
  76732. }
  76733. }
  76734. return -1;
  76735. };
  76736. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  76737. // check name not already in use
  76738. if (!this._ranges[name]) {
  76739. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  76740. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76741. if (this.bones[i].animations[0]) {
  76742. this.bones[i].animations[0].createRange(name, from, to);
  76743. }
  76744. }
  76745. }
  76746. };
  76747. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  76748. if (deleteFrames === void 0) { deleteFrames = true; }
  76749. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76750. if (this.bones[i].animations[0]) {
  76751. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  76752. }
  76753. }
  76754. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  76755. };
  76756. Skeleton.prototype.getAnimationRange = function (name) {
  76757. return this._ranges[name];
  76758. };
  76759. /**
  76760. * Returns as an Array, all AnimationRanges defined on this skeleton
  76761. */
  76762. Skeleton.prototype.getAnimationRanges = function () {
  76763. var animationRanges = [];
  76764. var name;
  76765. var i = 0;
  76766. for (name in this._ranges) {
  76767. animationRanges[i] = this._ranges[name];
  76768. i++;
  76769. }
  76770. return animationRanges;
  76771. };
  76772. /**
  76773. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  76774. */
  76775. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  76776. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76777. if (this._ranges[name] || !source.getAnimationRange(name)) {
  76778. return false;
  76779. }
  76780. var ret = true;
  76781. var frameOffset = this._getHighestAnimationFrame() + 1;
  76782. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  76783. var boneDict = {};
  76784. var sourceBones = source.bones;
  76785. var nBones;
  76786. var i;
  76787. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  76788. boneDict[sourceBones[i].name] = sourceBones[i];
  76789. }
  76790. if (this.bones.length !== sourceBones.length) {
  76791. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  76792. ret = false;
  76793. }
  76794. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  76795. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  76796. var boneName = this.bones[i].name;
  76797. var sourceBone = boneDict[boneName];
  76798. if (sourceBone) {
  76799. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  76800. }
  76801. else {
  76802. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  76803. ret = false;
  76804. }
  76805. }
  76806. // do not call createAnimationRange(), since it also is done to bones, which was already done
  76807. var range = source.getAnimationRange(name);
  76808. if (range) {
  76809. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  76810. }
  76811. return ret;
  76812. };
  76813. Skeleton.prototype.returnToRest = function () {
  76814. for (var index = 0; index < this.bones.length; index++) {
  76815. this.bones[index].returnToRest();
  76816. }
  76817. };
  76818. Skeleton.prototype._getHighestAnimationFrame = function () {
  76819. var ret = 0;
  76820. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  76821. if (this.bones[i].animations[0]) {
  76822. var highest = this.bones[i].animations[0].getHighestFrame();
  76823. if (ret < highest) {
  76824. ret = highest;
  76825. }
  76826. }
  76827. }
  76828. return ret;
  76829. };
  76830. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  76831. var range = this.getAnimationRange(name);
  76832. if (!range) {
  76833. return null;
  76834. }
  76835. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  76836. };
  76837. Skeleton.prototype._markAsDirty = function () {
  76838. this._isDirty = true;
  76839. };
  76840. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  76841. this._meshesWithPoseMatrix.push(mesh);
  76842. };
  76843. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  76844. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  76845. if (index > -1) {
  76846. this._meshesWithPoseMatrix.splice(index, 1);
  76847. }
  76848. };
  76849. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  76850. this.onBeforeComputeObservable.notifyObservers(this);
  76851. for (var index = 0; index < this.bones.length; index++) {
  76852. var bone = this.bones[index];
  76853. var parentBone = bone.getParent();
  76854. if (parentBone) {
  76855. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  76856. }
  76857. else {
  76858. if (initialSkinMatrix) {
  76859. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  76860. }
  76861. else {
  76862. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  76863. }
  76864. }
  76865. if (bone._index !== -1) {
  76866. var mappedIndex = bone._index === null ? index : bone._index;
  76867. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  76868. }
  76869. }
  76870. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  76871. };
  76872. Skeleton.prototype.prepare = function () {
  76873. if (!this._isDirty) {
  76874. return;
  76875. }
  76876. if (this.needInitialSkinMatrix) {
  76877. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  76878. var mesh = this._meshesWithPoseMatrix[index];
  76879. var poseMatrix = mesh.getPoseMatrix();
  76880. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  76881. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  76882. }
  76883. if (this._synchronizedWithMesh !== mesh) {
  76884. this._synchronizedWithMesh = mesh;
  76885. // Prepare bones
  76886. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  76887. var bone = this.bones[boneIndex];
  76888. if (!bone.getParent()) {
  76889. var matrix = bone.getBaseMatrix();
  76890. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  76891. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  76892. }
  76893. }
  76894. }
  76895. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  76896. }
  76897. }
  76898. else {
  76899. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  76900. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  76901. }
  76902. this._computeTransformMatrices(this._transformMatrices, null);
  76903. }
  76904. this._isDirty = false;
  76905. this._scene._activeBones.addCount(this.bones.length, false);
  76906. };
  76907. Skeleton.prototype.getAnimatables = function () {
  76908. if (!this._animatables || this._animatables.length !== this.bones.length) {
  76909. this._animatables = [];
  76910. for (var index = 0; index < this.bones.length; index++) {
  76911. this._animatables.push(this.bones[index]);
  76912. }
  76913. }
  76914. return this._animatables;
  76915. };
  76916. Skeleton.prototype.clone = function (name, id) {
  76917. var result = new Skeleton(name, id || name, this._scene);
  76918. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  76919. for (var index = 0; index < this.bones.length; index++) {
  76920. var source = this.bones[index];
  76921. var parentBone = null;
  76922. var parent_1 = source.getParent();
  76923. if (parent_1) {
  76924. var parentIndex = this.bones.indexOf(parent_1);
  76925. parentBone = result.bones[parentIndex];
  76926. }
  76927. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  76928. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  76929. }
  76930. if (this._ranges) {
  76931. result._ranges = {};
  76932. for (var rangeName in this._ranges) {
  76933. var range = this._ranges[rangeName];
  76934. if (range) {
  76935. result._ranges[rangeName] = range.clone();
  76936. }
  76937. }
  76938. }
  76939. this._isDirty = true;
  76940. return result;
  76941. };
  76942. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  76943. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  76944. this.bones.forEach(function (bone) {
  76945. bone.animations.forEach(function (animation) {
  76946. animation.enableBlending = true;
  76947. animation.blendingSpeed = blendingSpeed;
  76948. });
  76949. });
  76950. };
  76951. Skeleton.prototype.dispose = function () {
  76952. this._meshesWithPoseMatrix = [];
  76953. // Animations
  76954. this.getScene().stopAnimation(this);
  76955. // Remove from scene
  76956. this.getScene().removeSkeleton(this);
  76957. };
  76958. Skeleton.prototype.serialize = function () {
  76959. var serializationObject = {};
  76960. serializationObject.name = this.name;
  76961. serializationObject.id = this.id;
  76962. if (this.dimensionsAtRest) {
  76963. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  76964. }
  76965. serializationObject.bones = [];
  76966. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  76967. for (var index = 0; index < this.bones.length; index++) {
  76968. var bone = this.bones[index];
  76969. var parent_2 = bone.getParent();
  76970. var serializedBone = {
  76971. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  76972. name: bone.name,
  76973. matrix: bone.getBaseMatrix().toArray(),
  76974. rest: bone.getRestPose().toArray()
  76975. };
  76976. serializationObject.bones.push(serializedBone);
  76977. if (bone.length) {
  76978. serializedBone.length = bone.length;
  76979. }
  76980. if (bone.animations && bone.animations.length > 0) {
  76981. serializedBone.animation = bone.animations[0].serialize();
  76982. }
  76983. serializationObject.ranges = [];
  76984. for (var name in this._ranges) {
  76985. var source = this._ranges[name];
  76986. if (!source) {
  76987. continue;
  76988. }
  76989. var range = {};
  76990. range.name = name;
  76991. range.from = source.from;
  76992. range.to = source.to;
  76993. serializationObject.ranges.push(range);
  76994. }
  76995. }
  76996. return serializationObject;
  76997. };
  76998. Skeleton.Parse = function (parsedSkeleton, scene) {
  76999. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  77000. if (parsedSkeleton.dimensionsAtRest) {
  77001. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  77002. }
  77003. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  77004. var index;
  77005. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  77006. var parsedBone = parsedSkeleton.bones[index];
  77007. var parentBone = null;
  77008. if (parsedBone.parentBoneIndex > -1) {
  77009. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  77010. }
  77011. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  77012. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  77013. if (parsedBone.length) {
  77014. bone.length = parsedBone.length;
  77015. }
  77016. if (parsedBone.animation) {
  77017. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  77018. }
  77019. }
  77020. // placed after bones, so createAnimationRange can cascade down
  77021. if (parsedSkeleton.ranges) {
  77022. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  77023. var data = parsedSkeleton.ranges[index];
  77024. skeleton.createAnimationRange(data.name, data.from, data.to);
  77025. }
  77026. }
  77027. return skeleton;
  77028. };
  77029. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  77030. if (forceUpdate === void 0) { forceUpdate = false; }
  77031. var renderId = this._scene.getRenderId();
  77032. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  77033. this.bones[0].computeAbsoluteTransforms();
  77034. this._lastAbsoluteTransformsUpdateId = renderId;
  77035. }
  77036. };
  77037. Skeleton.prototype.getPoseMatrix = function () {
  77038. var poseMatrix = null;
  77039. if (this._meshesWithPoseMatrix.length > 0) {
  77040. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  77041. }
  77042. return poseMatrix;
  77043. };
  77044. Skeleton.prototype.sortBones = function () {
  77045. var bones = new Array();
  77046. var visited = new Array(this.bones.length);
  77047. for (var index = 0; index < this.bones.length; index++) {
  77048. this._sortBones(index, bones, visited);
  77049. }
  77050. this.bones = bones;
  77051. };
  77052. Skeleton.prototype._sortBones = function (index, bones, visited) {
  77053. if (visited[index]) {
  77054. return;
  77055. }
  77056. visited[index] = true;
  77057. var bone = this.bones[index];
  77058. if (bone._index === undefined) {
  77059. bone._index = index;
  77060. }
  77061. var parentBone = bone.getParent();
  77062. if (parentBone) {
  77063. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  77064. }
  77065. bones.push(bone);
  77066. };
  77067. return Skeleton;
  77068. }());
  77069. BABYLON.Skeleton = Skeleton;
  77070. })(BABYLON || (BABYLON = {}));
  77071. //# sourceMappingURL=babylon.skeleton.js.map
  77072. "use strict";
  77073. var BABYLON;
  77074. (function (BABYLON) {
  77075. var SphericalPolynomial = /** @class */ (function () {
  77076. function SphericalPolynomial() {
  77077. this.x = BABYLON.Vector3.Zero();
  77078. this.y = BABYLON.Vector3.Zero();
  77079. this.z = BABYLON.Vector3.Zero();
  77080. this.xx = BABYLON.Vector3.Zero();
  77081. this.yy = BABYLON.Vector3.Zero();
  77082. this.zz = BABYLON.Vector3.Zero();
  77083. this.xy = BABYLON.Vector3.Zero();
  77084. this.yz = BABYLON.Vector3.Zero();
  77085. this.zx = BABYLON.Vector3.Zero();
  77086. }
  77087. SphericalPolynomial.prototype.addAmbient = function (color) {
  77088. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77089. this.xx = this.xx.add(colorVector);
  77090. this.yy = this.yy.add(colorVector);
  77091. this.zz = this.zz.add(colorVector);
  77092. };
  77093. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  77094. var result = new SphericalPolynomial();
  77095. result.x = harmonics.L11.scale(1.02333);
  77096. result.y = harmonics.L1_1.scale(1.02333);
  77097. result.z = harmonics.L10.scale(1.02333);
  77098. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  77099. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  77100. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  77101. result.yz = harmonics.L2_1.scale(0.858086);
  77102. result.zx = harmonics.L21.scale(0.858086);
  77103. result.xy = harmonics.L2_2.scale(0.858086);
  77104. result.scale(1.0 / Math.PI);
  77105. return result;
  77106. };
  77107. SphericalPolynomial.prototype.scale = function (scale) {
  77108. this.x = this.x.scale(scale);
  77109. this.y = this.y.scale(scale);
  77110. this.z = this.z.scale(scale);
  77111. this.xx = this.xx.scale(scale);
  77112. this.yy = this.yy.scale(scale);
  77113. this.zz = this.zz.scale(scale);
  77114. this.yz = this.yz.scale(scale);
  77115. this.zx = this.zx.scale(scale);
  77116. this.xy = this.xy.scale(scale);
  77117. };
  77118. return SphericalPolynomial;
  77119. }());
  77120. BABYLON.SphericalPolynomial = SphericalPolynomial;
  77121. var SphericalHarmonics = /** @class */ (function () {
  77122. function SphericalHarmonics() {
  77123. this.L00 = BABYLON.Vector3.Zero();
  77124. this.L1_1 = BABYLON.Vector3.Zero();
  77125. this.L10 = BABYLON.Vector3.Zero();
  77126. this.L11 = BABYLON.Vector3.Zero();
  77127. this.L2_2 = BABYLON.Vector3.Zero();
  77128. this.L2_1 = BABYLON.Vector3.Zero();
  77129. this.L20 = BABYLON.Vector3.Zero();
  77130. this.L21 = BABYLON.Vector3.Zero();
  77131. this.L22 = BABYLON.Vector3.Zero();
  77132. }
  77133. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  77134. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77135. var c = colorVector.scale(deltaSolidAngle);
  77136. this.L00 = this.L00.add(c.scale(0.282095));
  77137. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  77138. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  77139. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  77140. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  77141. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  77142. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  77143. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  77144. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  77145. };
  77146. SphericalHarmonics.prototype.scale = function (scale) {
  77147. this.L00 = this.L00.scale(scale);
  77148. this.L1_1 = this.L1_1.scale(scale);
  77149. this.L10 = this.L10.scale(scale);
  77150. this.L11 = this.L11.scale(scale);
  77151. this.L2_2 = this.L2_2.scale(scale);
  77152. this.L2_1 = this.L2_1.scale(scale);
  77153. this.L20 = this.L20.scale(scale);
  77154. this.L21 = this.L21.scale(scale);
  77155. this.L22 = this.L22.scale(scale);
  77156. };
  77157. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  77158. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  77159. //
  77160. // E_lm = A_l * L_lm
  77161. //
  77162. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  77163. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  77164. // the scaling factors are given in equation 9.
  77165. // Constant (Band 0)
  77166. this.L00 = this.L00.scale(3.141593);
  77167. // Linear (Band 1)
  77168. this.L1_1 = this.L1_1.scale(2.094395);
  77169. this.L10 = this.L10.scale(2.094395);
  77170. this.L11 = this.L11.scale(2.094395);
  77171. // Quadratic (Band 2)
  77172. this.L2_2 = this.L2_2.scale(0.785398);
  77173. this.L2_1 = this.L2_1.scale(0.785398);
  77174. this.L20 = this.L20.scale(0.785398);
  77175. this.L21 = this.L21.scale(0.785398);
  77176. this.L22 = this.L22.scale(0.785398);
  77177. };
  77178. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  77179. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  77180. // L = (1/pi) * E * rho
  77181. //
  77182. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  77183. this.scale(1.0 / Math.PI);
  77184. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  77185. // (The pixel shader must apply albedo after texture fetches, etc).
  77186. };
  77187. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  77188. var result = new SphericalHarmonics();
  77189. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  77190. result.L1_1 = polynomial.y.scale(0.977204);
  77191. result.L10 = polynomial.z.scale(0.977204);
  77192. result.L11 = polynomial.x.scale(0.977204);
  77193. result.L2_2 = polynomial.xy.scale(1.16538);
  77194. result.L2_1 = polynomial.yz.scale(1.16538);
  77195. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  77196. result.L21 = polynomial.zx.scale(1.16538);
  77197. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  77198. result.scale(Math.PI);
  77199. return result;
  77200. };
  77201. return SphericalHarmonics;
  77202. }());
  77203. BABYLON.SphericalHarmonics = SphericalHarmonics;
  77204. })(BABYLON || (BABYLON = {}));
  77205. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  77206. "use strict";
  77207. var BABYLON;
  77208. (function (BABYLON) {
  77209. var FileFaceOrientation = /** @class */ (function () {
  77210. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  77211. this.name = name;
  77212. this.worldAxisForNormal = worldAxisForNormal;
  77213. this.worldAxisForFileX = worldAxisForFileX;
  77214. this.worldAxisForFileY = worldAxisForFileY;
  77215. }
  77216. return FileFaceOrientation;
  77217. }());
  77218. ;
  77219. /**
  77220. * Helper class dealing with the extraction of spherical polynomial dataArray
  77221. * from a cube map.
  77222. */
  77223. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  77224. function CubeMapToSphericalPolynomialTools() {
  77225. }
  77226. /**
  77227. * Converts a texture to the according Spherical Polynomial data.
  77228. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77229. *
  77230. * @param texture The texture to extract the information from.
  77231. * @return The Spherical Polynomial data.
  77232. */
  77233. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  77234. if (!texture.isCube) {
  77235. // Only supports cube Textures currently.
  77236. return null;
  77237. }
  77238. var size = texture.getSize().width;
  77239. var right = texture.readPixels(0);
  77240. var left = texture.readPixels(1);
  77241. var up;
  77242. var down;
  77243. if (texture.isRenderTarget) {
  77244. up = texture.readPixels(3);
  77245. down = texture.readPixels(2);
  77246. }
  77247. else {
  77248. up = texture.readPixels(2);
  77249. down = texture.readPixels(3);
  77250. }
  77251. var front = texture.readPixels(4);
  77252. var back = texture.readPixels(5);
  77253. var gammaSpace = texture.gammaSpace;
  77254. // Always read as RGBA.
  77255. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  77256. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77257. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77258. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77259. }
  77260. var cubeInfo = {
  77261. size: size,
  77262. right: right,
  77263. left: left,
  77264. up: up,
  77265. down: down,
  77266. front: front,
  77267. back: back,
  77268. format: format,
  77269. type: type,
  77270. gammaSpace: gammaSpace,
  77271. };
  77272. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  77273. };
  77274. /**
  77275. * Converts a cubemap to the according Spherical Polynomial data.
  77276. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77277. *
  77278. * @param cubeInfo The Cube map to extract the information from.
  77279. * @return The Spherical Polynomial data.
  77280. */
  77281. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  77282. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  77283. var totalSolidAngle = 0.0;
  77284. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  77285. var du = 2.0 / cubeInfo.size;
  77286. var dv = du;
  77287. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  77288. var minUV = du * 0.5 - 1.0;
  77289. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77290. var fileFace = this.FileFaces[faceIndex];
  77291. var dataArray = cubeInfo[fileFace.name];
  77292. var v = minUV;
  77293. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  77294. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  77295. // Because SP is still linear, so summation is fine in that basis.
  77296. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  77297. for (var y = 0; y < cubeInfo.size; y++) {
  77298. var u = minUV;
  77299. for (var x = 0; x < cubeInfo.size; x++) {
  77300. // World direction (not normalised)
  77301. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  77302. worldDirection.normalize();
  77303. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  77304. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  77305. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  77306. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  77307. // Handle Integer types.
  77308. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77309. r /= 255;
  77310. g /= 255;
  77311. b /= 255;
  77312. }
  77313. // Handle Gamma space textures.
  77314. if (cubeInfo.gammaSpace) {
  77315. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  77316. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  77317. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  77318. }
  77319. var color = new BABYLON.Color3(r, g, b);
  77320. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  77321. totalSolidAngle += deltaSolidAngle;
  77322. u += du;
  77323. }
  77324. v += dv;
  77325. }
  77326. }
  77327. // Solid angle for entire sphere is 4*pi
  77328. var sphereSolidAngle = 4.0 * Math.PI;
  77329. // Adjust the solid angle to allow for how many faces we processed.
  77330. var facesProcessed = 6.0;
  77331. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  77332. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  77333. // This is needed because the numerical integration over the cube uses a
  77334. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  77335. // and also to compensate for accumulative error due to float precision in the summation.
  77336. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  77337. sphericalHarmonics.scale(correctionFactor);
  77338. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  77339. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  77340. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  77341. };
  77342. CubeMapToSphericalPolynomialTools.FileFaces = [
  77343. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  77344. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  77345. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  77346. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  77347. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  77348. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  77349. ];
  77350. return CubeMapToSphericalPolynomialTools;
  77351. }());
  77352. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  77353. })(BABYLON || (BABYLON = {}));
  77354. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  77355. "use strict";
  77356. var BABYLON;
  77357. (function (BABYLON) {
  77358. /**
  77359. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  77360. */
  77361. var PanoramaToCubeMapTools = /** @class */ (function () {
  77362. function PanoramaToCubeMapTools() {
  77363. }
  77364. /**
  77365. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  77366. *
  77367. * @param float32Array The source data.
  77368. * @param inputWidth The width of the input panorama.
  77369. * @param inputhHeight The height of the input panorama.
  77370. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  77371. * @return The cubemap data
  77372. */
  77373. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  77374. if (!float32Array) {
  77375. throw "ConvertPanoramaToCubemap: input cannot be null";
  77376. }
  77377. if (float32Array.length != inputWidth * inputHeight * 3) {
  77378. throw "ConvertPanoramaToCubemap: input size is wrong";
  77379. }
  77380. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  77381. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  77382. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  77383. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  77384. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  77385. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  77386. return {
  77387. front: textureFront,
  77388. back: textureBack,
  77389. left: textureLeft,
  77390. right: textureRight,
  77391. up: textureUp,
  77392. down: textureDown,
  77393. size: size,
  77394. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  77395. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  77396. gammaSpace: false,
  77397. };
  77398. };
  77399. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  77400. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  77401. var textureArray = new Float32Array(buffer);
  77402. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  77403. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  77404. var dy = 1 / texSize;
  77405. var fy = 0;
  77406. for (var y = 0; y < texSize; y++) {
  77407. var xv1 = faceData[0];
  77408. var xv2 = faceData[2];
  77409. for (var x = 0; x < texSize; x++) {
  77410. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  77411. v.normalize();
  77412. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  77413. // 3 channels per pixels
  77414. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  77415. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  77416. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  77417. xv1 = xv1.add(rotDX1);
  77418. xv2 = xv2.add(rotDX2);
  77419. }
  77420. fy += dy;
  77421. }
  77422. return textureArray;
  77423. };
  77424. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  77425. var theta = Math.atan2(vDir.z, vDir.x);
  77426. var phi = Math.acos(vDir.y);
  77427. while (theta < -Math.PI)
  77428. theta += 2 * Math.PI;
  77429. while (theta > Math.PI)
  77430. theta -= 2 * Math.PI;
  77431. var dx = theta / Math.PI;
  77432. var dy = phi / Math.PI;
  77433. // recenter.
  77434. dx = dx * 0.5 + 0.5;
  77435. var px = Math.round(dx * inputWidth);
  77436. if (px < 0)
  77437. px = 0;
  77438. else if (px >= inputWidth)
  77439. px = inputWidth - 1;
  77440. var py = Math.round(dy * inputHeight);
  77441. if (py < 0)
  77442. py = 0;
  77443. else if (py >= inputHeight)
  77444. py = inputHeight - 1;
  77445. var inputY = (inputHeight - py - 1);
  77446. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  77447. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  77448. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  77449. return {
  77450. r: r,
  77451. g: g,
  77452. b: b
  77453. };
  77454. };
  77455. PanoramaToCubeMapTools.FACE_FRONT = [
  77456. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77457. new BABYLON.Vector3(1.0, -1.0, -1.0),
  77458. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  77459. new BABYLON.Vector3(1.0, 1.0, -1.0)
  77460. ];
  77461. PanoramaToCubeMapTools.FACE_BACK = [
  77462. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77463. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77464. new BABYLON.Vector3(1.0, 1.0, 1.0),
  77465. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  77466. ];
  77467. PanoramaToCubeMapTools.FACE_RIGHT = [
  77468. new BABYLON.Vector3(1.0, -1.0, -1.0),
  77469. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77470. new BABYLON.Vector3(1.0, 1.0, -1.0),
  77471. new BABYLON.Vector3(1.0, 1.0, 1.0)
  77472. ];
  77473. PanoramaToCubeMapTools.FACE_LEFT = [
  77474. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77475. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77476. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  77477. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  77478. ];
  77479. PanoramaToCubeMapTools.FACE_DOWN = [
  77480. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  77481. new BABYLON.Vector3(1.0, 1.0, -1.0),
  77482. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  77483. new BABYLON.Vector3(1.0, 1.0, 1.0)
  77484. ];
  77485. PanoramaToCubeMapTools.FACE_UP = [
  77486. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77487. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77488. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77489. new BABYLON.Vector3(1.0, -1.0, -1.0)
  77490. ];
  77491. return PanoramaToCubeMapTools;
  77492. }());
  77493. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  77494. })(BABYLON || (BABYLON = {}));
  77495. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  77496. "use strict";
  77497. var BABYLON;
  77498. (function (BABYLON) {
  77499. ;
  77500. /**
  77501. * This groups tools to convert HDR texture to native colors array.
  77502. */
  77503. var HDRTools = /** @class */ (function () {
  77504. function HDRTools() {
  77505. }
  77506. HDRTools.Ldexp = function (mantissa, exponent) {
  77507. if (exponent > 1023) {
  77508. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  77509. }
  77510. if (exponent < -1074) {
  77511. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  77512. }
  77513. return mantissa * Math.pow(2, exponent);
  77514. };
  77515. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  77516. if (exponent > 0) {
  77517. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  77518. float32array[index + 0] = red * exponent;
  77519. float32array[index + 1] = green * exponent;
  77520. float32array[index + 2] = blue * exponent;
  77521. }
  77522. else {
  77523. float32array[index + 0] = 0;
  77524. float32array[index + 1] = 0;
  77525. float32array[index + 2] = 0;
  77526. }
  77527. };
  77528. HDRTools.readStringLine = function (uint8array, startIndex) {
  77529. var line = "";
  77530. var character = "";
  77531. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  77532. character = String.fromCharCode(uint8array[i]);
  77533. if (character == "\n") {
  77534. break;
  77535. }
  77536. line += character;
  77537. }
  77538. return line;
  77539. };
  77540. /**
  77541. * Reads header information from an RGBE texture stored in a native array.
  77542. * More information on this format are available here:
  77543. * https://en.wikipedia.org/wiki/RGBE_image_format
  77544. *
  77545. * @param uint8array The binary file stored in native array.
  77546. * @return The header information.
  77547. */
  77548. HDRTools.RGBE_ReadHeader = function (uint8array) {
  77549. var height = 0;
  77550. var width = 0;
  77551. var line = this.readStringLine(uint8array, 0);
  77552. if (line[0] != '#' || line[1] != '?') {
  77553. throw "Bad HDR Format.";
  77554. }
  77555. var endOfHeader = false;
  77556. var findFormat = false;
  77557. var lineIndex = 0;
  77558. do {
  77559. lineIndex += (line.length + 1);
  77560. line = this.readStringLine(uint8array, lineIndex);
  77561. if (line == "FORMAT=32-bit_rle_rgbe") {
  77562. findFormat = true;
  77563. }
  77564. else if (line.length == 0) {
  77565. endOfHeader = true;
  77566. }
  77567. } while (!endOfHeader);
  77568. if (!findFormat) {
  77569. throw "HDR Bad header format, unsupported FORMAT";
  77570. }
  77571. lineIndex += (line.length + 1);
  77572. line = this.readStringLine(uint8array, lineIndex);
  77573. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  77574. var match = sizeRegexp.exec(line);
  77575. // TODO. Support +Y and -X if needed.
  77576. if (!match || match.length < 3) {
  77577. throw "HDR Bad header format, no size";
  77578. }
  77579. width = parseInt(match[2]);
  77580. height = parseInt(match[1]);
  77581. if (width < 8 || width > 0x7fff) {
  77582. throw "HDR Bad header format, unsupported size";
  77583. }
  77584. lineIndex += (line.length + 1);
  77585. return {
  77586. height: height,
  77587. width: width,
  77588. dataPosition: lineIndex
  77589. };
  77590. };
  77591. /**
  77592. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  77593. * This RGBE texture needs to store the information as a panorama.
  77594. *
  77595. * More information on this format are available here:
  77596. * https://en.wikipedia.org/wiki/RGBE_image_format
  77597. *
  77598. * @param buffer The binary file stored in an array buffer.
  77599. * @param size The expected size of the extracted cubemap.
  77600. * @return The Cube Map information.
  77601. */
  77602. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  77603. var uint8array = new Uint8Array(buffer);
  77604. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  77605. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  77606. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  77607. return cubeMapData;
  77608. };
  77609. /**
  77610. * Returns the pixels data extracted from an RGBE texture.
  77611. * This pixels will be stored left to right up to down in the R G B order in one array.
  77612. *
  77613. * More information on this format are available here:
  77614. * https://en.wikipedia.org/wiki/RGBE_image_format
  77615. *
  77616. * @param uint8array The binary file stored in an array buffer.
  77617. * @param hdrInfo The header information of the file.
  77618. * @return The pixels data in RGB right to left up to down order.
  77619. */
  77620. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  77621. // Keep for multi format supports.
  77622. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  77623. };
  77624. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  77625. var num_scanlines = hdrInfo.height;
  77626. var scanline_width = hdrInfo.width;
  77627. var a, b, c, d, count;
  77628. var dataIndex = hdrInfo.dataPosition;
  77629. var index = 0, endIndex = 0, i = 0;
  77630. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  77631. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  77632. // 3 channels of 4 bytes per pixel in float.
  77633. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  77634. var resultArray = new Float32Array(resultBuffer);
  77635. // read in each successive scanline
  77636. while (num_scanlines > 0) {
  77637. a = uint8array[dataIndex++];
  77638. b = uint8array[dataIndex++];
  77639. c = uint8array[dataIndex++];
  77640. d = uint8array[dataIndex++];
  77641. if (a != 2 || b != 2 || (c & 0x80)) {
  77642. // this file is not run length encoded
  77643. throw "HDR Bad header format, not RLE";
  77644. }
  77645. if (((c << 8) | d) != scanline_width) {
  77646. throw "HDR Bad header format, wrong scan line width";
  77647. }
  77648. index = 0;
  77649. // read each of the four channels for the scanline into the buffer
  77650. for (i = 0; i < 4; i++) {
  77651. endIndex = (i + 1) * scanline_width;
  77652. while (index < endIndex) {
  77653. a = uint8array[dataIndex++];
  77654. b = uint8array[dataIndex++];
  77655. if (a > 128) {
  77656. // a run of the same value
  77657. count = a - 128;
  77658. if ((count == 0) || (count > endIndex - index)) {
  77659. throw "HDR Bad Format, bad scanline data (run)";
  77660. }
  77661. while (count-- > 0) {
  77662. scanLineArray[index++] = b;
  77663. }
  77664. }
  77665. else {
  77666. // a non-run
  77667. count = a;
  77668. if ((count == 0) || (count > endIndex - index)) {
  77669. throw "HDR Bad Format, bad scanline data (non-run)";
  77670. }
  77671. scanLineArray[index++] = b;
  77672. if (--count > 0) {
  77673. for (var j = 0; j < count; j++) {
  77674. scanLineArray[index++] = uint8array[dataIndex++];
  77675. }
  77676. }
  77677. }
  77678. }
  77679. }
  77680. // now convert data from buffer into floats
  77681. for (i = 0; i < scanline_width; i++) {
  77682. a = scanLineArray[i];
  77683. b = scanLineArray[i + scanline_width];
  77684. c = scanLineArray[i + 2 * scanline_width];
  77685. d = scanLineArray[i + 3 * scanline_width];
  77686. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  77687. }
  77688. num_scanlines--;
  77689. }
  77690. return resultArray;
  77691. };
  77692. return HDRTools;
  77693. }());
  77694. BABYLON.HDRTools = HDRTools;
  77695. })(BABYLON || (BABYLON = {}));
  77696. //# sourceMappingURL=babylon.hdr.js.map
  77697. "use strict";
  77698. var BABYLON;
  77699. (function (BABYLON) {
  77700. /**
  77701. * This represents a texture coming from an HDR input.
  77702. *
  77703. * The only supported format is currently panorama picture stored in RGBE format.
  77704. * Example of such files can be found on HDRLib: http://hdrlib.com/
  77705. */
  77706. var HDRCubeTexture = /** @class */ (function (_super) {
  77707. __extends(HDRCubeTexture, _super);
  77708. /**
  77709. * Instantiates an HDRTexture from the following parameters.
  77710. *
  77711. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  77712. * @param scene The scene the texture will be used in
  77713. * @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.
  77714. * @param noMipmap Forces to not generate the mipmap if true
  77715. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  77716. * @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)
  77717. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  77718. */
  77719. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  77720. if (noMipmap === void 0) { noMipmap = false; }
  77721. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77722. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77723. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77724. if (onLoad === void 0) { onLoad = null; }
  77725. if (onError === void 0) { onError = null; }
  77726. var _this = _super.call(this, scene) || this;
  77727. _this._useInGammaSpace = false;
  77728. _this._generateHarmonics = true;
  77729. _this._isBABYLONPreprocessed = false;
  77730. _this._onLoad = null;
  77731. _this._onError = null;
  77732. /**
  77733. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  77734. */
  77735. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  77736. /**
  77737. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  77738. * This is usefull at run time to apply the good shader.
  77739. */
  77740. _this.isPMREM = false;
  77741. _this._isBlocking = true;
  77742. /**
  77743. * Gets or sets the center of the bounding box associated with the cube texture
  77744. * It must define where the camera used to render the texture was set
  77745. */
  77746. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  77747. if (!url) {
  77748. return _this;
  77749. }
  77750. _this.name = url;
  77751. _this.url = url;
  77752. _this.hasAlpha = false;
  77753. _this.isCube = true;
  77754. _this._textureMatrix = BABYLON.Matrix.Identity();
  77755. _this._onLoad = onLoad;
  77756. _this._onError = onError;
  77757. _this.gammaSpace = false;
  77758. var caps = scene.getEngine().getCaps();
  77759. if (size) {
  77760. _this._isBABYLONPreprocessed = false;
  77761. _this._noMipmap = noMipmap;
  77762. _this._size = size;
  77763. _this._useInGammaSpace = useInGammaSpace;
  77764. _this._usePMREMGenerator = usePMREMGenerator &&
  77765. caps.textureLOD &&
  77766. caps.textureFloat &&
  77767. !_this._useInGammaSpace;
  77768. }
  77769. else {
  77770. _this._isBABYLONPreprocessed = true;
  77771. _this._noMipmap = false;
  77772. _this._useInGammaSpace = false;
  77773. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  77774. !_this._useInGammaSpace;
  77775. }
  77776. _this.isPMREM = _this._usePMREMGenerator;
  77777. _this._texture = _this._getFromCache(url, _this._noMipmap);
  77778. if (!_this._texture) {
  77779. if (!scene.useDelayedTextureLoading) {
  77780. _this.loadTexture();
  77781. }
  77782. else {
  77783. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77784. }
  77785. }
  77786. return _this;
  77787. }
  77788. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  77789. /**
  77790. * Gets wether or not the texture is blocking during loading.
  77791. */
  77792. get: function () {
  77793. return this._isBlocking;
  77794. },
  77795. /**
  77796. * Sets wether or not the texture is blocking during loading.
  77797. */
  77798. set: function (value) {
  77799. this._isBlocking = value;
  77800. },
  77801. enumerable: true,
  77802. configurable: true
  77803. });
  77804. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  77805. get: function () {
  77806. return this._boundingBoxSize;
  77807. },
  77808. /**
  77809. * Gets or sets the size of the bounding box associated with the cube texture
  77810. * When defined, the cubemap will switch to local mode
  77811. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  77812. * @example https://www.babylonjs-playground.com/#RNASML
  77813. */
  77814. set: function (value) {
  77815. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  77816. return;
  77817. }
  77818. this._boundingBoxSize = value;
  77819. var scene = this.getScene();
  77820. if (scene) {
  77821. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  77822. }
  77823. },
  77824. enumerable: true,
  77825. configurable: true
  77826. });
  77827. /**
  77828. * Occurs when the file is a preprocessed .babylon.hdr file.
  77829. */
  77830. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  77831. var _this = this;
  77832. var mipLevels = 0;
  77833. var floatArrayView = null;
  77834. var scene = this.getScene();
  77835. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  77836. var mips = new Array();
  77837. if (!floatArrayView) {
  77838. return mips;
  77839. }
  77840. var startIndex = 30;
  77841. for (var level = 0; level < mipLevels; level++) {
  77842. mips.push([]);
  77843. // Fill each pixel of the mip level.
  77844. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  77845. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77846. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  77847. mips[level].push(faceData);
  77848. startIndex += faceSize;
  77849. }
  77850. }
  77851. return mips;
  77852. } : null;
  77853. var callback = function (buffer) {
  77854. var scene = _this.getScene();
  77855. if (!scene) {
  77856. return null;
  77857. }
  77858. // Create Native Array Views
  77859. var intArrayView = new Int32Array(buffer);
  77860. floatArrayView = new Float32Array(buffer);
  77861. // Fill header.
  77862. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  77863. _this._size = intArrayView[1]; // CubeMap max mip face size.
  77864. // Update Texture Information.
  77865. if (!_this._texture) {
  77866. return null;
  77867. }
  77868. _this._texture.updateSize(_this._size, _this._size);
  77869. // Fill polynomial information.
  77870. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  77871. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  77872. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  77873. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  77874. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  77875. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  77876. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  77877. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  77878. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  77879. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  77880. _this.sphericalPolynomial = sphericalPolynomial;
  77881. // Fill pixel data.
  77882. mipLevels = intArrayView[29]; // Number of mip levels.
  77883. var startIndex = 30;
  77884. var data = [];
  77885. var faceSize = Math.pow(_this._size, 2) * 3;
  77886. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77887. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  77888. startIndex += faceSize;
  77889. }
  77890. var results = [];
  77891. var byteArray = null;
  77892. // Push each faces.
  77893. for (var k = 0; k < 6; k++) {
  77894. var dataFace = null;
  77895. // To be deprecated.
  77896. if (version === 1) {
  77897. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  77898. dataFace = data[j];
  77899. }
  77900. // If special cases.
  77901. if (!mipmapGenerator && dataFace) {
  77902. if (!scene.getEngine().getCaps().textureFloat) {
  77903. // 3 channels of 1 bytes per pixel in bytes.
  77904. var byteBuffer = new ArrayBuffer(faceSize);
  77905. byteArray = new Uint8Array(byteBuffer);
  77906. }
  77907. for (var i = 0; i < _this._size * _this._size; i++) {
  77908. // Put in gamma space if requested.
  77909. if (_this._useInGammaSpace) {
  77910. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  77911. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  77912. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  77913. }
  77914. // Convert to int texture for fallback.
  77915. if (byteArray) {
  77916. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  77917. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  77918. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  77919. // May use luminance instead if the result is not accurate.
  77920. var max = Math.max(Math.max(r, g), b);
  77921. if (max > 255) {
  77922. var scale = 255 / max;
  77923. r *= scale;
  77924. g *= scale;
  77925. b *= scale;
  77926. }
  77927. byteArray[(i * 3) + 0] = r;
  77928. byteArray[(i * 3) + 1] = g;
  77929. byteArray[(i * 3) + 2] = b;
  77930. }
  77931. }
  77932. }
  77933. // Fill the array accordingly.
  77934. if (byteArray) {
  77935. results.push(byteArray);
  77936. }
  77937. else {
  77938. results.push(dataFace);
  77939. }
  77940. }
  77941. return results;
  77942. };
  77943. if (scene) {
  77944. 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);
  77945. }
  77946. };
  77947. /**
  77948. * Occurs when the file is raw .hdr file.
  77949. */
  77950. HDRCubeTexture.prototype.loadHDRTexture = function () {
  77951. var _this = this;
  77952. var callback = function (buffer) {
  77953. var scene = _this.getScene();
  77954. if (!scene) {
  77955. return null;
  77956. }
  77957. // Extract the raw linear data.
  77958. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  77959. // Generate harmonics if needed.
  77960. if (_this._generateHarmonics) {
  77961. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  77962. _this.sphericalPolynomial = sphericalPolynomial;
  77963. }
  77964. var results = [];
  77965. var byteArray = null;
  77966. // Push each faces.
  77967. for (var j = 0; j < 6; j++) {
  77968. // Create uintarray fallback.
  77969. if (!scene.getEngine().getCaps().textureFloat) {
  77970. // 3 channels of 1 bytes per pixel in bytes.
  77971. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  77972. byteArray = new Uint8Array(byteBuffer);
  77973. }
  77974. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  77975. // If special cases.
  77976. if (_this._useInGammaSpace || byteArray) {
  77977. for (var i = 0; i < _this._size * _this._size; i++) {
  77978. // Put in gamma space if requested.
  77979. if (_this._useInGammaSpace) {
  77980. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  77981. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  77982. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  77983. }
  77984. // Convert to int texture for fallback.
  77985. if (byteArray) {
  77986. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  77987. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  77988. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  77989. // May use luminance instead if the result is not accurate.
  77990. var max = Math.max(Math.max(r, g), b);
  77991. if (max > 255) {
  77992. var scale = 255 / max;
  77993. r *= scale;
  77994. g *= scale;
  77995. b *= scale;
  77996. }
  77997. byteArray[(i * 3) + 0] = r;
  77998. byteArray[(i * 3) + 1] = g;
  77999. byteArray[(i * 3) + 2] = b;
  78000. }
  78001. }
  78002. }
  78003. if (byteArray) {
  78004. results.push(byteArray);
  78005. }
  78006. else {
  78007. results.push(dataFace);
  78008. }
  78009. }
  78010. return results;
  78011. };
  78012. var mipmapGenerator = null;
  78013. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  78014. // if (!this._noMipmap &&
  78015. // this._usePMREMGenerator) {
  78016. // mipmapGenerator = (data: ArrayBufferView[]) => {
  78017. // // Custom setup of the generator matching with the PBR shader values.
  78018. // var generator = new BABYLON.PMREMGenerator(data,
  78019. // this._size,
  78020. // this._size,
  78021. // 0,
  78022. // 3,
  78023. // this.getScene().getEngine().getCaps().textureFloat,
  78024. // 2048,
  78025. // 0.25,
  78026. // false,
  78027. // true);
  78028. // return generator.filterCubeMap();
  78029. // };
  78030. // }
  78031. var scene = this.getScene();
  78032. if (scene) {
  78033. 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);
  78034. }
  78035. };
  78036. /**
  78037. * Starts the loading process of the texture.
  78038. */
  78039. HDRCubeTexture.prototype.loadTexture = function () {
  78040. if (this._isBABYLONPreprocessed) {
  78041. this.loadBabylonTexture();
  78042. }
  78043. else {
  78044. this.loadHDRTexture();
  78045. }
  78046. };
  78047. HDRCubeTexture.prototype.clone = function () {
  78048. var scene = this.getScene();
  78049. if (!scene) {
  78050. return this;
  78051. }
  78052. var size = (this._isBABYLONPreprocessed ? null : this._size);
  78053. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  78054. // Base texture
  78055. newTexture.level = this.level;
  78056. newTexture.wrapU = this.wrapU;
  78057. newTexture.wrapV = this.wrapV;
  78058. newTexture.coordinatesIndex = this.coordinatesIndex;
  78059. newTexture.coordinatesMode = this.coordinatesMode;
  78060. return newTexture;
  78061. };
  78062. // Methods
  78063. HDRCubeTexture.prototype.delayLoad = function () {
  78064. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78065. return;
  78066. }
  78067. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78068. this._texture = this._getFromCache(this.url, this._noMipmap);
  78069. if (!this._texture) {
  78070. this.loadTexture();
  78071. }
  78072. };
  78073. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  78074. return this._textureMatrix;
  78075. };
  78076. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  78077. this._textureMatrix = value;
  78078. };
  78079. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78080. var texture = null;
  78081. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78082. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  78083. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  78084. texture.name = parsedTexture.name;
  78085. texture.hasAlpha = parsedTexture.hasAlpha;
  78086. texture.level = parsedTexture.level;
  78087. texture.coordinatesMode = parsedTexture.coordinatesMode;
  78088. texture.isBlocking = parsedTexture.isBlocking;
  78089. }
  78090. if (texture) {
  78091. if (parsedTexture.boundingBoxPosition) {
  78092. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  78093. }
  78094. if (parsedTexture.boundingBoxSize) {
  78095. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  78096. }
  78097. }
  78098. return texture;
  78099. };
  78100. HDRCubeTexture.prototype.serialize = function () {
  78101. if (!this.name) {
  78102. return null;
  78103. }
  78104. var serializationObject = {};
  78105. serializationObject.name = this.name;
  78106. serializationObject.hasAlpha = this.hasAlpha;
  78107. serializationObject.isCube = true;
  78108. serializationObject.level = this.level;
  78109. serializationObject.size = this._size;
  78110. serializationObject.coordinatesMode = this.coordinatesMode;
  78111. serializationObject.useInGammaSpace = this._useInGammaSpace;
  78112. serializationObject.generateHarmonics = this._generateHarmonics;
  78113. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  78114. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  78115. serializationObject.customType = "BABYLON.HDRCubeTexture";
  78116. serializationObject.noMipmap = this._noMipmap;
  78117. serializationObject.isBlocking = this._isBlocking;
  78118. return serializationObject;
  78119. };
  78120. /**
  78121. * Saves as a file the data contained in the texture in a binary format.
  78122. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78123. * as the spherical used in the lighting.
  78124. * @param url The HDR file url.
  78125. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78126. * @param onError Method called if any error happens during download.
  78127. * @return The packed binary data.
  78128. */
  78129. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  78130. if (onError === void 0) { onError = null; }
  78131. var callback = function (buffer) {
  78132. var data = new Blob([buffer], { type: 'application/octet-stream' });
  78133. // Returns a URL you can use as a href.
  78134. var objUrl = window.URL.createObjectURL(data);
  78135. // Simulates a link to it and click to dowload.
  78136. var a = document.createElement("a");
  78137. document.body.appendChild(a);
  78138. a.style.display = "none";
  78139. a.href = objUrl;
  78140. a.download = "envmap.babylon.hdr";
  78141. a.click();
  78142. };
  78143. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  78144. };
  78145. /**
  78146. * Serializes the data contained in the texture in a binary format.
  78147. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78148. * as the spherical used in the lighting.
  78149. * @param url The HDR file url.
  78150. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78151. * @param onError Method called if any error happens during download.
  78152. * @return The packed binary data.
  78153. */
  78154. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  78155. if (onError === void 0) { onError = null; }
  78156. // Needs the url tho create the texture.
  78157. if (!url) {
  78158. return;
  78159. }
  78160. // Check Power of two size.
  78161. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  78162. return;
  78163. }
  78164. // Coming Back in 3.x.
  78165. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  78166. };
  78167. HDRCubeTexture._facesMapping = [
  78168. "right",
  78169. "left",
  78170. "up",
  78171. "down",
  78172. "front",
  78173. "back"
  78174. ];
  78175. return HDRCubeTexture;
  78176. }(BABYLON.BaseTexture));
  78177. BABYLON.HDRCubeTexture = HDRCubeTexture;
  78178. })(BABYLON || (BABYLON = {}));
  78179. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  78180. "use strict";
  78181. var BABYLON;
  78182. (function (BABYLON) {
  78183. var IndexedVector2 = /** @class */ (function (_super) {
  78184. __extends(IndexedVector2, _super);
  78185. function IndexedVector2(original, index) {
  78186. var _this = _super.call(this, original.x, original.y) || this;
  78187. _this.index = index;
  78188. return _this;
  78189. }
  78190. return IndexedVector2;
  78191. }(BABYLON.Vector2));
  78192. var PolygonPoints = /** @class */ (function () {
  78193. function PolygonPoints() {
  78194. this.elements = new Array();
  78195. }
  78196. PolygonPoints.prototype.add = function (originalPoints) {
  78197. var _this = this;
  78198. var result = new Array();
  78199. originalPoints.forEach(function (point) {
  78200. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  78201. var newPoint = new IndexedVector2(point, _this.elements.length);
  78202. result.push(newPoint);
  78203. _this.elements.push(newPoint);
  78204. }
  78205. });
  78206. return result;
  78207. };
  78208. PolygonPoints.prototype.computeBounds = function () {
  78209. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78210. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78211. this.elements.forEach(function (point) {
  78212. // x
  78213. if (point.x < lmin.x) {
  78214. lmin.x = point.x;
  78215. }
  78216. else if (point.x > lmax.x) {
  78217. lmax.x = point.x;
  78218. }
  78219. // y
  78220. if (point.y < lmin.y) {
  78221. lmin.y = point.y;
  78222. }
  78223. else if (point.y > lmax.y) {
  78224. lmax.y = point.y;
  78225. }
  78226. });
  78227. return {
  78228. min: lmin,
  78229. max: lmax,
  78230. width: lmax.x - lmin.x,
  78231. height: lmax.y - lmin.y
  78232. };
  78233. };
  78234. return PolygonPoints;
  78235. }());
  78236. var Polygon = /** @class */ (function () {
  78237. function Polygon() {
  78238. }
  78239. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  78240. return [
  78241. new BABYLON.Vector2(xmin, ymin),
  78242. new BABYLON.Vector2(xmax, ymin),
  78243. new BABYLON.Vector2(xmax, ymax),
  78244. new BABYLON.Vector2(xmin, ymax)
  78245. ];
  78246. };
  78247. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  78248. if (cx === void 0) { cx = 0; }
  78249. if (cy === void 0) { cy = 0; }
  78250. if (numberOfSides === void 0) { numberOfSides = 32; }
  78251. var result = new Array();
  78252. var angle = 0;
  78253. var increment = (Math.PI * 2) / numberOfSides;
  78254. for (var i = 0; i < numberOfSides; i++) {
  78255. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  78256. angle -= increment;
  78257. }
  78258. return result;
  78259. };
  78260. Polygon.Parse = function (input) {
  78261. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  78262. var i, result = [];
  78263. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  78264. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  78265. }
  78266. return result;
  78267. };
  78268. Polygon.StartingAt = function (x, y) {
  78269. return BABYLON.Path2.StartingAt(x, y);
  78270. };
  78271. return Polygon;
  78272. }());
  78273. BABYLON.Polygon = Polygon;
  78274. var PolygonMeshBuilder = /** @class */ (function () {
  78275. function PolygonMeshBuilder(name, contours, scene) {
  78276. this._points = new PolygonPoints();
  78277. this._outlinepoints = new PolygonPoints();
  78278. this._holes = new Array();
  78279. this._epoints = new Array();
  78280. this._eholes = new Array();
  78281. this._name = name;
  78282. this._scene = scene;
  78283. var points;
  78284. if (contours instanceof BABYLON.Path2) {
  78285. points = contours.getPoints();
  78286. }
  78287. else {
  78288. points = contours;
  78289. }
  78290. this._addToepoint(points);
  78291. this._points.add(points);
  78292. this._outlinepoints.add(points);
  78293. if (typeof earcut === 'undefined') {
  78294. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  78295. }
  78296. }
  78297. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  78298. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  78299. var p = points_1[_i];
  78300. this._epoints.push(p.x, p.y);
  78301. }
  78302. };
  78303. PolygonMeshBuilder.prototype.addHole = function (hole) {
  78304. this._points.add(hole);
  78305. var holepoints = new PolygonPoints();
  78306. holepoints.add(hole);
  78307. this._holes.push(holepoints);
  78308. this._eholes.push(this._epoints.length / 2);
  78309. this._addToepoint(hole);
  78310. return this;
  78311. };
  78312. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  78313. var _this = this;
  78314. if (updatable === void 0) { updatable = false; }
  78315. if (depth === void 0) { depth = 0; }
  78316. var result = new BABYLON.Mesh(this._name, this._scene);
  78317. var normals = new Array();
  78318. var positions = new Array();
  78319. var uvs = new Array();
  78320. var bounds = this._points.computeBounds();
  78321. this._points.elements.forEach(function (p) {
  78322. normals.push(0, 1.0, 0);
  78323. positions.push(p.x, 0, p.y);
  78324. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  78325. });
  78326. var indices = new Array();
  78327. var res = earcut(this._epoints, this._eholes, 2);
  78328. for (var i = 0; i < res.length; i++) {
  78329. indices.push(res[i]);
  78330. }
  78331. if (depth > 0) {
  78332. var positionscount = (positions.length / 3); //get the current pointcount
  78333. this._points.elements.forEach(function (p) {
  78334. normals.push(0, -1.0, 0);
  78335. positions.push(p.x, -depth, p.y);
  78336. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  78337. });
  78338. var totalCount = indices.length;
  78339. for (var i = 0; i < totalCount; i += 3) {
  78340. var i0 = indices[i + 0];
  78341. var i1 = indices[i + 1];
  78342. var i2 = indices[i + 2];
  78343. indices.push(i2 + positionscount);
  78344. indices.push(i1 + positionscount);
  78345. indices.push(i0 + positionscount);
  78346. }
  78347. //Add the sides
  78348. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  78349. this._holes.forEach(function (hole) {
  78350. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  78351. });
  78352. }
  78353. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  78354. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  78355. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  78356. result.setIndices(indices);
  78357. return result;
  78358. };
  78359. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  78360. var StartIndex = positions.length / 3;
  78361. var ulength = 0;
  78362. for (var i = 0; i < points.elements.length; i++) {
  78363. var p = points.elements[i];
  78364. var p1;
  78365. if ((i + 1) > points.elements.length - 1) {
  78366. p1 = points.elements[0];
  78367. }
  78368. else {
  78369. p1 = points.elements[i + 1];
  78370. }
  78371. positions.push(p.x, 0, p.y);
  78372. positions.push(p.x, -depth, p.y);
  78373. positions.push(p1.x, 0, p1.y);
  78374. positions.push(p1.x, -depth, p1.y);
  78375. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  78376. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  78377. var v3 = v2.subtract(v1);
  78378. var v4 = new BABYLON.Vector3(0, 1, 0);
  78379. var vn = BABYLON.Vector3.Cross(v3, v4);
  78380. vn = vn.normalize();
  78381. uvs.push(ulength / bounds.width, 0);
  78382. uvs.push(ulength / bounds.width, 1);
  78383. ulength += v3.length();
  78384. uvs.push((ulength / bounds.width), 0);
  78385. uvs.push((ulength / bounds.width), 1);
  78386. if (!flip) {
  78387. normals.push(-vn.x, -vn.y, -vn.z);
  78388. normals.push(-vn.x, -vn.y, -vn.z);
  78389. normals.push(-vn.x, -vn.y, -vn.z);
  78390. normals.push(-vn.x, -vn.y, -vn.z);
  78391. indices.push(StartIndex);
  78392. indices.push(StartIndex + 1);
  78393. indices.push(StartIndex + 2);
  78394. indices.push(StartIndex + 1);
  78395. indices.push(StartIndex + 3);
  78396. indices.push(StartIndex + 2);
  78397. }
  78398. else {
  78399. normals.push(vn.x, vn.y, vn.z);
  78400. normals.push(vn.x, vn.y, vn.z);
  78401. normals.push(vn.x, vn.y, vn.z);
  78402. normals.push(vn.x, vn.y, vn.z);
  78403. indices.push(StartIndex);
  78404. indices.push(StartIndex + 2);
  78405. indices.push(StartIndex + 1);
  78406. indices.push(StartIndex + 1);
  78407. indices.push(StartIndex + 2);
  78408. indices.push(StartIndex + 3);
  78409. }
  78410. StartIndex += 4;
  78411. }
  78412. ;
  78413. };
  78414. return PolygonMeshBuilder;
  78415. }());
  78416. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  78417. })(BABYLON || (BABYLON = {}));
  78418. //# sourceMappingURL=babylon.polygonMesh.js.map
  78419. "use strict";
  78420. var BABYLON;
  78421. (function (BABYLON) {
  78422. // Unique ID when we import meshes from Babylon to CSG
  78423. var currentCSGMeshId = 0;
  78424. // # class Vertex
  78425. // Represents a vertex of a polygon. Use your own vertex class instead of this
  78426. // one to provide additional features like texture coordinates and vertex
  78427. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  78428. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  78429. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  78430. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  78431. // is not used anywhere else.
  78432. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  78433. var Vertex = /** @class */ (function () {
  78434. function Vertex(pos, normal, uv) {
  78435. this.pos = pos;
  78436. this.normal = normal;
  78437. this.uv = uv;
  78438. }
  78439. Vertex.prototype.clone = function () {
  78440. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  78441. };
  78442. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  78443. // orientation of a polygon is flipped.
  78444. Vertex.prototype.flip = function () {
  78445. this.normal = this.normal.scale(-1);
  78446. };
  78447. // Create a new vertex between this vertex and `other` by linearly
  78448. // interpolating all properties using a parameter of `t`. Subclasses should
  78449. // override this to interpolate additional properties.
  78450. Vertex.prototype.interpolate = function (other, t) {
  78451. 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));
  78452. };
  78453. return Vertex;
  78454. }());
  78455. // # class Plane
  78456. // Represents a plane in 3D space.
  78457. var Plane = /** @class */ (function () {
  78458. function Plane(normal, w) {
  78459. this.normal = normal;
  78460. this.w = w;
  78461. }
  78462. Plane.FromPoints = function (a, b, c) {
  78463. var v0 = c.subtract(a);
  78464. var v1 = b.subtract(a);
  78465. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  78466. return null;
  78467. }
  78468. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  78469. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  78470. };
  78471. Plane.prototype.clone = function () {
  78472. return new Plane(this.normal.clone(), this.w);
  78473. };
  78474. Plane.prototype.flip = function () {
  78475. this.normal.scaleInPlace(-1);
  78476. this.w = -this.w;
  78477. };
  78478. // Split `polygon` by this plane if needed, then put the polygon or polygon
  78479. // fragments in the appropriate lists. Coplanar polygons go into either
  78480. // `coplanarFront` or `coplanarBack` depending on their orientation with
  78481. // respect to this plane. Polygons in front or in back of this plane go into
  78482. // either `front` or `back`.
  78483. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  78484. var COPLANAR = 0;
  78485. var FRONT = 1;
  78486. var BACK = 2;
  78487. var SPANNING = 3;
  78488. // Classify each point as well as the entire polygon into one of the above
  78489. // four classes.
  78490. var polygonType = 0;
  78491. var types = [];
  78492. var i;
  78493. var t;
  78494. for (i = 0; i < polygon.vertices.length; i++) {
  78495. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  78496. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  78497. polygonType |= type;
  78498. types.push(type);
  78499. }
  78500. // Put the polygon in the correct list, splitting it when necessary.
  78501. switch (polygonType) {
  78502. case COPLANAR:
  78503. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  78504. break;
  78505. case FRONT:
  78506. front.push(polygon);
  78507. break;
  78508. case BACK:
  78509. back.push(polygon);
  78510. break;
  78511. case SPANNING:
  78512. var f = [], b = [];
  78513. for (i = 0; i < polygon.vertices.length; i++) {
  78514. var j = (i + 1) % polygon.vertices.length;
  78515. var ti = types[i], tj = types[j];
  78516. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  78517. if (ti !== BACK)
  78518. f.push(vi);
  78519. if (ti !== FRONT)
  78520. b.push(ti !== BACK ? vi.clone() : vi);
  78521. if ((ti | tj) === SPANNING) {
  78522. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  78523. var v = vi.interpolate(vj, t);
  78524. f.push(v);
  78525. b.push(v.clone());
  78526. }
  78527. }
  78528. var poly;
  78529. if (f.length >= 3) {
  78530. poly = new Polygon(f, polygon.shared);
  78531. if (poly.plane)
  78532. front.push(poly);
  78533. }
  78534. if (b.length >= 3) {
  78535. poly = new Polygon(b, polygon.shared);
  78536. if (poly.plane)
  78537. back.push(poly);
  78538. }
  78539. break;
  78540. }
  78541. };
  78542. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  78543. // point is on the plane.
  78544. Plane.EPSILON = 1e-5;
  78545. return Plane;
  78546. }());
  78547. // # class Polygon
  78548. // Represents a convex polygon. The vertices used to initialize a polygon must
  78549. // be coplanar and form a convex loop.
  78550. //
  78551. // Each convex polygon has a `shared` property, which is shared between all
  78552. // polygons that are clones of each other or were split from the same polygon.
  78553. // This can be used to define per-polygon properties (such as surface color).
  78554. var Polygon = /** @class */ (function () {
  78555. function Polygon(vertices, shared) {
  78556. this.vertices = vertices;
  78557. this.shared = shared;
  78558. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  78559. }
  78560. Polygon.prototype.clone = function () {
  78561. var vertices = this.vertices.map(function (v) { return v.clone(); });
  78562. return new Polygon(vertices, this.shared);
  78563. };
  78564. Polygon.prototype.flip = function () {
  78565. this.vertices.reverse().map(function (v) { v.flip(); });
  78566. this.plane.flip();
  78567. };
  78568. return Polygon;
  78569. }());
  78570. // # class Node
  78571. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  78572. // by picking a polygon to split along. That polygon (and all other coplanar
  78573. // polygons) are added directly to that node and the other polygons are added to
  78574. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  78575. // no distinction between internal and leaf nodes.
  78576. var Node = /** @class */ (function () {
  78577. function Node(polygons) {
  78578. this.plane = null;
  78579. this.front = null;
  78580. this.back = null;
  78581. this.polygons = new Array();
  78582. if (polygons) {
  78583. this.build(polygons);
  78584. }
  78585. }
  78586. Node.prototype.clone = function () {
  78587. var node = new Node();
  78588. node.plane = this.plane && this.plane.clone();
  78589. node.front = this.front && this.front.clone();
  78590. node.back = this.back && this.back.clone();
  78591. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  78592. return node;
  78593. };
  78594. // Convert solid space to empty space and empty space to solid space.
  78595. Node.prototype.invert = function () {
  78596. for (var i = 0; i < this.polygons.length; i++) {
  78597. this.polygons[i].flip();
  78598. }
  78599. if (this.plane) {
  78600. this.plane.flip();
  78601. }
  78602. if (this.front) {
  78603. this.front.invert();
  78604. }
  78605. if (this.back) {
  78606. this.back.invert();
  78607. }
  78608. var temp = this.front;
  78609. this.front = this.back;
  78610. this.back = temp;
  78611. };
  78612. // Recursively remove all polygons in `polygons` that are inside this BSP
  78613. // tree.
  78614. Node.prototype.clipPolygons = function (polygons) {
  78615. if (!this.plane)
  78616. return polygons.slice();
  78617. var front = new Array(), back = new Array();
  78618. for (var i = 0; i < polygons.length; i++) {
  78619. this.plane.splitPolygon(polygons[i], front, back, front, back);
  78620. }
  78621. if (this.front) {
  78622. front = this.front.clipPolygons(front);
  78623. }
  78624. if (this.back) {
  78625. back = this.back.clipPolygons(back);
  78626. }
  78627. else {
  78628. back = [];
  78629. }
  78630. return front.concat(back);
  78631. };
  78632. // Remove all polygons in this BSP tree that are inside the other BSP tree
  78633. // `bsp`.
  78634. Node.prototype.clipTo = function (bsp) {
  78635. this.polygons = bsp.clipPolygons(this.polygons);
  78636. if (this.front)
  78637. this.front.clipTo(bsp);
  78638. if (this.back)
  78639. this.back.clipTo(bsp);
  78640. };
  78641. // Return a list of all polygons in this BSP tree.
  78642. Node.prototype.allPolygons = function () {
  78643. var polygons = this.polygons.slice();
  78644. if (this.front)
  78645. polygons = polygons.concat(this.front.allPolygons());
  78646. if (this.back)
  78647. polygons = polygons.concat(this.back.allPolygons());
  78648. return polygons;
  78649. };
  78650. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  78651. // new polygons are filtered down to the bottom of the tree and become new
  78652. // nodes there. Each set of polygons is partitioned using the first polygon
  78653. // (no heuristic is used to pick a good split).
  78654. Node.prototype.build = function (polygons) {
  78655. if (!polygons.length)
  78656. return;
  78657. if (!this.plane)
  78658. this.plane = polygons[0].plane.clone();
  78659. var front = new Array(), back = new Array();
  78660. for (var i = 0; i < polygons.length; i++) {
  78661. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  78662. }
  78663. if (front.length) {
  78664. if (!this.front)
  78665. this.front = new Node();
  78666. this.front.build(front);
  78667. }
  78668. if (back.length) {
  78669. if (!this.back)
  78670. this.back = new Node();
  78671. this.back.build(back);
  78672. }
  78673. };
  78674. return Node;
  78675. }());
  78676. var CSG = /** @class */ (function () {
  78677. function CSG() {
  78678. this.polygons = new Array();
  78679. }
  78680. // Convert BABYLON.Mesh to BABYLON.CSG
  78681. CSG.FromMesh = function (mesh) {
  78682. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  78683. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  78684. if (mesh instanceof BABYLON.Mesh) {
  78685. mesh.computeWorldMatrix(true);
  78686. matrix = mesh.getWorldMatrix();
  78687. meshPosition = mesh.position.clone();
  78688. meshRotation = mesh.rotation.clone();
  78689. if (mesh.rotationQuaternion) {
  78690. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  78691. }
  78692. meshScaling = mesh.scaling.clone();
  78693. }
  78694. else {
  78695. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  78696. }
  78697. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  78698. var subMeshes = mesh.subMeshes;
  78699. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  78700. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  78701. vertices = [];
  78702. for (var j = 0; j < 3; j++) {
  78703. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  78704. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  78705. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  78706. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  78707. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  78708. vertex = new Vertex(position, normal, uv);
  78709. vertices.push(vertex);
  78710. }
  78711. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  78712. // To handle the case of degenerated triangle
  78713. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  78714. if (polygon.plane)
  78715. polygons.push(polygon);
  78716. }
  78717. }
  78718. var csg = CSG.FromPolygons(polygons);
  78719. csg.matrix = matrix;
  78720. csg.position = meshPosition;
  78721. csg.rotation = meshRotation;
  78722. csg.scaling = meshScaling;
  78723. csg.rotationQuaternion = meshRotationQuaternion;
  78724. currentCSGMeshId++;
  78725. return csg;
  78726. };
  78727. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  78728. CSG.FromPolygons = function (polygons) {
  78729. var csg = new CSG();
  78730. csg.polygons = polygons;
  78731. return csg;
  78732. };
  78733. CSG.prototype.clone = function () {
  78734. var csg = new CSG();
  78735. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  78736. csg.copyTransformAttributes(this);
  78737. return csg;
  78738. };
  78739. CSG.prototype.union = function (csg) {
  78740. var a = new Node(this.clone().polygons);
  78741. var b = new Node(csg.clone().polygons);
  78742. a.clipTo(b);
  78743. b.clipTo(a);
  78744. b.invert();
  78745. b.clipTo(a);
  78746. b.invert();
  78747. a.build(b.allPolygons());
  78748. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78749. };
  78750. CSG.prototype.unionInPlace = function (csg) {
  78751. var a = new Node(this.polygons);
  78752. var b = new Node(csg.polygons);
  78753. a.clipTo(b);
  78754. b.clipTo(a);
  78755. b.invert();
  78756. b.clipTo(a);
  78757. b.invert();
  78758. a.build(b.allPolygons());
  78759. this.polygons = a.allPolygons();
  78760. };
  78761. CSG.prototype.subtract = function (csg) {
  78762. var a = new Node(this.clone().polygons);
  78763. var b = new Node(csg.clone().polygons);
  78764. a.invert();
  78765. a.clipTo(b);
  78766. b.clipTo(a);
  78767. b.invert();
  78768. b.clipTo(a);
  78769. b.invert();
  78770. a.build(b.allPolygons());
  78771. a.invert();
  78772. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78773. };
  78774. CSG.prototype.subtractInPlace = function (csg) {
  78775. var a = new Node(this.polygons);
  78776. var b = new Node(csg.polygons);
  78777. a.invert();
  78778. a.clipTo(b);
  78779. b.clipTo(a);
  78780. b.invert();
  78781. b.clipTo(a);
  78782. b.invert();
  78783. a.build(b.allPolygons());
  78784. a.invert();
  78785. this.polygons = a.allPolygons();
  78786. };
  78787. CSG.prototype.intersect = function (csg) {
  78788. var a = new Node(this.clone().polygons);
  78789. var b = new Node(csg.clone().polygons);
  78790. a.invert();
  78791. b.clipTo(a);
  78792. b.invert();
  78793. a.clipTo(b);
  78794. b.clipTo(a);
  78795. a.build(b.allPolygons());
  78796. a.invert();
  78797. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78798. };
  78799. CSG.prototype.intersectInPlace = function (csg) {
  78800. var a = new Node(this.polygons);
  78801. var b = new Node(csg.polygons);
  78802. a.invert();
  78803. b.clipTo(a);
  78804. b.invert();
  78805. a.clipTo(b);
  78806. b.clipTo(a);
  78807. a.build(b.allPolygons());
  78808. a.invert();
  78809. this.polygons = a.allPolygons();
  78810. };
  78811. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  78812. // not modified.
  78813. CSG.prototype.inverse = function () {
  78814. var csg = this.clone();
  78815. csg.inverseInPlace();
  78816. return csg;
  78817. };
  78818. CSG.prototype.inverseInPlace = function () {
  78819. this.polygons.map(function (p) { p.flip(); });
  78820. };
  78821. // This is used to keep meshes transformations so they can be restored
  78822. // when we build back a Babylon Mesh
  78823. // NB : All CSG operations are performed in world coordinates
  78824. CSG.prototype.copyTransformAttributes = function (csg) {
  78825. this.matrix = csg.matrix;
  78826. this.position = csg.position;
  78827. this.rotation = csg.rotation;
  78828. this.scaling = csg.scaling;
  78829. this.rotationQuaternion = csg.rotationQuaternion;
  78830. return this;
  78831. };
  78832. // Build Raw mesh from CSG
  78833. // Coordinates here are in world space
  78834. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  78835. var matrix = this.matrix.clone();
  78836. matrix.invert();
  78837. 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;
  78838. if (keepSubMeshes) {
  78839. // Sort Polygons, since subMeshes are indices range
  78840. polygons.sort(function (a, b) {
  78841. if (a.shared.meshId === b.shared.meshId) {
  78842. return a.shared.subMeshId - b.shared.subMeshId;
  78843. }
  78844. else {
  78845. return a.shared.meshId - b.shared.meshId;
  78846. }
  78847. });
  78848. }
  78849. for (var i = 0, il = polygons.length; i < il; i++) {
  78850. polygon = polygons[i];
  78851. // Building SubMeshes
  78852. if (!subMesh_dict[polygon.shared.meshId]) {
  78853. subMesh_dict[polygon.shared.meshId] = {};
  78854. }
  78855. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  78856. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  78857. indexStart: +Infinity,
  78858. indexEnd: -Infinity,
  78859. materialIndex: polygon.shared.materialIndex
  78860. };
  78861. }
  78862. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  78863. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  78864. polygonIndices[0] = 0;
  78865. polygonIndices[1] = j - 1;
  78866. polygonIndices[2] = j;
  78867. for (var k = 0; k < 3; k++) {
  78868. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  78869. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  78870. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  78871. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  78872. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  78873. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  78874. // Check if 2 points can be merged
  78875. if (!(typeof vertex_idx !== 'undefined' &&
  78876. normals[vertex_idx * 3] === localNormal.x &&
  78877. normals[vertex_idx * 3 + 1] === localNormal.y &&
  78878. normals[vertex_idx * 3 + 2] === localNormal.z &&
  78879. uvs[vertex_idx * 2] === uv.x &&
  78880. uvs[vertex_idx * 2 + 1] === uv.y)) {
  78881. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  78882. uvs.push(uv.x, uv.y);
  78883. normals.push(normal.x, normal.y, normal.z);
  78884. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  78885. }
  78886. indices.push(vertex_idx);
  78887. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  78888. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  78889. currentIndex++;
  78890. }
  78891. }
  78892. }
  78893. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  78894. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  78895. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  78896. mesh.setIndices(indices, null);
  78897. if (keepSubMeshes) {
  78898. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  78899. var materialIndexOffset = 0, materialMaxIndex;
  78900. mesh.subMeshes = new Array();
  78901. for (var m in subMesh_dict) {
  78902. materialMaxIndex = -1;
  78903. for (var sm in subMesh_dict[m]) {
  78904. subMesh_obj = subMesh_dict[m][sm];
  78905. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  78906. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  78907. }
  78908. materialIndexOffset += ++materialMaxIndex;
  78909. }
  78910. }
  78911. return mesh;
  78912. };
  78913. // Build Mesh from CSG taking material and transforms into account
  78914. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  78915. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  78916. mesh.material = material;
  78917. mesh.position.copyFrom(this.position);
  78918. mesh.rotation.copyFrom(this.rotation);
  78919. if (this.rotationQuaternion) {
  78920. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  78921. }
  78922. mesh.scaling.copyFrom(this.scaling);
  78923. mesh.computeWorldMatrix(true);
  78924. return mesh;
  78925. };
  78926. return CSG;
  78927. }());
  78928. BABYLON.CSG = CSG;
  78929. })(BABYLON || (BABYLON = {}));
  78930. //# sourceMappingURL=babylon.csg.js.map
  78931. "use strict";
  78932. var BABYLON;
  78933. (function (BABYLON) {
  78934. var LensFlare = /** @class */ (function () {
  78935. function LensFlare(size, position, color, imgUrl, system) {
  78936. this.size = size;
  78937. this.position = position;
  78938. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  78939. this.color = color || new BABYLON.Color3(1, 1, 1);
  78940. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  78941. this._system = system;
  78942. system.lensFlares.push(this);
  78943. }
  78944. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  78945. return new LensFlare(size, position, color, imgUrl, system);
  78946. };
  78947. LensFlare.prototype.dispose = function () {
  78948. if (this.texture) {
  78949. this.texture.dispose();
  78950. }
  78951. // Remove from scene
  78952. var index = this._system.lensFlares.indexOf(this);
  78953. this._system.lensFlares.splice(index, 1);
  78954. };
  78955. ;
  78956. return LensFlare;
  78957. }());
  78958. BABYLON.LensFlare = LensFlare;
  78959. })(BABYLON || (BABYLON = {}));
  78960. //# sourceMappingURL=babylon.lensFlare.js.map
  78961. "use strict";
  78962. var BABYLON;
  78963. (function (BABYLON) {
  78964. var LensFlareSystem = /** @class */ (function () {
  78965. function LensFlareSystem(name, emitter, scene) {
  78966. this.name = name;
  78967. this.lensFlares = new Array();
  78968. this.borderLimit = 300;
  78969. this.viewportBorder = 0;
  78970. this.layerMask = 0x0FFFFFFF;
  78971. this._vertexBuffers = {};
  78972. this._isEnabled = true;
  78973. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78974. this._emitter = emitter;
  78975. this.id = name;
  78976. scene.lensFlareSystems.push(this);
  78977. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  78978. var engine = scene.getEngine();
  78979. // VBO
  78980. var vertices = [];
  78981. vertices.push(1, 1);
  78982. vertices.push(-1, 1);
  78983. vertices.push(-1, -1);
  78984. vertices.push(1, -1);
  78985. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78986. // Indices
  78987. var indices = [];
  78988. indices.push(0);
  78989. indices.push(1);
  78990. indices.push(2);
  78991. indices.push(0);
  78992. indices.push(2);
  78993. indices.push(3);
  78994. this._indexBuffer = engine.createIndexBuffer(indices);
  78995. // Effects
  78996. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  78997. }
  78998. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  78999. get: function () {
  79000. return this._isEnabled;
  79001. },
  79002. set: function (value) {
  79003. this._isEnabled = value;
  79004. },
  79005. enumerable: true,
  79006. configurable: true
  79007. });
  79008. LensFlareSystem.prototype.getScene = function () {
  79009. return this._scene;
  79010. };
  79011. LensFlareSystem.prototype.getEmitter = function () {
  79012. return this._emitter;
  79013. };
  79014. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  79015. this._emitter = newEmitter;
  79016. };
  79017. LensFlareSystem.prototype.getEmitterPosition = function () {
  79018. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  79019. };
  79020. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  79021. var position = this.getEmitterPosition();
  79022. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  79023. this._positionX = position.x;
  79024. this._positionY = position.y;
  79025. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  79026. if (this.viewportBorder > 0) {
  79027. globalViewport.x -= this.viewportBorder;
  79028. globalViewport.y -= this.viewportBorder;
  79029. globalViewport.width += this.viewportBorder * 2;
  79030. globalViewport.height += this.viewportBorder * 2;
  79031. position.x += this.viewportBorder;
  79032. position.y += this.viewportBorder;
  79033. this._positionX += this.viewportBorder;
  79034. this._positionY += this.viewportBorder;
  79035. }
  79036. if (position.z > 0) {
  79037. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  79038. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  79039. return true;
  79040. }
  79041. return true;
  79042. }
  79043. return false;
  79044. };
  79045. LensFlareSystem.prototype._isVisible = function () {
  79046. if (!this._isEnabled || !this._scene.activeCamera) {
  79047. return false;
  79048. }
  79049. var emitterPosition = this.getEmitterPosition();
  79050. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  79051. var distance = direction.length();
  79052. direction.normalize();
  79053. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  79054. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  79055. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  79056. };
  79057. LensFlareSystem.prototype.render = function () {
  79058. if (!this._effect.isReady() || !this._scene.activeCamera)
  79059. return false;
  79060. var engine = this._scene.getEngine();
  79061. var viewport = this._scene.activeCamera.viewport;
  79062. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  79063. // Position
  79064. if (!this.computeEffectivePosition(globalViewport)) {
  79065. return false;
  79066. }
  79067. // Visibility
  79068. if (!this._isVisible()) {
  79069. return false;
  79070. }
  79071. // Intensity
  79072. var awayX;
  79073. var awayY;
  79074. if (this._positionX < this.borderLimit + globalViewport.x) {
  79075. awayX = this.borderLimit + globalViewport.x - this._positionX;
  79076. }
  79077. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  79078. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  79079. }
  79080. else {
  79081. awayX = 0;
  79082. }
  79083. if (this._positionY < this.borderLimit + globalViewport.y) {
  79084. awayY = this.borderLimit + globalViewport.y - this._positionY;
  79085. }
  79086. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  79087. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  79088. }
  79089. else {
  79090. awayY = 0;
  79091. }
  79092. var away = (awayX > awayY) ? awayX : awayY;
  79093. away -= this.viewportBorder;
  79094. if (away > this.borderLimit) {
  79095. away = this.borderLimit;
  79096. }
  79097. var intensity = 1.0 - (away / this.borderLimit);
  79098. if (intensity < 0) {
  79099. return false;
  79100. }
  79101. if (intensity > 1.0) {
  79102. intensity = 1.0;
  79103. }
  79104. if (this.viewportBorder > 0) {
  79105. globalViewport.x += this.viewportBorder;
  79106. globalViewport.y += this.viewportBorder;
  79107. globalViewport.width -= this.viewportBorder * 2;
  79108. globalViewport.height -= this.viewportBorder * 2;
  79109. this._positionX -= this.viewportBorder;
  79110. this._positionY -= this.viewportBorder;
  79111. }
  79112. // Position
  79113. var centerX = globalViewport.x + globalViewport.width / 2;
  79114. var centerY = globalViewport.y + globalViewport.height / 2;
  79115. var distX = centerX - this._positionX;
  79116. var distY = centerY - this._positionY;
  79117. // Effects
  79118. engine.enableEffect(this._effect);
  79119. engine.setState(false);
  79120. engine.setDepthBuffer(false);
  79121. // VBOs
  79122. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79123. // Flares
  79124. for (var index = 0; index < this.lensFlares.length; index++) {
  79125. var flare = this.lensFlares[index];
  79126. engine.setAlphaMode(flare.alphaMode);
  79127. var x = centerX - (distX * flare.position);
  79128. var y = centerY - (distY * flare.position);
  79129. var cw = flare.size;
  79130. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  79131. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  79132. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  79133. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  79134. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  79135. // Texture
  79136. this._effect.setTexture("textureSampler", flare.texture);
  79137. // Color
  79138. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  79139. // Draw order
  79140. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79141. }
  79142. engine.setDepthBuffer(true);
  79143. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79144. return true;
  79145. };
  79146. LensFlareSystem.prototype.dispose = function () {
  79147. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79148. if (vertexBuffer) {
  79149. vertexBuffer.dispose();
  79150. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79151. }
  79152. if (this._indexBuffer) {
  79153. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79154. this._indexBuffer = null;
  79155. }
  79156. while (this.lensFlares.length) {
  79157. this.lensFlares[0].dispose();
  79158. }
  79159. // Remove from scene
  79160. var index = this._scene.lensFlareSystems.indexOf(this);
  79161. this._scene.lensFlareSystems.splice(index, 1);
  79162. };
  79163. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  79164. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  79165. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  79166. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  79167. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  79168. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  79169. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  79170. var parsedFlare = parsedLensFlareSystem.flares[index];
  79171. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  79172. }
  79173. return lensFlareSystem;
  79174. };
  79175. LensFlareSystem.prototype.serialize = function () {
  79176. var serializationObject = {};
  79177. serializationObject.id = this.id;
  79178. serializationObject.name = this.name;
  79179. serializationObject.emitterId = this.getEmitter().id;
  79180. serializationObject.borderLimit = this.borderLimit;
  79181. serializationObject.flares = [];
  79182. for (var index = 0; index < this.lensFlares.length; index++) {
  79183. var flare = this.lensFlares[index];
  79184. serializationObject.flares.push({
  79185. size: flare.size,
  79186. position: flare.position,
  79187. color: flare.color.asArray(),
  79188. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  79189. });
  79190. }
  79191. return serializationObject;
  79192. };
  79193. return LensFlareSystem;
  79194. }());
  79195. BABYLON.LensFlareSystem = LensFlareSystem;
  79196. })(BABYLON || (BABYLON = {}));
  79197. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  79198. "use strict";
  79199. var BABYLON;
  79200. (function (BABYLON) {
  79201. /**
  79202. * This is a holder class for the physics joint created by the physics plugin.
  79203. * It holds a set of functions to control the underlying joint.
  79204. */
  79205. var PhysicsJoint = /** @class */ (function () {
  79206. function PhysicsJoint(type, jointData) {
  79207. this.type = type;
  79208. this.jointData = jointData;
  79209. jointData.nativeParams = jointData.nativeParams || {};
  79210. }
  79211. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  79212. get: function () {
  79213. return this._physicsJoint;
  79214. },
  79215. set: function (newJoint) {
  79216. if (this._physicsJoint) {
  79217. //remove from the wolrd
  79218. }
  79219. this._physicsJoint = newJoint;
  79220. },
  79221. enumerable: true,
  79222. configurable: true
  79223. });
  79224. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  79225. set: function (physicsPlugin) {
  79226. this._physicsPlugin = physicsPlugin;
  79227. },
  79228. enumerable: true,
  79229. configurable: true
  79230. });
  79231. /**
  79232. * Execute a function that is physics-plugin specific.
  79233. * @param {Function} func the function that will be executed.
  79234. * It accepts two parameters: the physics world and the physics joint.
  79235. */
  79236. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  79237. func(this._physicsPlugin.world, this._physicsJoint);
  79238. };
  79239. //TODO check if the native joints are the same
  79240. //Joint Types
  79241. PhysicsJoint.DistanceJoint = 0;
  79242. PhysicsJoint.HingeJoint = 1;
  79243. PhysicsJoint.BallAndSocketJoint = 2;
  79244. PhysicsJoint.WheelJoint = 3;
  79245. PhysicsJoint.SliderJoint = 4;
  79246. //OIMO
  79247. PhysicsJoint.PrismaticJoint = 5;
  79248. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  79249. PhysicsJoint.UniversalJoint = 6;
  79250. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  79251. //Cannon
  79252. //Similar to a Ball-Joint. Different in params
  79253. PhysicsJoint.PointToPointJoint = 8;
  79254. //Cannon only at the moment
  79255. PhysicsJoint.SpringJoint = 9;
  79256. PhysicsJoint.LockJoint = 10;
  79257. return PhysicsJoint;
  79258. }());
  79259. BABYLON.PhysicsJoint = PhysicsJoint;
  79260. /**
  79261. * A class representing a physics distance joint.
  79262. */
  79263. var DistanceJoint = /** @class */ (function (_super) {
  79264. __extends(DistanceJoint, _super);
  79265. function DistanceJoint(jointData) {
  79266. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  79267. }
  79268. /**
  79269. * Update the predefined distance.
  79270. */
  79271. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  79272. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  79273. };
  79274. return DistanceJoint;
  79275. }(PhysicsJoint));
  79276. BABYLON.DistanceJoint = DistanceJoint;
  79277. var MotorEnabledJoint = /** @class */ (function (_super) {
  79278. __extends(MotorEnabledJoint, _super);
  79279. function MotorEnabledJoint(type, jointData) {
  79280. return _super.call(this, type, jointData) || this;
  79281. }
  79282. /**
  79283. * Set the motor values.
  79284. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79285. * @param {number} force the force to apply
  79286. * @param {number} maxForce max force for this motor.
  79287. */
  79288. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  79289. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79290. };
  79291. /**
  79292. * Set the motor's limits.
  79293. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79294. */
  79295. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79296. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79297. };
  79298. return MotorEnabledJoint;
  79299. }(PhysicsJoint));
  79300. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  79301. /**
  79302. * This class represents a single hinge physics joint
  79303. */
  79304. var HingeJoint = /** @class */ (function (_super) {
  79305. __extends(HingeJoint, _super);
  79306. function HingeJoint(jointData) {
  79307. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  79308. }
  79309. /**
  79310. * Set the motor values.
  79311. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79312. * @param {number} force the force to apply
  79313. * @param {number} maxForce max force for this motor.
  79314. */
  79315. HingeJoint.prototype.setMotor = function (force, maxForce) {
  79316. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79317. };
  79318. /**
  79319. * Set the motor's limits.
  79320. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79321. */
  79322. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79323. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79324. };
  79325. return HingeJoint;
  79326. }(MotorEnabledJoint));
  79327. BABYLON.HingeJoint = HingeJoint;
  79328. /**
  79329. * This class represents a dual hinge physics joint (same as wheel joint)
  79330. */
  79331. var Hinge2Joint = /** @class */ (function (_super) {
  79332. __extends(Hinge2Joint, _super);
  79333. function Hinge2Joint(jointData) {
  79334. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  79335. }
  79336. /**
  79337. * Set the motor values.
  79338. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79339. * @param {number} force the force to apply
  79340. * @param {number} maxForce max force for this motor.
  79341. * @param {motorIndex} the motor's index, 0 or 1.
  79342. */
  79343. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  79344. if (motorIndex === void 0) { motorIndex = 0; }
  79345. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  79346. };
  79347. /**
  79348. * Set the motor limits.
  79349. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79350. * @param {number} upperLimit the upper limit
  79351. * @param {number} lowerLimit lower limit
  79352. * @param {motorIndex} the motor's index, 0 or 1.
  79353. */
  79354. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  79355. if (motorIndex === void 0) { motorIndex = 0; }
  79356. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  79357. };
  79358. return Hinge2Joint;
  79359. }(MotorEnabledJoint));
  79360. BABYLON.Hinge2Joint = Hinge2Joint;
  79361. })(BABYLON || (BABYLON = {}));
  79362. //# sourceMappingURL=babylon.physicsJoint.js.map
  79363. "use strict";
  79364. var BABYLON;
  79365. (function (BABYLON) {
  79366. var PhysicsImpostor = /** @class */ (function () {
  79367. function PhysicsImpostor(object, type, _options, _scene) {
  79368. if (_options === void 0) { _options = { mass: 0 }; }
  79369. var _this = this;
  79370. this.object = object;
  79371. this.type = type;
  79372. this._options = _options;
  79373. this._scene = _scene;
  79374. this._bodyUpdateRequired = false;
  79375. this._onBeforePhysicsStepCallbacks = new Array();
  79376. this._onAfterPhysicsStepCallbacks = new Array();
  79377. this._onPhysicsCollideCallbacks = [];
  79378. this._deltaPosition = BABYLON.Vector3.Zero();
  79379. this._isDisposed = false;
  79380. //temp variables for parent rotation calculations
  79381. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  79382. this._tmpQuat = new BABYLON.Quaternion();
  79383. this._tmpQuat2 = new BABYLON.Quaternion();
  79384. /**
  79385. * this function is executed by the physics engine.
  79386. */
  79387. this.beforeStep = function () {
  79388. if (!_this._physicsEngine) {
  79389. return;
  79390. }
  79391. _this.object.translate(_this._deltaPosition, -1);
  79392. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  79393. _this.object.computeWorldMatrix(false);
  79394. if (_this.object.parent && _this.object.rotationQuaternion) {
  79395. _this.getParentsRotation();
  79396. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  79397. }
  79398. else {
  79399. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  79400. }
  79401. if (!_this._options.disableBidirectionalTransformation) {
  79402. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  79403. }
  79404. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  79405. func(_this);
  79406. });
  79407. };
  79408. /**
  79409. * this function is executed by the physics engine.
  79410. */
  79411. this.afterStep = function () {
  79412. if (!_this._physicsEngine) {
  79413. return;
  79414. }
  79415. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  79416. func(_this);
  79417. });
  79418. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  79419. // object has now its world rotation. needs to be converted to local.
  79420. if (_this.object.parent && _this.object.rotationQuaternion) {
  79421. _this.getParentsRotation();
  79422. _this._tmpQuat.conjugateInPlace();
  79423. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  79424. }
  79425. // take the position set and make it the absolute position of this object.
  79426. _this.object.setAbsolutePosition(_this.object.position);
  79427. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  79428. _this.object.translate(_this._deltaPosition, 1);
  79429. };
  79430. /**
  79431. * Legacy collision detection event support
  79432. */
  79433. this.onCollideEvent = null;
  79434. //event and body object due to cannon's event-based architecture.
  79435. this.onCollide = function (e) {
  79436. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  79437. return;
  79438. }
  79439. if (!_this._physicsEngine) {
  79440. return;
  79441. }
  79442. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  79443. if (otherImpostor) {
  79444. // Legacy collision detection event support
  79445. if (_this.onCollideEvent) {
  79446. _this.onCollideEvent(_this, otherImpostor);
  79447. }
  79448. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  79449. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  79450. }).forEach(function (obj) {
  79451. obj.callback(_this, otherImpostor);
  79452. });
  79453. }
  79454. };
  79455. //sanity check!
  79456. if (!this.object) {
  79457. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  79458. return;
  79459. }
  79460. //legacy support for old syntax.
  79461. if (!this._scene && object.getScene) {
  79462. this._scene = object.getScene();
  79463. }
  79464. if (!this._scene) {
  79465. return;
  79466. }
  79467. this._physicsEngine = this._scene.getPhysicsEngine();
  79468. if (!this._physicsEngine) {
  79469. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  79470. }
  79471. else {
  79472. //set the object's quaternion, if not set
  79473. if (!this.object.rotationQuaternion) {
  79474. if (this.object.rotation) {
  79475. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  79476. }
  79477. else {
  79478. this.object.rotationQuaternion = new BABYLON.Quaternion();
  79479. }
  79480. }
  79481. //default options params
  79482. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  79483. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  79484. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  79485. this._joints = [];
  79486. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  79487. if (!this.object.parent || this._options.ignoreParent) {
  79488. this._init();
  79489. }
  79490. else if (this.object.parent.physicsImpostor) {
  79491. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  79492. }
  79493. }
  79494. }
  79495. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  79496. get: function () {
  79497. return this._isDisposed;
  79498. },
  79499. enumerable: true,
  79500. configurable: true
  79501. });
  79502. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  79503. get: function () {
  79504. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  79505. },
  79506. set: function (value) {
  79507. this.setMass(value);
  79508. },
  79509. enumerable: true,
  79510. configurable: true
  79511. });
  79512. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  79513. get: function () {
  79514. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  79515. },
  79516. set: function (value) {
  79517. if (!this._physicsEngine) {
  79518. return;
  79519. }
  79520. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  79521. },
  79522. enumerable: true,
  79523. configurable: true
  79524. });
  79525. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  79526. get: function () {
  79527. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  79528. },
  79529. set: function (value) {
  79530. if (!this._physicsEngine) {
  79531. return;
  79532. }
  79533. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  79534. },
  79535. enumerable: true,
  79536. configurable: true
  79537. });
  79538. /**
  79539. * This function will completly initialize this impostor.
  79540. * It will create a new body - but only if this mesh has no parent.
  79541. * If it has, this impostor will not be used other than to define the impostor
  79542. * of the child mesh.
  79543. */
  79544. PhysicsImpostor.prototype._init = function () {
  79545. if (!this._physicsEngine) {
  79546. return;
  79547. }
  79548. this._physicsEngine.removeImpostor(this);
  79549. this.physicsBody = null;
  79550. this._parent = this._parent || this._getPhysicsParent();
  79551. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  79552. this._physicsEngine.addImpostor(this);
  79553. }
  79554. };
  79555. PhysicsImpostor.prototype._getPhysicsParent = function () {
  79556. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  79557. var parentMesh = this.object.parent;
  79558. return parentMesh.physicsImpostor;
  79559. }
  79560. return null;
  79561. };
  79562. /**
  79563. * Should a new body be generated.
  79564. */
  79565. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  79566. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  79567. };
  79568. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  79569. this.forceUpdate();
  79570. };
  79571. /**
  79572. * Force a regeneration of this or the parent's impostor's body.
  79573. * Use under cautious - This will remove all joints already implemented.
  79574. */
  79575. PhysicsImpostor.prototype.forceUpdate = function () {
  79576. this._init();
  79577. if (this.parent && !this._options.ignoreParent) {
  79578. this.parent.forceUpdate();
  79579. }
  79580. };
  79581. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  79582. /*public get mesh(): AbstractMesh {
  79583. return this._mesh;
  79584. }*/
  79585. /**
  79586. * Gets the body that holds this impostor. Either its own, or its parent.
  79587. */
  79588. get: function () {
  79589. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  79590. },
  79591. /**
  79592. * Set the physics body. Used mainly by the physics engine/plugin
  79593. */
  79594. set: function (physicsBody) {
  79595. if (this._physicsBody && this._physicsEngine) {
  79596. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  79597. }
  79598. this._physicsBody = physicsBody;
  79599. this.resetUpdateFlags();
  79600. },
  79601. enumerable: true,
  79602. configurable: true
  79603. });
  79604. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  79605. get: function () {
  79606. return !this._options.ignoreParent && this._parent ? this._parent : null;
  79607. },
  79608. set: function (value) {
  79609. this._parent = value;
  79610. },
  79611. enumerable: true,
  79612. configurable: true
  79613. });
  79614. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  79615. this._bodyUpdateRequired = false;
  79616. };
  79617. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  79618. if (this.object.getBoundingInfo) {
  79619. var q = this.object.rotationQuaternion;
  79620. //reset rotation
  79621. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  79622. //calculate the world matrix with no rotation
  79623. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  79624. var boundingInfo = this.object.getBoundingInfo();
  79625. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  79626. //bring back the rotation
  79627. this.object.rotationQuaternion = q;
  79628. //calculate the world matrix with the new rotation
  79629. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  79630. return size;
  79631. }
  79632. else {
  79633. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  79634. }
  79635. };
  79636. PhysicsImpostor.prototype.getObjectCenter = function () {
  79637. if (this.object.getBoundingInfo) {
  79638. var boundingInfo = this.object.getBoundingInfo();
  79639. return boundingInfo.boundingBox.centerWorld;
  79640. }
  79641. else {
  79642. return this.object.position;
  79643. }
  79644. };
  79645. /**
  79646. * Get a specific parametes from the options parameter.
  79647. */
  79648. PhysicsImpostor.prototype.getParam = function (paramName) {
  79649. return this._options[paramName];
  79650. };
  79651. /**
  79652. * Sets a specific parameter in the options given to the physics plugin
  79653. */
  79654. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  79655. this._options[paramName] = value;
  79656. this._bodyUpdateRequired = true;
  79657. };
  79658. /**
  79659. * Specifically change the body's mass option. Won't recreate the physics body object
  79660. */
  79661. PhysicsImpostor.prototype.setMass = function (mass) {
  79662. if (this.getParam("mass") !== mass) {
  79663. this.setParam("mass", mass);
  79664. }
  79665. if (this._physicsEngine) {
  79666. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  79667. }
  79668. };
  79669. PhysicsImpostor.prototype.getLinearVelocity = function () {
  79670. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  79671. };
  79672. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  79673. if (this._physicsEngine) {
  79674. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  79675. }
  79676. };
  79677. PhysicsImpostor.prototype.getAngularVelocity = function () {
  79678. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  79679. };
  79680. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  79681. if (this._physicsEngine) {
  79682. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  79683. }
  79684. };
  79685. /**
  79686. * Execute a function with the physics plugin native code.
  79687. * Provide a function the will have two variables - the world object and the physics body object.
  79688. */
  79689. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  79690. if (this._physicsEngine) {
  79691. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  79692. }
  79693. };
  79694. /**
  79695. * Register a function that will be executed before the physics world is stepping forward.
  79696. */
  79697. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  79698. this._onBeforePhysicsStepCallbacks.push(func);
  79699. };
  79700. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  79701. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  79702. if (index > -1) {
  79703. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  79704. }
  79705. else {
  79706. BABYLON.Tools.Warn("Function to remove was not found");
  79707. }
  79708. };
  79709. /**
  79710. * Register a function that will be executed after the physics step
  79711. */
  79712. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  79713. this._onAfterPhysicsStepCallbacks.push(func);
  79714. };
  79715. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  79716. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  79717. if (index > -1) {
  79718. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  79719. }
  79720. else {
  79721. BABYLON.Tools.Warn("Function to remove was not found");
  79722. }
  79723. };
  79724. /**
  79725. * register a function that will be executed when this impostor collides against a different body.
  79726. */
  79727. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  79728. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  79729. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  79730. };
  79731. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  79732. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  79733. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  79734. if (index > -1) {
  79735. this._onPhysicsCollideCallbacks.splice(index, 1);
  79736. }
  79737. else {
  79738. BABYLON.Tools.Warn("Function to remove was not found");
  79739. }
  79740. };
  79741. PhysicsImpostor.prototype.getParentsRotation = function () {
  79742. var parent = this.object.parent;
  79743. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  79744. while (parent) {
  79745. if (parent.rotationQuaternion) {
  79746. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  79747. }
  79748. else {
  79749. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  79750. }
  79751. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  79752. parent = parent.parent;
  79753. }
  79754. return this._tmpQuat;
  79755. };
  79756. /**
  79757. * Apply a force
  79758. */
  79759. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  79760. if (this._physicsEngine) {
  79761. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  79762. }
  79763. return this;
  79764. };
  79765. /**
  79766. * Apply an impulse
  79767. */
  79768. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  79769. if (this._physicsEngine) {
  79770. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  79771. }
  79772. return this;
  79773. };
  79774. /**
  79775. * A help function to create a joint.
  79776. */
  79777. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  79778. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  79779. this.addJoint(otherImpostor, joint);
  79780. return this;
  79781. };
  79782. /**
  79783. * Add a joint to this impostor with a different impostor.
  79784. */
  79785. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  79786. this._joints.push({
  79787. otherImpostor: otherImpostor,
  79788. joint: joint
  79789. });
  79790. if (this._physicsEngine) {
  79791. this._physicsEngine.addJoint(this, otherImpostor, joint);
  79792. }
  79793. return this;
  79794. };
  79795. /**
  79796. * Will keep this body still, in a sleep mode.
  79797. */
  79798. PhysicsImpostor.prototype.sleep = function () {
  79799. if (this._physicsEngine) {
  79800. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  79801. }
  79802. return this;
  79803. };
  79804. /**
  79805. * Wake the body up.
  79806. */
  79807. PhysicsImpostor.prototype.wakeUp = function () {
  79808. if (this._physicsEngine) {
  79809. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  79810. }
  79811. return this;
  79812. };
  79813. PhysicsImpostor.prototype.clone = function (newObject) {
  79814. if (!newObject)
  79815. return null;
  79816. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  79817. };
  79818. PhysicsImpostor.prototype.dispose = function () {
  79819. var _this = this;
  79820. //no dispose if no physics engine is available.
  79821. if (!this._physicsEngine) {
  79822. return;
  79823. }
  79824. this._joints.forEach(function (j) {
  79825. if (_this._physicsEngine) {
  79826. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  79827. }
  79828. });
  79829. //dispose the physics body
  79830. this._physicsEngine.removeImpostor(this);
  79831. if (this.parent) {
  79832. this.parent.forceUpdate();
  79833. }
  79834. else {
  79835. /*this._object.getChildMeshes().forEach(function(mesh) {
  79836. if (mesh.physicsImpostor) {
  79837. if (disposeChildren) {
  79838. mesh.physicsImpostor.dispose();
  79839. mesh.physicsImpostor = null;
  79840. }
  79841. }
  79842. })*/
  79843. }
  79844. this._isDisposed = true;
  79845. };
  79846. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  79847. this._deltaPosition.copyFrom(position);
  79848. };
  79849. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  79850. if (!this._deltaRotation) {
  79851. this._deltaRotation = new BABYLON.Quaternion();
  79852. }
  79853. this._deltaRotation.copyFrom(rotation);
  79854. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  79855. };
  79856. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  79857. if (this._physicsEngine) {
  79858. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  79859. }
  79860. return this;
  79861. };
  79862. PhysicsImpostor.prototype.getRadius = function () {
  79863. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  79864. };
  79865. /**
  79866. * Sync a bone with this impostor
  79867. * @param bone The bone to sync to the impostor.
  79868. * @param boneMesh The mesh that the bone is influencing.
  79869. * @param jointPivot The pivot of the joint / bone in local space.
  79870. * @param distToJoint Optional distance from the impostor to the joint.
  79871. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  79872. */
  79873. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  79874. var tempVec = PhysicsImpostor._tmpVecs[0];
  79875. var mesh = this.object;
  79876. if (mesh.rotationQuaternion) {
  79877. if (adjustRotation) {
  79878. var tempQuat = PhysicsImpostor._tmpQuat;
  79879. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  79880. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  79881. }
  79882. else {
  79883. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  79884. }
  79885. }
  79886. tempVec.x = 0;
  79887. tempVec.y = 0;
  79888. tempVec.z = 0;
  79889. if (jointPivot) {
  79890. tempVec.x = jointPivot.x;
  79891. tempVec.y = jointPivot.y;
  79892. tempVec.z = jointPivot.z;
  79893. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  79894. if (distToJoint === undefined || distToJoint === null) {
  79895. distToJoint = jointPivot.length();
  79896. }
  79897. tempVec.x *= distToJoint;
  79898. tempVec.y *= distToJoint;
  79899. tempVec.z *= distToJoint;
  79900. }
  79901. if (bone.getParent()) {
  79902. tempVec.addInPlace(mesh.getAbsolutePosition());
  79903. bone.setAbsolutePosition(tempVec, boneMesh);
  79904. }
  79905. else {
  79906. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  79907. boneMesh.position.x -= tempVec.x;
  79908. boneMesh.position.y -= tempVec.y;
  79909. boneMesh.position.z -= tempVec.z;
  79910. }
  79911. };
  79912. /**
  79913. * Sync impostor to a bone
  79914. * @param bone The bone that the impostor will be synced to.
  79915. * @param boneMesh The mesh that the bone is influencing.
  79916. * @param jointPivot The pivot of the joint / bone in local space.
  79917. * @param distToJoint Optional distance from the impostor to the joint.
  79918. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  79919. * @param boneAxis Optional vector3 axis the bone is aligned with
  79920. */
  79921. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  79922. var mesh = this.object;
  79923. if (mesh.rotationQuaternion) {
  79924. if (adjustRotation) {
  79925. var tempQuat = PhysicsImpostor._tmpQuat;
  79926. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  79927. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  79928. }
  79929. else {
  79930. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  79931. }
  79932. }
  79933. var pos = PhysicsImpostor._tmpVecs[0];
  79934. var boneDir = PhysicsImpostor._tmpVecs[1];
  79935. if (!boneAxis) {
  79936. boneAxis = PhysicsImpostor._tmpVecs[2];
  79937. boneAxis.x = 0;
  79938. boneAxis.y = 1;
  79939. boneAxis.z = 0;
  79940. }
  79941. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  79942. bone.getAbsolutePositionToRef(boneMesh, pos);
  79943. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  79944. distToJoint = jointPivot.length();
  79945. }
  79946. if (distToJoint !== undefined && distToJoint !== null) {
  79947. pos.x += boneDir.x * distToJoint;
  79948. pos.y += boneDir.y * distToJoint;
  79949. pos.z += boneDir.z * distToJoint;
  79950. }
  79951. mesh.setAbsolutePosition(pos);
  79952. };
  79953. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  79954. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  79955. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79956. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  79957. //Impostor types
  79958. PhysicsImpostor.NoImpostor = 0;
  79959. PhysicsImpostor.SphereImpostor = 1;
  79960. PhysicsImpostor.BoxImpostor = 2;
  79961. PhysicsImpostor.PlaneImpostor = 3;
  79962. PhysicsImpostor.MeshImpostor = 4;
  79963. PhysicsImpostor.CylinderImpostor = 7;
  79964. PhysicsImpostor.ParticleImpostor = 8;
  79965. PhysicsImpostor.HeightmapImpostor = 9;
  79966. return PhysicsImpostor;
  79967. }());
  79968. BABYLON.PhysicsImpostor = PhysicsImpostor;
  79969. })(BABYLON || (BABYLON = {}));
  79970. //# sourceMappingURL=babylon.physicsImpostor.js.map
  79971. "use strict";
  79972. var BABYLON;
  79973. (function (BABYLON) {
  79974. var PhysicsEngine = /** @class */ (function () {
  79975. function PhysicsEngine(gravity, _physicsPlugin) {
  79976. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  79977. this._physicsPlugin = _physicsPlugin;
  79978. //new methods and parameters
  79979. this._impostors = [];
  79980. this._joints = [];
  79981. if (!this._physicsPlugin.isSupported()) {
  79982. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  79983. + "Please make sure it is included.");
  79984. }
  79985. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  79986. this.setGravity(gravity);
  79987. this.setTimeStep();
  79988. }
  79989. PhysicsEngine.prototype.setGravity = function (gravity) {
  79990. this.gravity = gravity;
  79991. this._physicsPlugin.setGravity(this.gravity);
  79992. };
  79993. /**
  79994. * Set the time step of the physics engine.
  79995. * default is 1/60.
  79996. * To slow it down, enter 1/600 for example.
  79997. * To speed it up, 1/30
  79998. * @param {number} newTimeStep the new timestep to apply to this world.
  79999. */
  80000. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  80001. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  80002. this._physicsPlugin.setTimeStep(newTimeStep);
  80003. };
  80004. /**
  80005. * Get the time step of the physics engine.
  80006. */
  80007. PhysicsEngine.prototype.getTimeStep = function () {
  80008. return this._physicsPlugin.getTimeStep();
  80009. };
  80010. PhysicsEngine.prototype.dispose = function () {
  80011. this._impostors.forEach(function (impostor) {
  80012. impostor.dispose();
  80013. });
  80014. this._physicsPlugin.dispose();
  80015. };
  80016. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  80017. return this._physicsPlugin.name;
  80018. };
  80019. /**
  80020. * Adding a new impostor for the impostor tracking.
  80021. * This will be done by the impostor itself.
  80022. * @param {PhysicsImpostor} impostor the impostor to add
  80023. */
  80024. PhysicsEngine.prototype.addImpostor = function (impostor) {
  80025. impostor.uniqueId = this._impostors.push(impostor);
  80026. //if no parent, generate the body
  80027. if (!impostor.parent) {
  80028. this._physicsPlugin.generatePhysicsBody(impostor);
  80029. }
  80030. };
  80031. /**
  80032. * Remove an impostor from the engine.
  80033. * This impostor and its mesh will not longer be updated by the physics engine.
  80034. * @param {PhysicsImpostor} impostor the impostor to remove
  80035. */
  80036. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  80037. var index = this._impostors.indexOf(impostor);
  80038. if (index > -1) {
  80039. var removed = this._impostors.splice(index, 1);
  80040. //Is it needed?
  80041. if (removed.length) {
  80042. //this will also remove it from the world.
  80043. removed[0].physicsBody = null;
  80044. }
  80045. }
  80046. };
  80047. /**
  80048. * Add a joint to the physics engine
  80049. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  80050. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  80051. * @param {PhysicsJoint} the joint that will connect both impostors.
  80052. */
  80053. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  80054. var impostorJoint = {
  80055. mainImpostor: mainImpostor,
  80056. connectedImpostor: connectedImpostor,
  80057. joint: joint
  80058. };
  80059. joint.physicsPlugin = this._physicsPlugin;
  80060. this._joints.push(impostorJoint);
  80061. this._physicsPlugin.generateJoint(impostorJoint);
  80062. };
  80063. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  80064. var matchingJoints = this._joints.filter(function (impostorJoint) {
  80065. return (impostorJoint.connectedImpostor === connectedImpostor
  80066. && impostorJoint.joint === joint
  80067. && impostorJoint.mainImpostor === mainImpostor);
  80068. });
  80069. if (matchingJoints.length) {
  80070. this._physicsPlugin.removeJoint(matchingJoints[0]);
  80071. //TODO remove it from the list as well
  80072. }
  80073. };
  80074. /**
  80075. * Called by the scene. no need to call it.
  80076. */
  80077. PhysicsEngine.prototype._step = function (delta) {
  80078. var _this = this;
  80079. //check if any mesh has no body / requires an update
  80080. this._impostors.forEach(function (impostor) {
  80081. if (impostor.isBodyInitRequired()) {
  80082. _this._physicsPlugin.generatePhysicsBody(impostor);
  80083. }
  80084. });
  80085. if (delta > 0.1) {
  80086. delta = 0.1;
  80087. }
  80088. else if (delta <= 0) {
  80089. delta = 1.0 / 60.0;
  80090. }
  80091. this._physicsPlugin.executeStep(delta, this._impostors);
  80092. };
  80093. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  80094. return this._physicsPlugin;
  80095. };
  80096. PhysicsEngine.prototype.getImpostors = function () {
  80097. return this._impostors;
  80098. };
  80099. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  80100. for (var i = 0; i < this._impostors.length; ++i) {
  80101. if (this._impostors[i].object === object) {
  80102. return this._impostors[i];
  80103. }
  80104. }
  80105. return null;
  80106. };
  80107. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  80108. for (var i = 0; i < this._impostors.length; ++i) {
  80109. if (this._impostors[i].physicsBody === body) {
  80110. return this._impostors[i];
  80111. }
  80112. }
  80113. return null;
  80114. };
  80115. // Statics
  80116. PhysicsEngine.Epsilon = 0.001;
  80117. return PhysicsEngine;
  80118. }());
  80119. BABYLON.PhysicsEngine = PhysicsEngine;
  80120. })(BABYLON || (BABYLON = {}));
  80121. //# sourceMappingURL=babylon.physicsEngine.js.map
  80122. "use strict";
  80123. var BABYLON;
  80124. (function (BABYLON) {
  80125. var PhysicsHelper = /** @class */ (function () {
  80126. function PhysicsHelper(scene) {
  80127. this._scene = scene;
  80128. this._physicsEngine = this._scene.getPhysicsEngine();
  80129. if (!this._physicsEngine) {
  80130. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  80131. }
  80132. }
  80133. /**
  80134. * @param {Vector3} origin the origin of the explosion
  80135. * @param {number} radius the explosion radius
  80136. * @param {number} strength the explosion strength
  80137. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80138. */
  80139. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  80140. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80141. if (!this._physicsEngine) {
  80142. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  80143. return null;
  80144. }
  80145. var impostors = this._physicsEngine.getImpostors();
  80146. if (impostors.length === 0) {
  80147. return null;
  80148. }
  80149. var event = new PhysicsRadialExplosionEvent(this._scene);
  80150. impostors.forEach(function (impostor) {
  80151. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80152. if (!impostorForceAndContactPoint) {
  80153. return;
  80154. }
  80155. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80156. });
  80157. event.dispose(false);
  80158. return event;
  80159. };
  80160. /**
  80161. * @param {Vector3} origin the origin of the explosion
  80162. * @param {number} radius the explosion radius
  80163. * @param {number} strength the explosion strength
  80164. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80165. */
  80166. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  80167. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80168. if (!this._physicsEngine) {
  80169. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80170. return null;
  80171. }
  80172. var impostors = this._physicsEngine.getImpostors();
  80173. if (impostors.length === 0) {
  80174. return null;
  80175. }
  80176. var event = new PhysicsRadialExplosionEvent(this._scene);
  80177. impostors.forEach(function (impostor) {
  80178. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80179. if (!impostorForceAndContactPoint) {
  80180. return;
  80181. }
  80182. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80183. });
  80184. event.dispose(false);
  80185. return event;
  80186. };
  80187. /**
  80188. * @param {Vector3} origin the origin of the explosion
  80189. * @param {number} radius the explosion radius
  80190. * @param {number} strength the explosion strength
  80191. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80192. */
  80193. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  80194. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80195. if (!this._physicsEngine) {
  80196. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80197. return null;
  80198. }
  80199. var impostors = this._physicsEngine.getImpostors();
  80200. if (impostors.length === 0) {
  80201. return null;
  80202. }
  80203. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  80204. event.dispose(false);
  80205. return event;
  80206. };
  80207. /**
  80208. * @param {Vector3} origin the origin of the updraft
  80209. * @param {number} radius the radius of the updraft
  80210. * @param {number} strength the strength of the updraft
  80211. * @param {number} height the height of the updraft
  80212. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  80213. */
  80214. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  80215. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  80216. if (!this._physicsEngine) {
  80217. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80218. return null;
  80219. }
  80220. if (this._physicsEngine.getImpostors().length === 0) {
  80221. return null;
  80222. }
  80223. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  80224. event.dispose(false);
  80225. return event;
  80226. };
  80227. /**
  80228. * @param {Vector3} origin the of the vortex
  80229. * @param {number} radius the radius of the vortex
  80230. * @param {number} strength the strength of the vortex
  80231. * @param {number} height the height of the vortex
  80232. */
  80233. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  80234. if (!this._physicsEngine) {
  80235. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80236. return null;
  80237. }
  80238. if (this._physicsEngine.getImpostors().length === 0) {
  80239. return null;
  80240. }
  80241. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  80242. event.dispose(false);
  80243. return event;
  80244. };
  80245. return PhysicsHelper;
  80246. }());
  80247. BABYLON.PhysicsHelper = PhysicsHelper;
  80248. /***** Radial explosion *****/
  80249. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  80250. function PhysicsRadialExplosionEvent(scene) {
  80251. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  80252. this._rays = [];
  80253. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  80254. this._scene = scene;
  80255. }
  80256. /**
  80257. * Returns the data related to the radial explosion event (sphere & rays).
  80258. * @returns {PhysicsRadialExplosionEventData}
  80259. */
  80260. PhysicsRadialExplosionEvent.prototype.getData = function () {
  80261. this._dataFetched = true;
  80262. return {
  80263. sphere: this._sphere,
  80264. rays: this._rays,
  80265. };
  80266. };
  80267. /**
  80268. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  80269. * @param impostor
  80270. * @param {Vector3} origin the origin of the explosion
  80271. * @param {number} radius the explosion radius
  80272. * @param {number} strength the explosion strength
  80273. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  80274. * @returns {Nullable<PhysicsForceAndContactPoint>}
  80275. */
  80276. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  80277. if (impostor.mass === 0) {
  80278. return null;
  80279. }
  80280. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  80281. return null;
  80282. }
  80283. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  80284. return null;
  80285. }
  80286. var impostorObjectCenter = impostor.getObjectCenter();
  80287. var direction = impostorObjectCenter.subtract(origin);
  80288. var ray = new BABYLON.Ray(origin, direction, radius);
  80289. this._rays.push(ray);
  80290. var hit = ray.intersectsMesh(impostor.object);
  80291. var contactPoint = hit.pickedPoint;
  80292. if (!contactPoint) {
  80293. return null;
  80294. }
  80295. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  80296. if (distanceFromOrigin > radius) {
  80297. return null;
  80298. }
  80299. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  80300. ? strength
  80301. : strength * (1 - (distanceFromOrigin / radius));
  80302. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  80303. return { force: force, contactPoint: contactPoint };
  80304. };
  80305. /**
  80306. * Disposes the sphere.
  80307. * @param {bolean} force
  80308. */
  80309. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  80310. var _this = this;
  80311. if (force === void 0) { force = true; }
  80312. if (force) {
  80313. this._sphere.dispose();
  80314. }
  80315. else {
  80316. setTimeout(function () {
  80317. if (!_this._dataFetched) {
  80318. _this._sphere.dispose();
  80319. }
  80320. }, 0);
  80321. }
  80322. };
  80323. /*** Helpers ***/
  80324. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  80325. if (!this._sphere) {
  80326. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  80327. this._sphere.isVisible = false;
  80328. }
  80329. };
  80330. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  80331. var impostorObject = impostor.object;
  80332. this._prepareSphere();
  80333. this._sphere.position = origin;
  80334. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  80335. this._sphere._updateBoundingInfo();
  80336. this._sphere.computeWorldMatrix(true);
  80337. return this._sphere.intersectsMesh(impostorObject, true);
  80338. };
  80339. return PhysicsRadialExplosionEvent;
  80340. }());
  80341. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  80342. /***** Gravitational Field *****/
  80343. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  80344. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  80345. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80346. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80347. this._physicsHelper = physicsHelper;
  80348. this._scene = scene;
  80349. this._origin = origin;
  80350. this._radius = radius;
  80351. this._strength = strength;
  80352. this._falloff = falloff;
  80353. this._tickCallback = this._tick.bind(this);
  80354. }
  80355. /**
  80356. * Returns the data related to the gravitational field event (sphere).
  80357. * @returns {PhysicsGravitationalFieldEventData}
  80358. */
  80359. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  80360. this._dataFetched = true;
  80361. return {
  80362. sphere: this._sphere,
  80363. };
  80364. };
  80365. /**
  80366. * Enables the gravitational field.
  80367. */
  80368. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  80369. this._tickCallback.call(this);
  80370. this._scene.registerBeforeRender(this._tickCallback);
  80371. };
  80372. /**
  80373. * Disables the gravitational field.
  80374. */
  80375. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  80376. this._scene.unregisterBeforeRender(this._tickCallback);
  80377. };
  80378. /**
  80379. * Disposes the sphere.
  80380. * @param {bolean} force
  80381. */
  80382. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  80383. var _this = this;
  80384. if (force === void 0) { force = true; }
  80385. if (force) {
  80386. this._sphere.dispose();
  80387. }
  80388. else {
  80389. setTimeout(function () {
  80390. if (!_this._dataFetched) {
  80391. _this._sphere.dispose();
  80392. }
  80393. }, 0);
  80394. }
  80395. };
  80396. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  80397. // Since the params won't change, we fetch the event only once
  80398. if (this._sphere) {
  80399. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80400. }
  80401. else {
  80402. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80403. if (radialExplosionEvent) {
  80404. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  80405. }
  80406. }
  80407. };
  80408. return PhysicsGravitationalFieldEvent;
  80409. }());
  80410. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  80411. /***** Updraft *****/
  80412. var PhysicsUpdraftEvent = /** @class */ (function () {
  80413. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  80414. this._scene = _scene;
  80415. this._origin = _origin;
  80416. this._radius = _radius;
  80417. this._strength = _strength;
  80418. this._height = _height;
  80419. this._updraftMode = _updraftMode;
  80420. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  80421. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  80422. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  80423. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80424. this._physicsEngine = this._scene.getPhysicsEngine();
  80425. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  80426. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  80427. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  80428. this._originDirection = this._origin.subtract(this._originTop).normalize();
  80429. }
  80430. this._tickCallback = this._tick.bind(this);
  80431. }
  80432. /**
  80433. * Returns the data related to the updraft event (cylinder).
  80434. * @returns {PhysicsUpdraftEventData}
  80435. */
  80436. PhysicsUpdraftEvent.prototype.getData = function () {
  80437. this._dataFetched = true;
  80438. return {
  80439. cylinder: this._cylinder,
  80440. };
  80441. };
  80442. /**
  80443. * Enables the updraft.
  80444. */
  80445. PhysicsUpdraftEvent.prototype.enable = function () {
  80446. this._tickCallback.call(this);
  80447. this._scene.registerBeforeRender(this._tickCallback);
  80448. };
  80449. /**
  80450. * Disables the cortex.
  80451. */
  80452. PhysicsUpdraftEvent.prototype.disable = function () {
  80453. this._scene.unregisterBeforeRender(this._tickCallback);
  80454. };
  80455. /**
  80456. * Disposes the sphere.
  80457. * @param {bolean} force
  80458. */
  80459. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  80460. var _this = this;
  80461. if (force === void 0) { force = true; }
  80462. if (force) {
  80463. this._cylinder.dispose();
  80464. }
  80465. else {
  80466. setTimeout(function () {
  80467. if (!_this._dataFetched) {
  80468. _this._cylinder.dispose();
  80469. }
  80470. }, 0);
  80471. }
  80472. };
  80473. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  80474. if (impostor.mass === 0) {
  80475. return null;
  80476. }
  80477. if (!this._intersectsWithCylinder(impostor)) {
  80478. return null;
  80479. }
  80480. var impostorObjectCenter = impostor.getObjectCenter();
  80481. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  80482. var direction = this._originDirection;
  80483. }
  80484. else {
  80485. var direction = impostorObjectCenter.subtract(this._originTop);
  80486. }
  80487. var multiplier = this._strength * -1;
  80488. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  80489. return { force: force, contactPoint: impostorObjectCenter };
  80490. };
  80491. PhysicsUpdraftEvent.prototype._tick = function () {
  80492. var _this = this;
  80493. this._physicsEngine.getImpostors().forEach(function (impostor) {
  80494. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  80495. if (!impostorForceAndContactPoint) {
  80496. return;
  80497. }
  80498. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80499. });
  80500. };
  80501. /*** Helpers ***/
  80502. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  80503. if (!this._cylinder) {
  80504. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  80505. height: this._height,
  80506. diameter: this._radius * 2,
  80507. }, this._scene);
  80508. this._cylinder.isVisible = false;
  80509. }
  80510. };
  80511. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  80512. var impostorObject = impostor.object;
  80513. this._prepareCylinder();
  80514. this._cylinder.position = this._cylinderPosition;
  80515. return this._cylinder.intersectsMesh(impostorObject, true);
  80516. };
  80517. return PhysicsUpdraftEvent;
  80518. }());
  80519. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  80520. /***** Vortex *****/
  80521. var PhysicsVortexEvent = /** @class */ (function () {
  80522. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  80523. this._scene = _scene;
  80524. this._origin = _origin;
  80525. this._radius = _radius;
  80526. this._strength = _strength;
  80527. this._height = _height;
  80528. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  80529. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  80530. this._updraftMultiplier = 0.02;
  80531. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  80532. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80533. this._physicsEngine = this._scene.getPhysicsEngine();
  80534. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  80535. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  80536. this._tickCallback = this._tick.bind(this);
  80537. }
  80538. /**
  80539. * Returns the data related to the vortex event (cylinder).
  80540. * @returns {PhysicsVortexEventData}
  80541. */
  80542. PhysicsVortexEvent.prototype.getData = function () {
  80543. this._dataFetched = true;
  80544. return {
  80545. cylinder: this._cylinder,
  80546. };
  80547. };
  80548. /**
  80549. * Enables the vortex.
  80550. */
  80551. PhysicsVortexEvent.prototype.enable = function () {
  80552. this._tickCallback.call(this);
  80553. this._scene.registerBeforeRender(this._tickCallback);
  80554. };
  80555. /**
  80556. * Disables the cortex.
  80557. */
  80558. PhysicsVortexEvent.prototype.disable = function () {
  80559. this._scene.unregisterBeforeRender(this._tickCallback);
  80560. };
  80561. /**
  80562. * Disposes the sphere.
  80563. * @param {bolean} force
  80564. */
  80565. PhysicsVortexEvent.prototype.dispose = function (force) {
  80566. var _this = this;
  80567. if (force === void 0) { force = true; }
  80568. if (force) {
  80569. this._cylinder.dispose();
  80570. }
  80571. else {
  80572. setTimeout(function () {
  80573. if (!_this._dataFetched) {
  80574. _this._cylinder.dispose();
  80575. }
  80576. }, 0);
  80577. }
  80578. };
  80579. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  80580. if (impostor.mass === 0) {
  80581. return null;
  80582. }
  80583. if (!this._intersectsWithCylinder(impostor)) {
  80584. return null;
  80585. }
  80586. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  80587. return null;
  80588. }
  80589. var impostorObjectCenter = impostor.getObjectCenter();
  80590. 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)
  80591. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  80592. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  80593. var hit = ray.intersectsMesh(impostor.object);
  80594. var contactPoint = hit.pickedPoint;
  80595. if (!contactPoint) {
  80596. return null;
  80597. }
  80598. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  80599. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  80600. var directionToOrigin = contactPoint.normalize();
  80601. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  80602. directionToOrigin = directionToOrigin.negate();
  80603. }
  80604. // TODO: find a more physically based solution
  80605. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  80606. var forceX = directionToOrigin.x * this._strength / 8;
  80607. var forceY = directionToOrigin.y * this._updraftMultiplier;
  80608. var forceZ = directionToOrigin.z * this._strength / 8;
  80609. }
  80610. else {
  80611. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  80612. var forceY = this._originTop.y * this._updraftMultiplier;
  80613. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  80614. }
  80615. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  80616. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  80617. return { force: force, contactPoint: impostorObjectCenter };
  80618. };
  80619. PhysicsVortexEvent.prototype._tick = function () {
  80620. var _this = this;
  80621. this._physicsEngine.getImpostors().forEach(function (impostor) {
  80622. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  80623. if (!impostorForceAndContactPoint) {
  80624. return;
  80625. }
  80626. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80627. });
  80628. };
  80629. /*** Helpers ***/
  80630. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  80631. if (!this._cylinder) {
  80632. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  80633. height: this._height,
  80634. diameter: this._radius * 2,
  80635. }, this._scene);
  80636. this._cylinder.isVisible = false;
  80637. }
  80638. };
  80639. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  80640. var impostorObject = impostor.object;
  80641. this._prepareCylinder();
  80642. this._cylinder.position = this._cylinderPosition;
  80643. return this._cylinder.intersectsMesh(impostorObject, true);
  80644. };
  80645. return PhysicsVortexEvent;
  80646. }());
  80647. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  80648. /***** Enums *****/
  80649. /**
  80650. * The strenght of the force in correspondence to the distance of the affected object
  80651. */
  80652. var PhysicsRadialImpulseFalloff;
  80653. (function (PhysicsRadialImpulseFalloff) {
  80654. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  80655. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  80656. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  80657. /**
  80658. * The strenght of the force in correspondence to the distance of the affected object
  80659. */
  80660. var PhysicsUpdraftMode;
  80661. (function (PhysicsUpdraftMode) {
  80662. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  80663. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  80664. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  80665. })(BABYLON || (BABYLON = {}));
  80666. //# sourceMappingURL=babylon.physicsHelper.js.map
  80667. "use strict";
  80668. var BABYLON;
  80669. (function (BABYLON) {
  80670. var CannonJSPlugin = /** @class */ (function () {
  80671. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  80672. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  80673. if (iterations === void 0) { iterations = 10; }
  80674. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  80675. this.name = "CannonJSPlugin";
  80676. this._physicsMaterials = new Array();
  80677. this._fixedTimeStep = 1 / 60;
  80678. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  80679. this.BJSCANNON = CANNON;
  80680. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  80681. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  80682. this._tmpPosition = BABYLON.Vector3.Zero();
  80683. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  80684. this._tmpUnityRotation = new BABYLON.Quaternion();
  80685. if (!this.isSupported()) {
  80686. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  80687. return;
  80688. }
  80689. this._extendNamespace();
  80690. this.world = new this.BJSCANNON.World();
  80691. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  80692. this.world.solver.iterations = iterations;
  80693. }
  80694. CannonJSPlugin.prototype.setGravity = function (gravity) {
  80695. this.world.gravity.copy(gravity);
  80696. };
  80697. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  80698. this._fixedTimeStep = timeStep;
  80699. };
  80700. CannonJSPlugin.prototype.getTimeStep = function () {
  80701. return this._fixedTimeStep;
  80702. };
  80703. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  80704. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  80705. };
  80706. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  80707. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  80708. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  80709. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  80710. };
  80711. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  80712. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  80713. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  80714. impostor.physicsBody.applyForce(impulse, worldPoint);
  80715. };
  80716. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  80717. //parent-child relationship. Does this impostor has a parent impostor?
  80718. if (impostor.parent) {
  80719. if (impostor.physicsBody) {
  80720. this.removePhysicsBody(impostor);
  80721. //TODO is that needed?
  80722. impostor.forceUpdate();
  80723. }
  80724. return;
  80725. }
  80726. //should a new body be created for this impostor?
  80727. if (impostor.isBodyInitRequired()) {
  80728. var shape = this._createShape(impostor);
  80729. //unregister events, if body is being changed
  80730. var oldBody = impostor.physicsBody;
  80731. if (oldBody) {
  80732. this.removePhysicsBody(impostor);
  80733. }
  80734. //create the body and material
  80735. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  80736. var bodyCreationObject = {
  80737. mass: impostor.getParam("mass"),
  80738. material: material
  80739. };
  80740. // A simple extend, in case native options were used.
  80741. var nativeOptions = impostor.getParam("nativeOptions");
  80742. for (var key in nativeOptions) {
  80743. if (nativeOptions.hasOwnProperty(key)) {
  80744. bodyCreationObject[key] = nativeOptions[key];
  80745. }
  80746. }
  80747. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  80748. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  80749. this.world.addEventListener("preStep", impostor.beforeStep);
  80750. this.world.addEventListener("postStep", impostor.afterStep);
  80751. impostor.physicsBody.addShape(shape);
  80752. this.world.add(impostor.physicsBody);
  80753. //try to keep the body moving in the right direction by taking old properties.
  80754. //Should be tested!
  80755. if (oldBody) {
  80756. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  80757. impostor.physicsBody[param].copy(oldBody[param]);
  80758. });
  80759. }
  80760. this._processChildMeshes(impostor);
  80761. }
  80762. //now update the body's transformation
  80763. this._updatePhysicsBodyTransformation(impostor);
  80764. };
  80765. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  80766. var _this = this;
  80767. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  80768. var currentRotation = mainImpostor.object.rotationQuaternion;
  80769. if (meshChildren.length) {
  80770. var processMesh = function (localPosition, mesh) {
  80771. if (!currentRotation || !mesh.rotationQuaternion) {
  80772. return;
  80773. }
  80774. var childImpostor = mesh.getPhysicsImpostor();
  80775. if (childImpostor) {
  80776. var parent = childImpostor.parent;
  80777. if (parent !== mainImpostor) {
  80778. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  80779. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  80780. if (childImpostor.physicsBody) {
  80781. _this.removePhysicsBody(childImpostor);
  80782. childImpostor.physicsBody = null;
  80783. }
  80784. childImpostor.parent = mainImpostor;
  80785. childImpostor.resetUpdateFlags();
  80786. 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));
  80787. //Add the mass of the children.
  80788. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  80789. }
  80790. }
  80791. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  80792. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  80793. };
  80794. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  80795. }
  80796. };
  80797. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  80798. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  80799. this.world.removeEventListener("preStep", impostor.beforeStep);
  80800. this.world.removeEventListener("postStep", impostor.afterStep);
  80801. this.world.remove(impostor.physicsBody);
  80802. };
  80803. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  80804. var mainBody = impostorJoint.mainImpostor.physicsBody;
  80805. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  80806. if (!mainBody || !connectedBody) {
  80807. return;
  80808. }
  80809. var constraint;
  80810. var jointData = impostorJoint.joint.jointData;
  80811. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  80812. var constraintData = {
  80813. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  80814. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  80815. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  80816. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  80817. maxForce: jointData.nativeParams.maxForce,
  80818. collideConnected: !!jointData.collision
  80819. };
  80820. switch (impostorJoint.joint.type) {
  80821. case BABYLON.PhysicsJoint.HingeJoint:
  80822. case BABYLON.PhysicsJoint.Hinge2Joint:
  80823. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  80824. break;
  80825. case BABYLON.PhysicsJoint.DistanceJoint:
  80826. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  80827. break;
  80828. case BABYLON.PhysicsJoint.SpringJoint:
  80829. var springData = jointData;
  80830. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  80831. restLength: springData.length,
  80832. stiffness: springData.stiffness,
  80833. damping: springData.damping,
  80834. localAnchorA: constraintData.pivotA,
  80835. localAnchorB: constraintData.pivotB
  80836. });
  80837. break;
  80838. case BABYLON.PhysicsJoint.LockJoint:
  80839. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  80840. break;
  80841. case BABYLON.PhysicsJoint.PointToPointJoint:
  80842. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  80843. default:
  80844. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  80845. break;
  80846. }
  80847. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  80848. constraint.collideConnected = !!jointData.collision;
  80849. impostorJoint.joint.physicsJoint = constraint;
  80850. //don't add spring as constraint, as it is not one.
  80851. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  80852. this.world.addConstraint(constraint);
  80853. }
  80854. else {
  80855. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  80856. constraint.applyForce();
  80857. });
  80858. }
  80859. };
  80860. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  80861. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  80862. };
  80863. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  80864. var index;
  80865. var mat;
  80866. for (index = 0; index < this._physicsMaterials.length; index++) {
  80867. mat = this._physicsMaterials[index];
  80868. if (mat.friction === friction && mat.restitution === restitution) {
  80869. return mat;
  80870. }
  80871. }
  80872. var currentMat = new this.BJSCANNON.Material(name);
  80873. currentMat.friction = friction;
  80874. currentMat.restitution = restitution;
  80875. this._physicsMaterials.push(currentMat);
  80876. return currentMat;
  80877. };
  80878. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  80879. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  80880. };
  80881. CannonJSPlugin.prototype._createShape = function (impostor) {
  80882. var object = impostor.object;
  80883. var returnValue;
  80884. var extendSize = impostor.getObjectExtendSize();
  80885. switch (impostor.type) {
  80886. case BABYLON.PhysicsImpostor.SphereImpostor:
  80887. var radiusX = extendSize.x;
  80888. var radiusY = extendSize.y;
  80889. var radiusZ = extendSize.z;
  80890. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  80891. break;
  80892. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  80893. case BABYLON.PhysicsImpostor.CylinderImpostor:
  80894. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  80895. break;
  80896. case BABYLON.PhysicsImpostor.BoxImpostor:
  80897. var box = extendSize.scale(0.5);
  80898. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  80899. break;
  80900. case BABYLON.PhysicsImpostor.PlaneImpostor:
  80901. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  80902. returnValue = new this.BJSCANNON.Plane();
  80903. break;
  80904. case BABYLON.PhysicsImpostor.MeshImpostor:
  80905. // should transform the vertex data to world coordinates!!
  80906. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  80907. var rawFaces = object.getIndices ? object.getIndices() : [];
  80908. if (!rawVerts)
  80909. return;
  80910. // get only scale! so the object could transform correctly.
  80911. var oldPosition = object.position.clone();
  80912. var oldRotation = object.rotation && object.rotation.clone();
  80913. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  80914. object.position.copyFromFloats(0, 0, 0);
  80915. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  80916. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  80917. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  80918. var transform = object.computeWorldMatrix(true);
  80919. // convert rawVerts to object space
  80920. var temp = new Array();
  80921. var index;
  80922. for (index = 0; index < rawVerts.length; index += 3) {
  80923. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  80924. }
  80925. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  80926. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  80927. //now set back the transformation!
  80928. object.position.copyFrom(oldPosition);
  80929. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  80930. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  80931. break;
  80932. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  80933. var oldPosition2 = object.position.clone();
  80934. var oldRotation2 = object.rotation && object.rotation.clone();
  80935. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  80936. object.position.copyFromFloats(0, 0, 0);
  80937. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  80938. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  80939. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  80940. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  80941. returnValue = this._createHeightmap(object);
  80942. object.position.copyFrom(oldPosition2);
  80943. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  80944. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  80945. object.computeWorldMatrix(true);
  80946. break;
  80947. case BABYLON.PhysicsImpostor.ParticleImpostor:
  80948. returnValue = new this.BJSCANNON.Particle();
  80949. break;
  80950. }
  80951. return returnValue;
  80952. };
  80953. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  80954. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80955. var transform = object.computeWorldMatrix(true);
  80956. // convert rawVerts to object space
  80957. var temp = new Array();
  80958. var index;
  80959. for (index = 0; index < pos.length; index += 3) {
  80960. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  80961. }
  80962. pos = temp;
  80963. var matrix = new Array();
  80964. //For now pointDepth will not be used and will be automatically calculated.
  80965. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  80966. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  80967. var boundingInfo = object.getBoundingInfo();
  80968. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  80969. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  80970. var elementSize = dim * 2 / arraySize;
  80971. for (var i = 0; i < pos.length; i = i + 3) {
  80972. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  80973. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  80974. var y = -pos[i + 2] + minY;
  80975. if (!matrix[x]) {
  80976. matrix[x] = [];
  80977. }
  80978. if (!matrix[x][z]) {
  80979. matrix[x][z] = y;
  80980. }
  80981. matrix[x][z] = Math.max(y, matrix[x][z]);
  80982. }
  80983. for (var x = 0; x <= arraySize; ++x) {
  80984. if (!matrix[x]) {
  80985. var loc = 1;
  80986. while (!matrix[(x + loc) % arraySize]) {
  80987. loc++;
  80988. }
  80989. matrix[x] = matrix[(x + loc) % arraySize].slice();
  80990. //console.log("missing x", x);
  80991. }
  80992. for (var z = 0; z <= arraySize; ++z) {
  80993. if (!matrix[x][z]) {
  80994. var loc = 1;
  80995. var newValue;
  80996. while (newValue === undefined) {
  80997. newValue = matrix[x][(z + loc++) % arraySize];
  80998. }
  80999. matrix[x][z] = newValue;
  81000. }
  81001. }
  81002. }
  81003. var shape = new this.BJSCANNON.Heightfield(matrix, {
  81004. elementSize: elementSize
  81005. });
  81006. //For future reference, needed for body transformation
  81007. shape.minY = minY;
  81008. return shape;
  81009. };
  81010. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  81011. var object = impostor.object;
  81012. //make sure it is updated...
  81013. object.computeWorldMatrix && object.computeWorldMatrix(true);
  81014. // The delta between the mesh position and the mesh bounding box center
  81015. var bInfo = object.getBoundingInfo();
  81016. if (!bInfo)
  81017. return;
  81018. var center = impostor.getObjectCenter();
  81019. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  81020. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  81021. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  81022. this._tmpPosition.copyFrom(center);
  81023. var quaternion = object.rotationQuaternion;
  81024. if (!quaternion) {
  81025. return;
  81026. }
  81027. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  81028. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  81029. //-90 DEG in X, precalculated
  81030. quaternion = quaternion.multiply(this._minus90X);
  81031. //Invert! (Precalculated, 90 deg in X)
  81032. //No need to clone. this will never change.
  81033. impostor.setDeltaRotation(this._plus90X);
  81034. }
  81035. //If it is a heightfield, if should be centered.
  81036. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  81037. var mesh = object;
  81038. var boundingInfo = mesh.getBoundingInfo();
  81039. //calculate the correct body position:
  81040. var rotationQuaternion = mesh.rotationQuaternion;
  81041. mesh.rotationQuaternion = this._tmpUnityRotation;
  81042. mesh.computeWorldMatrix(true);
  81043. //get original center with no rotation
  81044. var c = center.clone();
  81045. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  81046. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  81047. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  81048. mesh.setPreTransformMatrix(p);
  81049. mesh.computeWorldMatrix(true);
  81050. //calculate the translation
  81051. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  81052. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  81053. //add it inverted to the delta
  81054. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  81055. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  81056. //rotation is back
  81057. mesh.rotationQuaternion = rotationQuaternion;
  81058. mesh.setPreTransformMatrix(oldPivot);
  81059. mesh.computeWorldMatrix(true);
  81060. }
  81061. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  81062. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  81063. //this._tmpPosition.copyFrom(object.position);
  81064. }
  81065. impostor.setDeltaPosition(this._tmpDeltaPosition);
  81066. //Now update the impostor object
  81067. impostor.physicsBody.position.copy(this._tmpPosition);
  81068. impostor.physicsBody.quaternion.copy(quaternion);
  81069. };
  81070. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81071. impostor.object.position.copyFrom(impostor.physicsBody.position);
  81072. if (impostor.object.rotationQuaternion) {
  81073. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  81074. }
  81075. };
  81076. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81077. impostor.physicsBody.position.copy(newPosition);
  81078. impostor.physicsBody.quaternion.copy(newRotation);
  81079. };
  81080. CannonJSPlugin.prototype.isSupported = function () {
  81081. return this.BJSCANNON !== undefined;
  81082. };
  81083. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81084. impostor.physicsBody.velocity.copy(velocity);
  81085. };
  81086. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81087. impostor.physicsBody.angularVelocity.copy(velocity);
  81088. };
  81089. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81090. var v = impostor.physicsBody.velocity;
  81091. if (!v) {
  81092. return null;
  81093. }
  81094. return new BABYLON.Vector3(v.x, v.y, v.z);
  81095. };
  81096. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81097. var v = impostor.physicsBody.angularVelocity;
  81098. if (!v) {
  81099. return null;
  81100. }
  81101. return new BABYLON.Vector3(v.x, v.y, v.z);
  81102. };
  81103. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81104. impostor.physicsBody.mass = mass;
  81105. impostor.physicsBody.updateMassProperties();
  81106. };
  81107. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  81108. return impostor.physicsBody.mass;
  81109. };
  81110. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  81111. return impostor.physicsBody.material.friction;
  81112. };
  81113. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81114. impostor.physicsBody.material.friction = friction;
  81115. };
  81116. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81117. return impostor.physicsBody.material.restitution;
  81118. };
  81119. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81120. impostor.physicsBody.material.restitution = restitution;
  81121. };
  81122. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  81123. impostor.physicsBody.sleep();
  81124. };
  81125. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  81126. impostor.physicsBody.wakeUp();
  81127. };
  81128. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81129. joint.physicsJoint.distance = maxDistance;
  81130. };
  81131. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81132. // if (!motorIndex) {
  81133. // joint.physicsJoint.enableMotor();
  81134. // }
  81135. // }
  81136. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81137. // if (!motorIndex) {
  81138. // joint.physicsJoint.disableMotor();
  81139. // }
  81140. // }
  81141. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81142. if (!motorIndex) {
  81143. joint.physicsJoint.enableMotor();
  81144. joint.physicsJoint.setMotorSpeed(speed);
  81145. if (maxForce) {
  81146. this.setLimit(joint, maxForce);
  81147. }
  81148. }
  81149. };
  81150. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  81151. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  81152. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  81153. };
  81154. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81155. var body = impostor.physicsBody;
  81156. mesh.position.x = body.position.x;
  81157. mesh.position.y = body.position.y;
  81158. mesh.position.z = body.position.z;
  81159. if (mesh.rotationQuaternion) {
  81160. mesh.rotationQuaternion.x = body.quaternion.x;
  81161. mesh.rotationQuaternion.y = body.quaternion.y;
  81162. mesh.rotationQuaternion.z = body.quaternion.z;
  81163. mesh.rotationQuaternion.w = body.quaternion.w;
  81164. }
  81165. };
  81166. CannonJSPlugin.prototype.getRadius = function (impostor) {
  81167. var shape = impostor.physicsBody.shapes[0];
  81168. return shape.boundingSphereRadius;
  81169. };
  81170. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81171. var shape = impostor.physicsBody.shapes[0];
  81172. result.x = shape.halfExtents.x * 2;
  81173. result.y = shape.halfExtents.y * 2;
  81174. result.z = shape.halfExtents.z * 2;
  81175. };
  81176. CannonJSPlugin.prototype.dispose = function () {
  81177. };
  81178. CannonJSPlugin.prototype._extendNamespace = function () {
  81179. //this will force cannon to execute at least one step when using interpolation
  81180. var step_tmp1 = new this.BJSCANNON.Vec3();
  81181. var Engine = this.BJSCANNON;
  81182. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  81183. maxSubSteps = maxSubSteps || 10;
  81184. timeSinceLastCalled = timeSinceLastCalled || 0;
  81185. if (timeSinceLastCalled === 0) {
  81186. this.internalStep(dt);
  81187. this.time += dt;
  81188. }
  81189. else {
  81190. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  81191. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  81192. var t0 = performance.now();
  81193. for (var i = 0; i !== internalSteps; i++) {
  81194. this.internalStep(dt);
  81195. if (performance.now() - t0 > dt * 1000) {
  81196. break;
  81197. }
  81198. }
  81199. this.time += timeSinceLastCalled;
  81200. var h = this.time % dt;
  81201. var h_div_dt = h / dt;
  81202. var interpvelo = step_tmp1;
  81203. var bodies = this.bodies;
  81204. for (var j = 0; j !== bodies.length; j++) {
  81205. var b = bodies[j];
  81206. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  81207. b.position.vsub(b.previousPosition, interpvelo);
  81208. interpvelo.scale(h_div_dt, interpvelo);
  81209. b.position.vadd(interpvelo, b.interpolatedPosition);
  81210. }
  81211. else {
  81212. b.interpolatedPosition.copy(b.position);
  81213. b.interpolatedQuaternion.copy(b.quaternion);
  81214. }
  81215. }
  81216. }
  81217. };
  81218. };
  81219. return CannonJSPlugin;
  81220. }());
  81221. BABYLON.CannonJSPlugin = CannonJSPlugin;
  81222. })(BABYLON || (BABYLON = {}));
  81223. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  81224. "use strict";
  81225. var BABYLON;
  81226. (function (BABYLON) {
  81227. var OimoJSPlugin = /** @class */ (function () {
  81228. function OimoJSPlugin(iterations) {
  81229. this.name = "OimoJSPlugin";
  81230. this._tmpImpostorsArray = [];
  81231. this._tmpPositionVector = BABYLON.Vector3.Zero();
  81232. this.BJSOIMO = OIMO;
  81233. this.world = new this.BJSOIMO.World({
  81234. iterations: iterations
  81235. });
  81236. this.world.clear();
  81237. }
  81238. OimoJSPlugin.prototype.setGravity = function (gravity) {
  81239. this.world.gravity.copy(gravity);
  81240. };
  81241. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  81242. this.world.timeStep = timeStep;
  81243. };
  81244. OimoJSPlugin.prototype.getTimeStep = function () {
  81245. return this.world.timeStep;
  81246. };
  81247. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  81248. var _this = this;
  81249. impostors.forEach(function (impostor) {
  81250. impostor.beforeStep();
  81251. });
  81252. this.world.step();
  81253. impostors.forEach(function (impostor) {
  81254. impostor.afterStep();
  81255. //update the ordered impostors array
  81256. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  81257. });
  81258. //check for collisions
  81259. var contact = this.world.contacts;
  81260. while (contact !== null) {
  81261. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  81262. contact = contact.next;
  81263. continue;
  81264. }
  81265. //is this body colliding with any other? get the impostor
  81266. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  81267. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  81268. if (!mainImpostor || !collidingImpostor) {
  81269. contact = contact.next;
  81270. continue;
  81271. }
  81272. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  81273. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  81274. contact = contact.next;
  81275. }
  81276. };
  81277. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81278. var mass = impostor.physicsBody.mass;
  81279. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  81280. };
  81281. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81282. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  81283. this.applyImpulse(impostor, force, contactPoint);
  81284. };
  81285. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81286. var _this = this;
  81287. //parent-child relationship. Does this impostor has a parent impostor?
  81288. if (impostor.parent) {
  81289. if (impostor.physicsBody) {
  81290. this.removePhysicsBody(impostor);
  81291. //TODO is that needed?
  81292. impostor.forceUpdate();
  81293. }
  81294. return;
  81295. }
  81296. if (impostor.isBodyInitRequired()) {
  81297. var bodyConfig = {
  81298. name: impostor.uniqueId,
  81299. //Oimo must have mass, also for static objects.
  81300. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  81301. size: [],
  81302. type: [],
  81303. pos: [],
  81304. posShape: [],
  81305. rot: [],
  81306. rotShape: [],
  81307. move: impostor.getParam("mass") !== 0,
  81308. density: impostor.getParam("mass"),
  81309. friction: impostor.getParam("friction"),
  81310. restitution: impostor.getParam("restitution"),
  81311. //Supporting older versions of Oimo
  81312. world: this.world
  81313. };
  81314. var impostors = [impostor];
  81315. var addToArray = function (parent) {
  81316. if (!parent.getChildMeshes)
  81317. return;
  81318. parent.getChildMeshes().forEach(function (m) {
  81319. if (m.physicsImpostor) {
  81320. impostors.push(m.physicsImpostor);
  81321. //m.physicsImpostor._init();
  81322. }
  81323. });
  81324. };
  81325. addToArray(impostor.object);
  81326. var checkWithEpsilon_1 = function (value) {
  81327. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  81328. };
  81329. impostors.forEach(function (i) {
  81330. if (!i.object.rotationQuaternion) {
  81331. return;
  81332. }
  81333. //get the correct bounding box
  81334. var oldQuaternion = i.object.rotationQuaternion;
  81335. var rot = oldQuaternion.toEulerAngles();
  81336. var extendSize = i.getObjectExtendSize();
  81337. var radToDeg = 57.295779513082320876;
  81338. if (i === impostor) {
  81339. var center = impostor.getObjectCenter();
  81340. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  81341. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  81342. //Can also use Array.prototype.push.apply
  81343. bodyConfig.pos.push(center.x);
  81344. bodyConfig.pos.push(center.y);
  81345. bodyConfig.pos.push(center.z);
  81346. bodyConfig.posShape.push(0, 0, 0);
  81347. //tmp solution
  81348. bodyConfig.rot.push(rot.x * radToDeg);
  81349. bodyConfig.rot.push(rot.y * radToDeg);
  81350. bodyConfig.rot.push(rot.z * radToDeg);
  81351. bodyConfig.rotShape.push(0, 0, 0);
  81352. }
  81353. else {
  81354. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  81355. bodyConfig.posShape.push(localPosition.x);
  81356. bodyConfig.posShape.push(localPosition.y);
  81357. bodyConfig.posShape.push(localPosition.z);
  81358. bodyConfig.pos.push(0, 0, 0);
  81359. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  81360. bodyConfig.rot.push(0);
  81361. bodyConfig.rot.push(0);
  81362. bodyConfig.rot.push(0);
  81363. bodyConfig.rotShape.push(rot.x * radToDeg);
  81364. bodyConfig.rotShape.push(rot.y * radToDeg);
  81365. bodyConfig.rotShape.push(rot.z * radToDeg);
  81366. }
  81367. // register mesh
  81368. switch (i.type) {
  81369. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81370. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  81371. case BABYLON.PhysicsImpostor.SphereImpostor:
  81372. var radiusX = extendSize.x;
  81373. var radiusY = extendSize.y;
  81374. var radiusZ = extendSize.z;
  81375. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  81376. bodyConfig.type.push('sphere');
  81377. //due to the way oimo works with compounds, add 3 times
  81378. bodyConfig.size.push(size);
  81379. bodyConfig.size.push(size);
  81380. bodyConfig.size.push(size);
  81381. break;
  81382. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81383. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  81384. var sizeY = checkWithEpsilon_1(extendSize.y);
  81385. bodyConfig.type.push('cylinder');
  81386. bodyConfig.size.push(sizeX);
  81387. bodyConfig.size.push(sizeY);
  81388. //due to the way oimo works with compounds, add one more value.
  81389. bodyConfig.size.push(sizeY);
  81390. break;
  81391. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81392. case BABYLON.PhysicsImpostor.BoxImpostor:
  81393. default:
  81394. var sizeX = checkWithEpsilon_1(extendSize.x);
  81395. var sizeY = checkWithEpsilon_1(extendSize.y);
  81396. var sizeZ = checkWithEpsilon_1(extendSize.z);
  81397. bodyConfig.type.push('box');
  81398. //if (i === impostor) {
  81399. bodyConfig.size.push(sizeX);
  81400. bodyConfig.size.push(sizeY);
  81401. bodyConfig.size.push(sizeZ);
  81402. //} else {
  81403. // bodyConfig.size.push(0,0,0);
  81404. //}
  81405. break;
  81406. }
  81407. //actually not needed, but hey...
  81408. i.object.rotationQuaternion = oldQuaternion;
  81409. });
  81410. impostor.physicsBody = this.world.add(bodyConfig);
  81411. }
  81412. else {
  81413. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  81414. }
  81415. impostor.setDeltaPosition(this._tmpPositionVector);
  81416. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  81417. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  81418. };
  81419. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81420. //impostor.physicsBody.dispose();
  81421. //Same as : (older oimo versions)
  81422. this.world.removeRigidBody(impostor.physicsBody);
  81423. };
  81424. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81425. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81426. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81427. if (!mainBody || !connectedBody) {
  81428. return;
  81429. }
  81430. var jointData = impostorJoint.joint.jointData;
  81431. var options = jointData.nativeParams || {};
  81432. var type;
  81433. var nativeJointData = {
  81434. body1: mainBody,
  81435. body2: connectedBody,
  81436. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  81437. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  81438. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  81439. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  81440. min: options.min,
  81441. max: options.max,
  81442. collision: options.collision || jointData.collision,
  81443. spring: options.spring,
  81444. //supporting older version of Oimo
  81445. world: this.world
  81446. };
  81447. switch (impostorJoint.joint.type) {
  81448. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81449. type = "jointBall";
  81450. break;
  81451. case BABYLON.PhysicsJoint.SpringJoint:
  81452. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  81453. var springData = jointData;
  81454. nativeJointData.min = springData.length || nativeJointData.min;
  81455. //Max should also be set, just make sure it is at least min
  81456. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  81457. case BABYLON.PhysicsJoint.DistanceJoint:
  81458. type = "jointDistance";
  81459. nativeJointData.max = jointData.maxDistance;
  81460. break;
  81461. case BABYLON.PhysicsJoint.PrismaticJoint:
  81462. type = "jointPrisme";
  81463. break;
  81464. case BABYLON.PhysicsJoint.SliderJoint:
  81465. type = "jointSlide";
  81466. break;
  81467. case BABYLON.PhysicsJoint.WheelJoint:
  81468. type = "jointWheel";
  81469. break;
  81470. case BABYLON.PhysicsJoint.HingeJoint:
  81471. default:
  81472. type = "jointHinge";
  81473. break;
  81474. }
  81475. nativeJointData.type = type;
  81476. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  81477. };
  81478. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81479. //Bug in Oimo prevents us from disposing a joint in the playground
  81480. //joint.joint.physicsJoint.dispose();
  81481. //So we will bruteforce it!
  81482. try {
  81483. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  81484. }
  81485. catch (e) {
  81486. BABYLON.Tools.Warn(e);
  81487. }
  81488. };
  81489. OimoJSPlugin.prototype.isSupported = function () {
  81490. return this.BJSOIMO !== undefined;
  81491. };
  81492. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81493. if (!impostor.physicsBody.sleeping) {
  81494. //TODO check that
  81495. /*if (impostor.physicsBody.shapes.next) {
  81496. var parentShape = this._getLastShape(impostor.physicsBody);
  81497. impostor.object.position.copyFrom(parentShape.position);
  81498. console.log(parentShape.position);
  81499. } else {*/
  81500. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  81501. //}
  81502. if (impostor.object.rotationQuaternion) {
  81503. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  81504. }
  81505. }
  81506. };
  81507. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81508. var body = impostor.physicsBody;
  81509. body.position.copy(newPosition);
  81510. body.orientation.copy(newRotation);
  81511. body.syncShapes();
  81512. body.awake();
  81513. };
  81514. /*private _getLastShape(body: any): any {
  81515. var lastShape = body.shapes;
  81516. while (lastShape.next) {
  81517. lastShape = lastShape.next;
  81518. }
  81519. return lastShape;
  81520. }*/
  81521. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81522. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  81523. };
  81524. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81525. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  81526. };
  81527. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81528. var v = impostor.physicsBody.linearVelocity;
  81529. if (!v) {
  81530. return null;
  81531. }
  81532. return new BABYLON.Vector3(v.x, v.y, v.z);
  81533. };
  81534. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81535. var v = impostor.physicsBody.angularVelocity;
  81536. if (!v) {
  81537. return null;
  81538. }
  81539. return new BABYLON.Vector3(v.x, v.y, v.z);
  81540. };
  81541. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81542. var staticBody = mass === 0;
  81543. //this will actually set the body's density and not its mass.
  81544. //But this is how oimo treats the mass variable.
  81545. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  81546. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  81547. };
  81548. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  81549. return impostor.physicsBody.shapes.density;
  81550. };
  81551. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  81552. return impostor.physicsBody.shapes.friction;
  81553. };
  81554. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81555. impostor.physicsBody.shapes.friction = friction;
  81556. };
  81557. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81558. return impostor.physicsBody.shapes.restitution;
  81559. };
  81560. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81561. impostor.physicsBody.shapes.restitution = restitution;
  81562. };
  81563. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  81564. impostor.physicsBody.sleep();
  81565. };
  81566. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  81567. impostor.physicsBody.awake();
  81568. };
  81569. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81570. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  81571. if (minDistance !== void 0) {
  81572. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  81573. }
  81574. };
  81575. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81576. //TODO separate rotational and transational motors.
  81577. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  81578. if (motor) {
  81579. motor.setMotor(speed, maxForce);
  81580. }
  81581. };
  81582. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  81583. //TODO separate rotational and transational motors.
  81584. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  81585. if (motor) {
  81586. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  81587. }
  81588. };
  81589. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81590. var body = impostor.physicsBody;
  81591. mesh.position.x = body.position.x;
  81592. mesh.position.y = body.position.y;
  81593. mesh.position.z = body.position.z;
  81594. if (mesh.rotationQuaternion) {
  81595. mesh.rotationQuaternion.x = body.orientation.x;
  81596. mesh.rotationQuaternion.y = body.orientation.y;
  81597. mesh.rotationQuaternion.z = body.orientation.z;
  81598. mesh.rotationQuaternion.w = body.orientation.s;
  81599. }
  81600. };
  81601. OimoJSPlugin.prototype.getRadius = function (impostor) {
  81602. return impostor.physicsBody.shapes.radius;
  81603. };
  81604. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81605. var shape = impostor.physicsBody.shapes;
  81606. result.x = shape.halfWidth * 2;
  81607. result.y = shape.halfHeight * 2;
  81608. result.z = shape.halfDepth * 2;
  81609. };
  81610. OimoJSPlugin.prototype.dispose = function () {
  81611. this.world.clear();
  81612. };
  81613. return OimoJSPlugin;
  81614. }());
  81615. BABYLON.OimoJSPlugin = OimoJSPlugin;
  81616. })(BABYLON || (BABYLON = {}));
  81617. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  81618. "use strict";
  81619. var BABYLON;
  81620. (function (BABYLON) {
  81621. /*
  81622. * Based on jsTGALoader - Javascript loader for TGA file
  81623. * By Vincent Thibault
  81624. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  81625. */
  81626. var TGATools = /** @class */ (function () {
  81627. function TGATools() {
  81628. }
  81629. TGATools.GetTGAHeader = function (data) {
  81630. var offset = 0;
  81631. var header = {
  81632. id_length: data[offset++],
  81633. colormap_type: data[offset++],
  81634. image_type: data[offset++],
  81635. colormap_index: data[offset++] | data[offset++] << 8,
  81636. colormap_length: data[offset++] | data[offset++] << 8,
  81637. colormap_size: data[offset++],
  81638. origin: [
  81639. data[offset++] | data[offset++] << 8,
  81640. data[offset++] | data[offset++] << 8
  81641. ],
  81642. width: data[offset++] | data[offset++] << 8,
  81643. height: data[offset++] | data[offset++] << 8,
  81644. pixel_size: data[offset++],
  81645. flags: data[offset++]
  81646. };
  81647. return header;
  81648. };
  81649. TGATools.UploadContent = function (gl, data) {
  81650. // Not enough data to contain header ?
  81651. if (data.length < 19) {
  81652. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  81653. return;
  81654. }
  81655. // Read Header
  81656. var offset = 18;
  81657. var header = TGATools.GetTGAHeader(data);
  81658. // Assume it's a valid Targa file.
  81659. if (header.id_length + offset > data.length) {
  81660. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  81661. return;
  81662. }
  81663. // Skip not needed data
  81664. offset += header.id_length;
  81665. var use_rle = false;
  81666. var use_pal = false;
  81667. var use_grey = false;
  81668. // Get some informations.
  81669. switch (header.image_type) {
  81670. case TGATools._TYPE_RLE_INDEXED:
  81671. use_rle = true;
  81672. case TGATools._TYPE_INDEXED:
  81673. use_pal = true;
  81674. break;
  81675. case TGATools._TYPE_RLE_RGB:
  81676. use_rle = true;
  81677. case TGATools._TYPE_RGB:
  81678. // use_rgb = true;
  81679. break;
  81680. case TGATools._TYPE_RLE_GREY:
  81681. use_rle = true;
  81682. case TGATools._TYPE_GREY:
  81683. use_grey = true;
  81684. break;
  81685. }
  81686. var pixel_data;
  81687. // var numAlphaBits = header.flags & 0xf;
  81688. var pixel_size = header.pixel_size >> 3;
  81689. var pixel_total = header.width * header.height * pixel_size;
  81690. // Read palettes
  81691. var palettes;
  81692. if (use_pal) {
  81693. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  81694. }
  81695. // Read LRE
  81696. if (use_rle) {
  81697. pixel_data = new Uint8Array(pixel_total);
  81698. var c, count, i;
  81699. var localOffset = 0;
  81700. var pixels = new Uint8Array(pixel_size);
  81701. while (offset < pixel_total && localOffset < pixel_total) {
  81702. c = data[offset++];
  81703. count = (c & 0x7f) + 1;
  81704. // RLE pixels
  81705. if (c & 0x80) {
  81706. // Bind pixel tmp array
  81707. for (i = 0; i < pixel_size; ++i) {
  81708. pixels[i] = data[offset++];
  81709. }
  81710. // Copy pixel array
  81711. for (i = 0; i < count; ++i) {
  81712. pixel_data.set(pixels, localOffset + i * pixel_size);
  81713. }
  81714. localOffset += pixel_size * count;
  81715. }
  81716. else {
  81717. count *= pixel_size;
  81718. for (i = 0; i < count; ++i) {
  81719. pixel_data[localOffset + i] = data[offset++];
  81720. }
  81721. localOffset += count;
  81722. }
  81723. }
  81724. }
  81725. else {
  81726. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  81727. }
  81728. // Load to texture
  81729. var x_start, y_start, x_step, y_step, y_end, x_end;
  81730. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  81731. default:
  81732. case TGATools._ORIGIN_UL:
  81733. x_start = 0;
  81734. x_step = 1;
  81735. x_end = header.width;
  81736. y_start = 0;
  81737. y_step = 1;
  81738. y_end = header.height;
  81739. break;
  81740. case TGATools._ORIGIN_BL:
  81741. x_start = 0;
  81742. x_step = 1;
  81743. x_end = header.width;
  81744. y_start = header.height - 1;
  81745. y_step = -1;
  81746. y_end = -1;
  81747. break;
  81748. case TGATools._ORIGIN_UR:
  81749. x_start = header.width - 1;
  81750. x_step = -1;
  81751. x_end = -1;
  81752. y_start = 0;
  81753. y_step = 1;
  81754. y_end = header.height;
  81755. break;
  81756. case TGATools._ORIGIN_BR:
  81757. x_start = header.width - 1;
  81758. x_step = -1;
  81759. x_end = -1;
  81760. y_start = header.height - 1;
  81761. y_step = -1;
  81762. y_end = -1;
  81763. break;
  81764. }
  81765. // Load the specify method
  81766. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  81767. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  81768. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  81769. };
  81770. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81771. var image = pixel_data, colormap = palettes;
  81772. var width = header.width, height = header.height;
  81773. var color, i = 0, x, y;
  81774. var imageData = new Uint8Array(width * height * 4);
  81775. for (y = y_start; y !== y_end; y += y_step) {
  81776. for (x = x_start; x !== x_end; x += x_step, i++) {
  81777. color = image[i];
  81778. imageData[(x + width * y) * 4 + 3] = 255;
  81779. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  81780. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  81781. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  81782. }
  81783. }
  81784. return imageData;
  81785. };
  81786. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81787. var image = pixel_data;
  81788. var width = header.width, height = header.height;
  81789. var color, i = 0, x, y;
  81790. var imageData = new Uint8Array(width * height * 4);
  81791. for (y = y_start; y !== y_end; y += y_step) {
  81792. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  81793. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  81794. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  81795. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  81796. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  81797. imageData[(x + width * y) * 4 + 0] = r;
  81798. imageData[(x + width * y) * 4 + 1] = g;
  81799. imageData[(x + width * y) * 4 + 2] = b;
  81800. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  81801. }
  81802. }
  81803. return imageData;
  81804. };
  81805. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81806. var image = pixel_data;
  81807. var width = header.width, height = header.height;
  81808. var i = 0, x, y;
  81809. var imageData = new Uint8Array(width * height * 4);
  81810. for (y = y_start; y !== y_end; y += y_step) {
  81811. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  81812. imageData[(x + width * y) * 4 + 3] = 255;
  81813. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81814. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  81815. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  81816. }
  81817. }
  81818. return imageData;
  81819. };
  81820. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81821. var image = pixel_data;
  81822. var width = header.width, height = header.height;
  81823. var i = 0, x, y;
  81824. var imageData = new Uint8Array(width * height * 4);
  81825. for (y = y_start; y !== y_end; y += y_step) {
  81826. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  81827. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81828. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  81829. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  81830. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  81831. }
  81832. }
  81833. return imageData;
  81834. };
  81835. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81836. var image = pixel_data;
  81837. var width = header.width, height = header.height;
  81838. var color, i = 0, x, y;
  81839. var imageData = new Uint8Array(width * height * 4);
  81840. for (y = y_start; y !== y_end; y += y_step) {
  81841. for (x = x_start; x !== x_end; x += x_step, i++) {
  81842. color = image[i];
  81843. imageData[(x + width * y) * 4 + 0] = color;
  81844. imageData[(x + width * y) * 4 + 1] = color;
  81845. imageData[(x + width * y) * 4 + 2] = color;
  81846. imageData[(x + width * y) * 4 + 3] = 255;
  81847. }
  81848. }
  81849. return imageData;
  81850. };
  81851. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  81852. var image = pixel_data;
  81853. var width = header.width, height = header.height;
  81854. var i = 0, x, y;
  81855. var imageData = new Uint8Array(width * height * 4);
  81856. for (y = y_start; y !== y_end; y += y_step) {
  81857. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  81858. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  81859. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  81860. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  81861. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  81862. }
  81863. }
  81864. return imageData;
  81865. };
  81866. //private static _TYPE_NO_DATA = 0;
  81867. TGATools._TYPE_INDEXED = 1;
  81868. TGATools._TYPE_RGB = 2;
  81869. TGATools._TYPE_GREY = 3;
  81870. TGATools._TYPE_RLE_INDEXED = 9;
  81871. TGATools._TYPE_RLE_RGB = 10;
  81872. TGATools._TYPE_RLE_GREY = 11;
  81873. TGATools._ORIGIN_MASK = 0x30;
  81874. TGATools._ORIGIN_SHIFT = 0x04;
  81875. TGATools._ORIGIN_BL = 0x00;
  81876. TGATools._ORIGIN_BR = 0x01;
  81877. TGATools._ORIGIN_UL = 0x02;
  81878. TGATools._ORIGIN_UR = 0x03;
  81879. return TGATools;
  81880. }());
  81881. BABYLON.TGATools = TGATools;
  81882. })(BABYLON || (BABYLON = {}));
  81883. //# sourceMappingURL=babylon.tga.js.map
  81884. "use strict";
  81885. var BABYLON;
  81886. (function (BABYLON) {
  81887. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  81888. // All values and structures referenced from:
  81889. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  81890. var DDS_MAGIC = 0x20534444;
  81891. var
  81892. //DDSD_CAPS = 0x1,
  81893. //DDSD_HEIGHT = 0x2,
  81894. //DDSD_WIDTH = 0x4,
  81895. //DDSD_PITCH = 0x8,
  81896. //DDSD_PIXELFORMAT = 0x1000,
  81897. DDSD_MIPMAPCOUNT = 0x20000;
  81898. //DDSD_LINEARSIZE = 0x80000,
  81899. //DDSD_DEPTH = 0x800000;
  81900. // var DDSCAPS_COMPLEX = 0x8,
  81901. // DDSCAPS_MIPMAP = 0x400000,
  81902. // DDSCAPS_TEXTURE = 0x1000;
  81903. var DDSCAPS2_CUBEMAP = 0x200;
  81904. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  81905. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  81906. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  81907. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  81908. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  81909. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  81910. // DDSCAPS2_VOLUME = 0x200000;
  81911. var
  81912. //DDPF_ALPHAPIXELS = 0x1,
  81913. //DDPF_ALPHA = 0x2,
  81914. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  81915. //DDPF_YUV = 0x200,
  81916. DDPF_LUMINANCE = 0x20000;
  81917. function FourCCToInt32(value) {
  81918. return value.charCodeAt(0) +
  81919. (value.charCodeAt(1) << 8) +
  81920. (value.charCodeAt(2) << 16) +
  81921. (value.charCodeAt(3) << 24);
  81922. }
  81923. function Int32ToFourCC(value) {
  81924. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  81925. }
  81926. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  81927. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  81928. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  81929. var FOURCC_DX10 = FourCCToInt32("DX10");
  81930. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  81931. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  81932. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  81933. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  81934. var headerLengthInt = 31; // The header length in 32 bit ints
  81935. // Offsets into the header array
  81936. var off_magic = 0;
  81937. var off_size = 1;
  81938. var off_flags = 2;
  81939. var off_height = 3;
  81940. var off_width = 4;
  81941. var off_mipmapCount = 7;
  81942. var off_pfFlags = 20;
  81943. var off_pfFourCC = 21;
  81944. var off_RGBbpp = 22;
  81945. var off_RMask = 23;
  81946. var off_GMask = 24;
  81947. var off_BMask = 25;
  81948. var off_AMask = 26;
  81949. // var off_caps1 = 27;
  81950. var off_caps2 = 28;
  81951. // var off_caps3 = 29;
  81952. // var off_caps4 = 30;
  81953. var off_dxgiFormat = 32;
  81954. ;
  81955. var DDSTools = /** @class */ (function () {
  81956. function DDSTools() {
  81957. }
  81958. DDSTools.GetDDSInfo = function (arrayBuffer) {
  81959. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  81960. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  81961. var mipmapCount = 1;
  81962. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  81963. mipmapCount = Math.max(1, header[off_mipmapCount]);
  81964. }
  81965. var fourCC = header[off_pfFourCC];
  81966. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  81967. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81968. switch (fourCC) {
  81969. case FOURCC_D3DFMT_R16G16B16A16F:
  81970. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81971. break;
  81972. case FOURCC_D3DFMT_R32G32B32A32F:
  81973. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81974. break;
  81975. case FOURCC_DX10:
  81976. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  81977. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81978. break;
  81979. }
  81980. }
  81981. return {
  81982. width: header[off_width],
  81983. height: header[off_height],
  81984. mipmapCount: mipmapCount,
  81985. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  81986. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  81987. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  81988. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  81989. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  81990. dxgiFormat: dxgiFormat,
  81991. textureType: textureType
  81992. };
  81993. };
  81994. DDSTools._ToHalfFloat = function (value) {
  81995. if (!DDSTools._FloatView) {
  81996. DDSTools._FloatView = new Float32Array(1);
  81997. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  81998. }
  81999. DDSTools._FloatView[0] = value;
  82000. var x = DDSTools._Int32View[0];
  82001. var bits = (x >> 16) & 0x8000; /* Get the sign */
  82002. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  82003. var e = (x >> 23) & 0xff; /* Using int is faster here */
  82004. /* If zero, or denormal, or exponent underflows too much for a denormal
  82005. * half, return signed zero. */
  82006. if (e < 103) {
  82007. return bits;
  82008. }
  82009. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  82010. if (e > 142) {
  82011. bits |= 0x7c00;
  82012. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  82013. * not Inf, so make sure we set one mantissa bit too. */
  82014. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  82015. return bits;
  82016. }
  82017. /* If exponent underflows but not too much, return a denormal */
  82018. if (e < 113) {
  82019. m |= 0x0800;
  82020. /* Extra rounding may overflow and set mantissa to 0 and exponent
  82021. * to 1, which is OK. */
  82022. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  82023. return bits;
  82024. }
  82025. bits |= ((e - 112) << 10) | (m >> 1);
  82026. bits += m & 1;
  82027. return bits;
  82028. };
  82029. DDSTools._FromHalfFloat = function (value) {
  82030. var s = (value & 0x8000) >> 15;
  82031. var e = (value & 0x7C00) >> 10;
  82032. var f = value & 0x03FF;
  82033. if (e === 0) {
  82034. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  82035. }
  82036. else if (e == 0x1F) {
  82037. return f ? NaN : ((s ? -1 : 1) * Infinity);
  82038. }
  82039. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  82040. };
  82041. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82042. var destArray = new Float32Array(dataLength);
  82043. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82044. var index = 0;
  82045. for (var y = 0; y < height; y++) {
  82046. for (var x = 0; x < width; x++) {
  82047. var srcPos = (x + y * width) * 4;
  82048. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  82049. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  82050. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  82051. if (DDSTools.StoreLODInAlphaChannel) {
  82052. destArray[index + 3] = lod;
  82053. }
  82054. else {
  82055. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  82056. }
  82057. index += 4;
  82058. }
  82059. }
  82060. return destArray;
  82061. };
  82062. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82063. if (DDSTools.StoreLODInAlphaChannel) {
  82064. var destArray = new Uint16Array(dataLength);
  82065. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82066. var index = 0;
  82067. for (var y = 0; y < height; y++) {
  82068. for (var x = 0; x < width; x++) {
  82069. var srcPos = (x + y * width) * 4;
  82070. destArray[index] = srcData[srcPos];
  82071. destArray[index + 1] = srcData[srcPos + 1];
  82072. destArray[index + 2] = srcData[srcPos + 2];
  82073. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  82074. index += 4;
  82075. }
  82076. }
  82077. return destArray;
  82078. }
  82079. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  82080. };
  82081. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82082. if (DDSTools.StoreLODInAlphaChannel) {
  82083. var destArray = new Float32Array(dataLength);
  82084. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82085. var index = 0;
  82086. for (var y = 0; y < height; y++) {
  82087. for (var x = 0; x < width; x++) {
  82088. var srcPos = (x + y * width) * 4;
  82089. destArray[index] = srcData[srcPos];
  82090. destArray[index + 1] = srcData[srcPos + 1];
  82091. destArray[index + 2] = srcData[srcPos + 2];
  82092. destArray[index + 3] = lod;
  82093. index += 4;
  82094. }
  82095. }
  82096. return destArray;
  82097. }
  82098. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  82099. };
  82100. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82101. var destArray = new Uint8Array(dataLength);
  82102. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82103. var index = 0;
  82104. for (var y = 0; y < height; y++) {
  82105. for (var x = 0; x < width; x++) {
  82106. var srcPos = (x + y * width) * 4;
  82107. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  82108. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  82109. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  82110. if (DDSTools.StoreLODInAlphaChannel) {
  82111. destArray[index + 3] = lod;
  82112. }
  82113. else {
  82114. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  82115. }
  82116. index += 4;
  82117. }
  82118. }
  82119. return destArray;
  82120. };
  82121. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82122. var destArray = new Uint8Array(dataLength);
  82123. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82124. var index = 0;
  82125. for (var y = 0; y < height; y++) {
  82126. for (var x = 0; x < width; x++) {
  82127. var srcPos = (x + y * width) * 4;
  82128. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  82129. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  82130. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  82131. if (DDSTools.StoreLODInAlphaChannel) {
  82132. destArray[index + 3] = lod;
  82133. }
  82134. else {
  82135. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  82136. }
  82137. index += 4;
  82138. }
  82139. }
  82140. return destArray;
  82141. };
  82142. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  82143. var byteArray = new Uint8Array(dataLength);
  82144. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82145. var index = 0;
  82146. for (var y = 0; y < height; y++) {
  82147. for (var x = 0; x < width; x++) {
  82148. var srcPos = (x + y * width) * 4;
  82149. byteArray[index] = srcData[srcPos + rOffset];
  82150. byteArray[index + 1] = srcData[srcPos + gOffset];
  82151. byteArray[index + 2] = srcData[srcPos + bOffset];
  82152. byteArray[index + 3] = srcData[srcPos + aOffset];
  82153. index += 4;
  82154. }
  82155. }
  82156. return byteArray;
  82157. };
  82158. DDSTools._ExtractLongWordOrder = function (value) {
  82159. if (value === 0 || value === 255 || value === -16777216) {
  82160. return 0;
  82161. }
  82162. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  82163. };
  82164. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  82165. var byteArray = new Uint8Array(dataLength);
  82166. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82167. var index = 0;
  82168. for (var y = 0; y < height; y++) {
  82169. for (var x = 0; x < width; x++) {
  82170. var srcPos = (x + y * width) * 3;
  82171. byteArray[index] = srcData[srcPos + rOffset];
  82172. byteArray[index + 1] = srcData[srcPos + gOffset];
  82173. byteArray[index + 2] = srcData[srcPos + bOffset];
  82174. index += 3;
  82175. }
  82176. }
  82177. return byteArray;
  82178. };
  82179. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  82180. var byteArray = new Uint8Array(dataLength);
  82181. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82182. var index = 0;
  82183. for (var y = 0; y < height; y++) {
  82184. for (var x = 0; x < width; x++) {
  82185. var srcPos = (x + y * width);
  82186. byteArray[index] = srcData[srcPos];
  82187. index++;
  82188. }
  82189. }
  82190. return byteArray;
  82191. };
  82192. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  82193. if (lodIndex === void 0) { lodIndex = -1; }
  82194. var ext = engine.getCaps().s3tc;
  82195. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82196. var fourCC, width, height, dataLength = 0, dataOffset;
  82197. var byteArray, mipmapCount, mip;
  82198. var internalFormat = 0;
  82199. var format = 0;
  82200. var blockBytes = 1;
  82201. if (header[off_magic] !== DDS_MAGIC) {
  82202. BABYLON.Tools.Error("Invalid magic number in DDS header");
  82203. return;
  82204. }
  82205. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  82206. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  82207. return;
  82208. }
  82209. if (info.isCompressed && !ext) {
  82210. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  82211. return;
  82212. }
  82213. var bpp = header[off_RGBbpp];
  82214. dataOffset = header[off_size] + 4;
  82215. var computeFormats = false;
  82216. if (info.isFourCC) {
  82217. fourCC = header[off_pfFourCC];
  82218. switch (fourCC) {
  82219. case FOURCC_DXT1:
  82220. blockBytes = 8;
  82221. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  82222. break;
  82223. case FOURCC_DXT3:
  82224. blockBytes = 16;
  82225. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  82226. break;
  82227. case FOURCC_DXT5:
  82228. blockBytes = 16;
  82229. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  82230. break;
  82231. case FOURCC_D3DFMT_R16G16B16A16F:
  82232. computeFormats = true;
  82233. break;
  82234. case FOURCC_D3DFMT_R32G32B32A32F:
  82235. computeFormats = true;
  82236. break;
  82237. case FOURCC_DX10:
  82238. // There is an additionnal header so dataOffset need to be changed
  82239. dataOffset += 5 * 4; // 5 uints
  82240. var supported = false;
  82241. switch (info.dxgiFormat) {
  82242. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  82243. computeFormats = true;
  82244. supported = true;
  82245. break;
  82246. case DXGI_FORMAT_B8G8R8X8_UNORM:
  82247. info.isRGB = true;
  82248. info.isFourCC = false;
  82249. bpp = 32;
  82250. supported = true;
  82251. break;
  82252. }
  82253. if (supported) {
  82254. break;
  82255. }
  82256. default:
  82257. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  82258. return;
  82259. }
  82260. }
  82261. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  82262. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  82263. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  82264. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  82265. if (computeFormats) {
  82266. format = engine._getWebGLTextureType(info.textureType);
  82267. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82268. }
  82269. mipmapCount = 1;
  82270. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  82271. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82272. }
  82273. for (var face = 0; face < faces; face++) {
  82274. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  82275. width = header[off_width];
  82276. height = header[off_height];
  82277. for (mip = 0; mip < mipmapCount; ++mip) {
  82278. if (lodIndex === -1 || lodIndex === mip) {
  82279. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  82280. var i = (lodIndex === -1) ? mip : 0;
  82281. if (!info.isCompressed && info.isFourCC) {
  82282. dataLength = width * height * 4;
  82283. var floatArray = null;
  82284. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  82285. if (bpp === 128) {
  82286. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82287. }
  82288. else if (bpp === 64) {
  82289. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82290. }
  82291. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82292. format = engine._getWebGLTextureType(info.textureType);
  82293. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82294. }
  82295. else {
  82296. if (bpp === 128) {
  82297. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82298. }
  82299. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  82300. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82301. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82302. format = engine._getWebGLTextureType(info.textureType);
  82303. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82304. }
  82305. else {
  82306. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82307. }
  82308. }
  82309. if (floatArray) {
  82310. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  82311. }
  82312. }
  82313. else if (info.isRGB) {
  82314. if (bpp === 24) {
  82315. dataLength = width * height * 3;
  82316. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  82317. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  82318. }
  82319. else {
  82320. dataLength = width * height * 4;
  82321. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  82322. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  82323. }
  82324. }
  82325. else if (info.isLuminance) {
  82326. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  82327. var unpaddedRowSize = width;
  82328. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  82329. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  82330. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  82331. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  82332. }
  82333. else {
  82334. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  82335. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  82336. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  82337. }
  82338. }
  82339. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  82340. width *= 0.5;
  82341. height *= 0.5;
  82342. width = Math.max(1.0, width);
  82343. height = Math.max(1.0, height);
  82344. }
  82345. if (currentFace !== undefined) {
  82346. // Loading a single face
  82347. break;
  82348. }
  82349. }
  82350. };
  82351. DDSTools.StoreLODInAlphaChannel = false;
  82352. return DDSTools;
  82353. }());
  82354. BABYLON.DDSTools = DDSTools;
  82355. })(BABYLON || (BABYLON = {}));
  82356. //# sourceMappingURL=babylon.dds.js.map
  82357. "use strict";
  82358. var BABYLON;
  82359. (function (BABYLON) {
  82360. /**
  82361. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  82362. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  82363. */
  82364. var KhronosTextureContainer = /** @class */ (function () {
  82365. /**
  82366. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  82367. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  82368. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  82369. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  82370. */
  82371. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  82372. this.arrayBuffer = arrayBuffer;
  82373. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  82374. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  82375. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  82376. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  82377. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  82378. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  82379. BABYLON.Tools.Error("texture missing KTX identifier");
  82380. return;
  82381. }
  82382. // load the reset of the header in native 32 bit int
  82383. var header = new Int32Array(this.arrayBuffer, 12, 13);
  82384. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  82385. var oppositeEndianess = header[0] === 0x01020304;
  82386. // read all the header elements in order they exist in the file, without modification (sans endainness)
  82387. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  82388. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  82389. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  82390. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  82391. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  82392. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  82393. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  82394. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  82395. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  82396. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  82397. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  82398. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  82399. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  82400. if (this.glType !== 0) {
  82401. BABYLON.Tools.Error("only compressed formats currently supported");
  82402. return;
  82403. }
  82404. else {
  82405. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  82406. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  82407. }
  82408. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  82409. BABYLON.Tools.Error("only 2D textures currently supported");
  82410. return;
  82411. }
  82412. if (this.numberOfArrayElements !== 0) {
  82413. BABYLON.Tools.Error("texture arrays not currently supported");
  82414. return;
  82415. }
  82416. if (this.numberOfFaces !== facesExpected) {
  82417. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  82418. return;
  82419. }
  82420. // we now have a completely validated file, so could use existence of loadType as success
  82421. // would need to make this more elaborate & adjust checks above to support more than one load type
  82422. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  82423. }
  82424. // not as fast hardware based, but will probably never need to use
  82425. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  82426. return ((val & 0xFF) << 24)
  82427. | ((val & 0xFF00) << 8)
  82428. | ((val >> 8) & 0xFF00)
  82429. | ((val >> 24) & 0xFF);
  82430. };
  82431. /**
  82432. * It is assumed that the texture has already been created & is currently bound
  82433. */
  82434. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  82435. switch (this.loadType) {
  82436. case KhronosTextureContainer.COMPRESSED_2D:
  82437. this._upload2DCompressedLevels(gl, loadMipmaps);
  82438. break;
  82439. case KhronosTextureContainer.TEX_2D:
  82440. case KhronosTextureContainer.COMPRESSED_3D:
  82441. case KhronosTextureContainer.TEX_3D:
  82442. }
  82443. };
  82444. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  82445. // initialize width & height for level 1
  82446. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  82447. var width = this.pixelWidth;
  82448. var height = this.pixelHeight;
  82449. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  82450. for (var level = 0; level < mipmapCount; level++) {
  82451. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  82452. for (var face = 0; face < this.numberOfFaces; face++) {
  82453. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  82454. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  82455. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  82456. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  82457. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  82458. }
  82459. width = Math.max(1.0, width * 0.5);
  82460. height = Math.max(1.0, height * 0.5);
  82461. }
  82462. };
  82463. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  82464. // load types
  82465. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  82466. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  82467. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  82468. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  82469. return KhronosTextureContainer;
  82470. }());
  82471. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  82472. })(BABYLON || (BABYLON = {}));
  82473. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  82474. "use strict";
  82475. var BABYLON;
  82476. (function (BABYLON) {
  82477. var Debug;
  82478. (function (Debug) {
  82479. /**
  82480. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  82481. */
  82482. var SkeletonViewer = /** @class */ (function () {
  82483. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  82484. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  82485. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  82486. this.skeleton = skeleton;
  82487. this.mesh = mesh;
  82488. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  82489. this.renderingGroupId = renderingGroupId;
  82490. this.color = BABYLON.Color3.White();
  82491. this._debugLines = new Array();
  82492. this._isEnabled = false;
  82493. this._scene = scene;
  82494. this.update();
  82495. this._renderFunction = this.update.bind(this);
  82496. }
  82497. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  82498. get: function () {
  82499. return this._isEnabled;
  82500. },
  82501. set: function (value) {
  82502. if (this._isEnabled === value) {
  82503. return;
  82504. }
  82505. this._isEnabled = value;
  82506. if (value) {
  82507. this._scene.registerBeforeRender(this._renderFunction);
  82508. }
  82509. else {
  82510. this._scene.unregisterBeforeRender(this._renderFunction);
  82511. }
  82512. },
  82513. enumerable: true,
  82514. configurable: true
  82515. });
  82516. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  82517. if (x === void 0) { x = 0; }
  82518. if (y === void 0) { y = 0; }
  82519. if (z === void 0) { z = 0; }
  82520. var tmat = BABYLON.Tmp.Matrix[0];
  82521. var parentBone = bone.getParent();
  82522. tmat.copyFrom(bone.getLocalMatrix());
  82523. if (x !== 0 || y !== 0 || z !== 0) {
  82524. var tmat2 = BABYLON.Tmp.Matrix[1];
  82525. BABYLON.Matrix.IdentityToRef(tmat2);
  82526. tmat2.m[12] = x;
  82527. tmat2.m[13] = y;
  82528. tmat2.m[14] = z;
  82529. tmat2.multiplyToRef(tmat, tmat);
  82530. }
  82531. if (parentBone) {
  82532. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  82533. }
  82534. tmat.multiplyToRef(meshMat, tmat);
  82535. position.x = tmat.m[12];
  82536. position.y = tmat.m[13];
  82537. position.z = tmat.m[14];
  82538. };
  82539. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  82540. var len = bones.length;
  82541. var meshPos = this.mesh.position;
  82542. for (var i = 0; i < len; i++) {
  82543. var bone = bones[i];
  82544. var points = this._debugLines[i];
  82545. if (!points) {
  82546. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82547. this._debugLines[i] = points;
  82548. }
  82549. this._getBonePosition(points[0], bone, meshMat);
  82550. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  82551. points[0].subtractInPlace(meshPos);
  82552. points[1].subtractInPlace(meshPos);
  82553. }
  82554. };
  82555. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  82556. var len = bones.length;
  82557. var boneNum = 0;
  82558. var meshPos = this.mesh.position;
  82559. for (var i = len - 1; i >= 0; i--) {
  82560. var childBone = bones[i];
  82561. var parentBone = childBone.getParent();
  82562. if (!parentBone) {
  82563. continue;
  82564. }
  82565. var points = this._debugLines[boneNum];
  82566. if (!points) {
  82567. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82568. this._debugLines[boneNum] = points;
  82569. }
  82570. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  82571. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  82572. points[0].subtractInPlace(meshPos);
  82573. points[1].subtractInPlace(meshPos);
  82574. boneNum++;
  82575. }
  82576. };
  82577. SkeletonViewer.prototype.update = function () {
  82578. if (this.autoUpdateBonesMatrices) {
  82579. this.skeleton.computeAbsoluteTransforms();
  82580. }
  82581. if (this.skeleton.bones[0].length === undefined) {
  82582. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  82583. }
  82584. else {
  82585. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  82586. }
  82587. if (!this._debugMesh) {
  82588. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  82589. this._debugMesh.renderingGroupId = this.renderingGroupId;
  82590. }
  82591. else {
  82592. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  82593. }
  82594. this._debugMesh.position.copyFrom(this.mesh.position);
  82595. this._debugMesh.color = this.color;
  82596. };
  82597. SkeletonViewer.prototype.dispose = function () {
  82598. if (this._debugMesh) {
  82599. this.isEnabled = false;
  82600. this._debugMesh.dispose();
  82601. this._debugMesh = null;
  82602. }
  82603. };
  82604. return SkeletonViewer;
  82605. }());
  82606. Debug.SkeletonViewer = SkeletonViewer;
  82607. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82608. })(BABYLON || (BABYLON = {}));
  82609. //# sourceMappingURL=babylon.skeletonViewer.js.map
  82610. "use strict";
  82611. /**
  82612. * Module Debug contains the (visual) components to debug a scene correctly
  82613. */
  82614. var BABYLON;
  82615. (function (BABYLON) {
  82616. var Debug;
  82617. (function (Debug) {
  82618. /**
  82619. * The Axes viewer will show 3 axes in a specific point in space
  82620. */
  82621. var AxesViewer = /** @class */ (function () {
  82622. function AxesViewer(scene, scaleLines) {
  82623. if (scaleLines === void 0) { scaleLines = 1; }
  82624. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82625. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82626. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82627. this.scaleLines = 1;
  82628. this.scaleLines = scaleLines;
  82629. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  82630. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  82631. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  82632. this._xmesh.renderingGroupId = 2;
  82633. this._ymesh.renderingGroupId = 2;
  82634. this._zmesh.renderingGroupId = 2;
  82635. this._xmesh.material.checkReadyOnlyOnce = true;
  82636. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  82637. this._ymesh.material.checkReadyOnlyOnce = true;
  82638. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  82639. this._zmesh.material.checkReadyOnlyOnce = true;
  82640. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  82641. this.scene = scene;
  82642. }
  82643. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  82644. var scaleLines = this.scaleLines;
  82645. if (this._xmesh) {
  82646. this._xmesh.position.copyFrom(position);
  82647. }
  82648. if (this._ymesh) {
  82649. this._ymesh.position.copyFrom(position);
  82650. }
  82651. if (this._zmesh) {
  82652. this._zmesh.position.copyFrom(position);
  82653. }
  82654. var point2 = this._xline[1];
  82655. point2.x = xaxis.x * scaleLines;
  82656. point2.y = xaxis.y * scaleLines;
  82657. point2.z = xaxis.z * scaleLines;
  82658. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  82659. point2 = this._yline[1];
  82660. point2.x = yaxis.x * scaleLines;
  82661. point2.y = yaxis.y * scaleLines;
  82662. point2.z = yaxis.z * scaleLines;
  82663. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  82664. point2 = this._zline[1];
  82665. point2.x = zaxis.x * scaleLines;
  82666. point2.y = zaxis.y * scaleLines;
  82667. point2.z = zaxis.z * scaleLines;
  82668. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  82669. };
  82670. AxesViewer.prototype.dispose = function () {
  82671. if (this._xmesh) {
  82672. this._xmesh.dispose();
  82673. }
  82674. if (this._ymesh) {
  82675. this._ymesh.dispose();
  82676. }
  82677. if (this._zmesh) {
  82678. this._zmesh.dispose();
  82679. }
  82680. this._xmesh = null;
  82681. this._ymesh = null;
  82682. this._zmesh = null;
  82683. this.scene = null;
  82684. };
  82685. return AxesViewer;
  82686. }());
  82687. Debug.AxesViewer = AxesViewer;
  82688. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82689. })(BABYLON || (BABYLON = {}));
  82690. //# sourceMappingURL=babylon.axesViewer.js.map
  82691. "use strict";
  82692. var BABYLON;
  82693. (function (BABYLON) {
  82694. var Debug;
  82695. (function (Debug) {
  82696. /**
  82697. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  82698. */
  82699. var BoneAxesViewer = /** @class */ (function (_super) {
  82700. __extends(BoneAxesViewer, _super);
  82701. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  82702. if (scaleLines === void 0) { scaleLines = 1; }
  82703. var _this = _super.call(this, scene, scaleLines) || this;
  82704. _this.pos = BABYLON.Vector3.Zero();
  82705. _this.xaxis = BABYLON.Vector3.Zero();
  82706. _this.yaxis = BABYLON.Vector3.Zero();
  82707. _this.zaxis = BABYLON.Vector3.Zero();
  82708. _this.mesh = mesh;
  82709. _this.bone = bone;
  82710. return _this;
  82711. }
  82712. BoneAxesViewer.prototype.update = function () {
  82713. if (!this.mesh || !this.bone) {
  82714. return;
  82715. }
  82716. var bone = this.bone;
  82717. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  82718. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  82719. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  82720. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  82721. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  82722. };
  82723. BoneAxesViewer.prototype.dispose = function () {
  82724. if (this.mesh) {
  82725. this.mesh = null;
  82726. this.bone = null;
  82727. _super.prototype.dispose.call(this);
  82728. }
  82729. };
  82730. return BoneAxesViewer;
  82731. }(Debug.AxesViewer));
  82732. Debug.BoneAxesViewer = BoneAxesViewer;
  82733. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  82734. })(BABYLON || (BABYLON = {}));
  82735. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  82736. "use strict";
  82737. var BABYLON;
  82738. (function (BABYLON) {
  82739. var RayHelper = /** @class */ (function () {
  82740. function RayHelper(ray) {
  82741. this.ray = ray;
  82742. }
  82743. RayHelper.CreateAndShow = function (ray, scene, color) {
  82744. var helper = new RayHelper(ray);
  82745. helper.show(scene, color);
  82746. return helper;
  82747. };
  82748. RayHelper.prototype.show = function (scene, color) {
  82749. if (!this._renderFunction && this.ray) {
  82750. var ray = this.ray;
  82751. this._renderFunction = this._render.bind(this);
  82752. this._scene = scene;
  82753. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  82754. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  82755. if (this._renderFunction) {
  82756. this._scene.registerBeforeRender(this._renderFunction);
  82757. }
  82758. }
  82759. if (color && this._renderLine) {
  82760. this._renderLine.color.copyFrom(color);
  82761. }
  82762. };
  82763. RayHelper.prototype.hide = function () {
  82764. if (this._renderFunction && this._scene) {
  82765. this._scene.unregisterBeforeRender(this._renderFunction);
  82766. this._scene = null;
  82767. this._renderFunction = null;
  82768. if (this._renderLine) {
  82769. this._renderLine.dispose();
  82770. this._renderLine = null;
  82771. }
  82772. this._renderPoints = [];
  82773. }
  82774. };
  82775. RayHelper.prototype._render = function () {
  82776. var ray = this.ray;
  82777. if (!ray) {
  82778. return;
  82779. }
  82780. var point = this._renderPoints[1];
  82781. var len = Math.min(ray.length, 1000000);
  82782. point.copyFrom(ray.direction);
  82783. point.scaleInPlace(len);
  82784. point.addInPlace(ray.origin);
  82785. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  82786. };
  82787. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  82788. this._attachedToMesh = mesh;
  82789. var ray = this.ray;
  82790. if (!ray) {
  82791. return;
  82792. }
  82793. if (!ray.direction) {
  82794. ray.direction = BABYLON.Vector3.Zero();
  82795. }
  82796. if (!ray.origin) {
  82797. ray.origin = BABYLON.Vector3.Zero();
  82798. }
  82799. if (length) {
  82800. ray.length = length;
  82801. }
  82802. if (!meshSpaceOrigin) {
  82803. meshSpaceOrigin = BABYLON.Vector3.Zero();
  82804. }
  82805. if (!meshSpaceDirection) {
  82806. // -1 so that this will work with Mesh.lookAt
  82807. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  82808. }
  82809. if (!this._meshSpaceDirection) {
  82810. this._meshSpaceDirection = meshSpaceDirection.clone();
  82811. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  82812. }
  82813. else {
  82814. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  82815. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  82816. }
  82817. if (!this._updateToMeshFunction) {
  82818. this._updateToMeshFunction = this._updateToMesh.bind(this);
  82819. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  82820. }
  82821. this._updateToMesh();
  82822. };
  82823. RayHelper.prototype.detachFromMesh = function () {
  82824. if (this._attachedToMesh) {
  82825. if (this._updateToMeshFunction) {
  82826. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  82827. }
  82828. this._attachedToMesh = null;
  82829. this._updateToMeshFunction = null;
  82830. }
  82831. };
  82832. RayHelper.prototype._updateToMesh = function () {
  82833. var ray = this.ray;
  82834. if (!this._attachedToMesh || !ray) {
  82835. return;
  82836. }
  82837. if (this._attachedToMesh._isDisposed) {
  82838. this.detachFromMesh();
  82839. return;
  82840. }
  82841. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  82842. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  82843. };
  82844. RayHelper.prototype.dispose = function () {
  82845. this.hide();
  82846. this.detachFromMesh();
  82847. this.ray = null;
  82848. };
  82849. return RayHelper;
  82850. }());
  82851. BABYLON.RayHelper = RayHelper;
  82852. })(BABYLON || (BABYLON = {}));
  82853. //# sourceMappingURL=babylon.rayHelper.js.map
  82854. "use strict";
  82855. var BABYLON;
  82856. (function (BABYLON) {
  82857. // load the inspector using require, if not present in the global namespace.
  82858. var DebugLayer = /** @class */ (function () {
  82859. function DebugLayer(scene) {
  82860. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  82861. this._scene = scene;
  82862. // load inspector using require, if it doesn't exist on the global namespace.
  82863. }
  82864. /** Creates the inspector window. */
  82865. DebugLayer.prototype._createInspector = function (config) {
  82866. if (config === void 0) { config = {}; }
  82867. var popup = config.popup || false;
  82868. var initialTab = config.initialTab || 0;
  82869. var parentElement = config.parentElement || null;
  82870. if (!this._inspector) {
  82871. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  82872. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  82873. } // else nothing to do,; instance is already existing
  82874. };
  82875. DebugLayer.prototype.isVisible = function () {
  82876. if (!this._inspector) {
  82877. return false;
  82878. }
  82879. return true;
  82880. };
  82881. DebugLayer.prototype.hide = function () {
  82882. if (this._inspector) {
  82883. try {
  82884. this._inspector.dispose();
  82885. }
  82886. catch (e) {
  82887. // If the inspector has been removed directly from the inspector tool
  82888. }
  82889. this._inspector = null;
  82890. }
  82891. };
  82892. DebugLayer.prototype.show = function (config) {
  82893. if (config === void 0) { config = {}; }
  82894. if (typeof this.BJSINSPECTOR == 'undefined') {
  82895. // Load inspector and add it to the DOM
  82896. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  82897. }
  82898. else {
  82899. // Otherwise creates the inspector
  82900. this._createInspector(config);
  82901. }
  82902. };
  82903. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  82904. return DebugLayer;
  82905. }());
  82906. BABYLON.DebugLayer = DebugLayer;
  82907. })(BABYLON || (BABYLON = {}));
  82908. //# sourceMappingURL=babylon.debugLayer.js.map
  82909. "use strict";
  82910. var BABYLON;
  82911. (function (BABYLON) {
  82912. var Debug;
  82913. (function (Debug) {
  82914. /**
  82915. * Used to show the physics impostor around the specific mesh.
  82916. */
  82917. var PhysicsViewer = /** @class */ (function () {
  82918. function PhysicsViewer(scene) {
  82919. this._impostors = [];
  82920. this._meshes = [];
  82921. this._numMeshes = 0;
  82922. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82923. var physicEngine = this._scene.getPhysicsEngine();
  82924. if (physicEngine) {
  82925. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  82926. }
  82927. }
  82928. PhysicsViewer.prototype._updateDebugMeshes = function () {
  82929. var plugin = this._physicsEnginePlugin;
  82930. for (var i = 0; i < this._numMeshes; i++) {
  82931. var impostor = this._impostors[i];
  82932. if (!impostor) {
  82933. continue;
  82934. }
  82935. if (impostor.isDisposed) {
  82936. this.hideImpostor(this._impostors[i--]);
  82937. }
  82938. else {
  82939. var mesh = this._meshes[i];
  82940. if (mesh && plugin) {
  82941. plugin.syncMeshWithImpostor(mesh, impostor);
  82942. }
  82943. }
  82944. }
  82945. };
  82946. PhysicsViewer.prototype.showImpostor = function (impostor) {
  82947. if (!this._scene) {
  82948. return;
  82949. }
  82950. for (var i = 0; i < this._numMeshes; i++) {
  82951. if (this._impostors[i] == impostor) {
  82952. return;
  82953. }
  82954. }
  82955. var debugMesh = this._getDebugMesh(impostor, this._scene);
  82956. if (debugMesh) {
  82957. this._impostors[this._numMeshes] = impostor;
  82958. this._meshes[this._numMeshes] = debugMesh;
  82959. if (this._numMeshes === 0) {
  82960. this._renderFunction = this._updateDebugMeshes.bind(this);
  82961. this._scene.registerBeforeRender(this._renderFunction);
  82962. }
  82963. this._numMeshes++;
  82964. }
  82965. };
  82966. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  82967. if (!impostor || !this._scene) {
  82968. return;
  82969. }
  82970. var removed = false;
  82971. for (var i = 0; i < this._numMeshes; i++) {
  82972. if (this._impostors[i] == impostor) {
  82973. var mesh = this._meshes[i];
  82974. if (!mesh) {
  82975. continue;
  82976. }
  82977. this._scene.removeMesh(mesh);
  82978. mesh.dispose();
  82979. this._numMeshes--;
  82980. if (this._numMeshes > 0) {
  82981. this._meshes[i] = this._meshes[this._numMeshes];
  82982. this._impostors[i] = this._impostors[this._numMeshes];
  82983. this._meshes[this._numMeshes] = null;
  82984. this._impostors[this._numMeshes] = null;
  82985. }
  82986. else {
  82987. this._meshes[0] = null;
  82988. this._impostors[0] = null;
  82989. }
  82990. removed = true;
  82991. break;
  82992. }
  82993. }
  82994. if (removed && this._numMeshes === 0) {
  82995. this._scene.unregisterBeforeRender(this._renderFunction);
  82996. }
  82997. };
  82998. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  82999. if (!this._debugMaterial) {
  83000. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  83001. this._debugMaterial.wireframe = true;
  83002. }
  83003. return this._debugMaterial;
  83004. };
  83005. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  83006. if (!this._debugBoxMesh) {
  83007. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  83008. this._debugBoxMesh.renderingGroupId = 1;
  83009. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83010. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  83011. scene.removeMesh(this._debugBoxMesh);
  83012. }
  83013. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  83014. };
  83015. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  83016. if (!this._debugSphereMesh) {
  83017. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  83018. this._debugSphereMesh.renderingGroupId = 1;
  83019. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83020. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  83021. scene.removeMesh(this._debugSphereMesh);
  83022. }
  83023. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  83024. };
  83025. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  83026. var mesh = null;
  83027. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  83028. mesh = this._getDebugBoxMesh(scene);
  83029. impostor.getBoxSizeToRef(mesh.scaling);
  83030. }
  83031. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  83032. mesh = this._getDebugSphereMesh(scene);
  83033. var radius = impostor.getRadius();
  83034. mesh.scaling.x = radius * 2;
  83035. mesh.scaling.y = radius * 2;
  83036. mesh.scaling.z = radius * 2;
  83037. }
  83038. return mesh;
  83039. };
  83040. PhysicsViewer.prototype.dispose = function () {
  83041. for (var i = 0; i < this._numMeshes; i++) {
  83042. this.hideImpostor(this._impostors[i]);
  83043. }
  83044. if (this._debugBoxMesh) {
  83045. this._debugBoxMesh.dispose();
  83046. }
  83047. if (this._debugSphereMesh) {
  83048. this._debugSphereMesh.dispose();
  83049. }
  83050. if (this._debugMaterial) {
  83051. this._debugMaterial.dispose();
  83052. }
  83053. this._impostors.length = 0;
  83054. this._scene = null;
  83055. this._physicsEnginePlugin = null;
  83056. };
  83057. return PhysicsViewer;
  83058. }());
  83059. Debug.PhysicsViewer = PhysicsViewer;
  83060. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83061. })(BABYLON || (BABYLON = {}));
  83062. //# sourceMappingURL=babylon.physicsViewer.js.map
  83063. "use strict";
  83064. var BABYLON;
  83065. (function (BABYLON) {
  83066. var BoundingBoxRenderer = /** @class */ (function () {
  83067. function BoundingBoxRenderer(scene) {
  83068. this.frontColor = new BABYLON.Color3(1, 1, 1);
  83069. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  83070. this.showBackLines = true;
  83071. this.renderList = new BABYLON.SmartArray(32);
  83072. this._vertexBuffers = {};
  83073. this._scene = scene;
  83074. }
  83075. BoundingBoxRenderer.prototype._prepareRessources = function () {
  83076. if (this._colorShader) {
  83077. return;
  83078. }
  83079. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  83080. attributes: [BABYLON.VertexBuffer.PositionKind],
  83081. uniforms: ["world", "viewProjection", "color"]
  83082. });
  83083. var engine = this._scene.getEngine();
  83084. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  83085. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  83086. this._createIndexBuffer();
  83087. };
  83088. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  83089. var engine = this._scene.getEngine();
  83090. 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]);
  83091. };
  83092. BoundingBoxRenderer.prototype._rebuild = function () {
  83093. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83094. if (vb) {
  83095. vb._rebuild();
  83096. }
  83097. this._createIndexBuffer();
  83098. };
  83099. BoundingBoxRenderer.prototype.reset = function () {
  83100. this.renderList.reset();
  83101. };
  83102. BoundingBoxRenderer.prototype.render = function () {
  83103. if (this.renderList.length === 0) {
  83104. return;
  83105. }
  83106. this._prepareRessources();
  83107. if (!this._colorShader.isReady()) {
  83108. return;
  83109. }
  83110. var engine = this._scene.getEngine();
  83111. engine.setDepthWrite(false);
  83112. this._colorShader._preBind();
  83113. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  83114. var boundingBox = this.renderList.data[boundingBoxIndex];
  83115. var min = boundingBox.minimum;
  83116. var max = boundingBox.maximum;
  83117. var diff = max.subtract(min);
  83118. var median = min.add(diff.scale(0.5));
  83119. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83120. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83121. .multiply(boundingBox.getWorldMatrix());
  83122. // VBOs
  83123. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83124. if (this.showBackLines) {
  83125. // Back
  83126. engine.setDepthFunctionToGreaterOrEqual();
  83127. this._scene.resetCachedMaterial();
  83128. this._colorShader.setColor4("color", this.backColor.toColor4());
  83129. this._colorShader.bind(worldMatrix);
  83130. // Draw order
  83131. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83132. }
  83133. // Front
  83134. engine.setDepthFunctionToLess();
  83135. this._scene.resetCachedMaterial();
  83136. this._colorShader.setColor4("color", this.frontColor.toColor4());
  83137. this._colorShader.bind(worldMatrix);
  83138. // Draw order
  83139. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83140. }
  83141. this._colorShader.unbind();
  83142. engine.setDepthFunctionToLessOrEqual();
  83143. engine.setDepthWrite(true);
  83144. };
  83145. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  83146. this._prepareRessources();
  83147. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  83148. return;
  83149. }
  83150. var engine = this._scene.getEngine();
  83151. engine.setDepthWrite(false);
  83152. engine.setColorWrite(false);
  83153. this._colorShader._preBind();
  83154. var boundingBox = mesh._boundingInfo.boundingBox;
  83155. var min = boundingBox.minimum;
  83156. var max = boundingBox.maximum;
  83157. var diff = max.subtract(min);
  83158. var median = min.add(diff.scale(0.5));
  83159. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83160. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83161. .multiply(boundingBox.getWorldMatrix());
  83162. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83163. engine.setDepthFunctionToLess();
  83164. this._scene.resetCachedMaterial();
  83165. this._colorShader.bind(worldMatrix);
  83166. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83167. this._colorShader.unbind();
  83168. engine.setDepthFunctionToLessOrEqual();
  83169. engine.setDepthWrite(true);
  83170. engine.setColorWrite(true);
  83171. };
  83172. BoundingBoxRenderer.prototype.dispose = function () {
  83173. if (!this._colorShader) {
  83174. return;
  83175. }
  83176. this.renderList.dispose();
  83177. this._colorShader.dispose();
  83178. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83179. if (buffer) {
  83180. buffer.dispose();
  83181. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83182. }
  83183. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83184. };
  83185. return BoundingBoxRenderer;
  83186. }());
  83187. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  83188. })(BABYLON || (BABYLON = {}));
  83189. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  83190. "use strict";
  83191. var BABYLON;
  83192. (function (BABYLON) {
  83193. var MorphTarget = /** @class */ (function () {
  83194. function MorphTarget(name, influence) {
  83195. if (influence === void 0) { influence = 0; }
  83196. this.name = name;
  83197. this.animations = new Array();
  83198. this._positions = null;
  83199. this._normals = null;
  83200. this._tangents = null;
  83201. this.onInfluenceChanged = new BABYLON.Observable();
  83202. this.influence = influence;
  83203. }
  83204. Object.defineProperty(MorphTarget.prototype, "influence", {
  83205. get: function () {
  83206. return this._influence;
  83207. },
  83208. set: function (influence) {
  83209. if (this._influence === influence) {
  83210. return;
  83211. }
  83212. var previous = this._influence;
  83213. this._influence = influence;
  83214. if (this.onInfluenceChanged.hasObservers) {
  83215. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  83216. }
  83217. },
  83218. enumerable: true,
  83219. configurable: true
  83220. });
  83221. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  83222. get: function () {
  83223. return !!this._positions;
  83224. },
  83225. enumerable: true,
  83226. configurable: true
  83227. });
  83228. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  83229. get: function () {
  83230. return !!this._normals;
  83231. },
  83232. enumerable: true,
  83233. configurable: true
  83234. });
  83235. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  83236. get: function () {
  83237. return !!this._tangents;
  83238. },
  83239. enumerable: true,
  83240. configurable: true
  83241. });
  83242. MorphTarget.prototype.setPositions = function (data) {
  83243. this._positions = data;
  83244. };
  83245. MorphTarget.prototype.getPositions = function () {
  83246. return this._positions;
  83247. };
  83248. MorphTarget.prototype.setNormals = function (data) {
  83249. this._normals = data;
  83250. };
  83251. MorphTarget.prototype.getNormals = function () {
  83252. return this._normals;
  83253. };
  83254. MorphTarget.prototype.setTangents = function (data) {
  83255. this._tangents = data;
  83256. };
  83257. MorphTarget.prototype.getTangents = function () {
  83258. return this._tangents;
  83259. };
  83260. /**
  83261. * Serializes the current target into a Serialization object.
  83262. * Returns the serialized object.
  83263. */
  83264. MorphTarget.prototype.serialize = function () {
  83265. var serializationObject = {};
  83266. serializationObject.name = this.name;
  83267. serializationObject.influence = this.influence;
  83268. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  83269. if (this.hasNormals) {
  83270. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  83271. }
  83272. if (this.hasTangents) {
  83273. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  83274. }
  83275. // Animations
  83276. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  83277. return serializationObject;
  83278. };
  83279. // Statics
  83280. MorphTarget.Parse = function (serializationObject) {
  83281. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  83282. result.setPositions(serializationObject.positions);
  83283. if (serializationObject.normals) {
  83284. result.setNormals(serializationObject.normals);
  83285. }
  83286. if (serializationObject.tangents) {
  83287. result.setTangents(serializationObject.tangents);
  83288. }
  83289. // Animations
  83290. if (serializationObject.animations) {
  83291. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  83292. var parsedAnimation = serializationObject.animations[animationIndex];
  83293. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  83294. }
  83295. }
  83296. return result;
  83297. };
  83298. MorphTarget.FromMesh = function (mesh, name, influence) {
  83299. if (!name) {
  83300. name = mesh.name;
  83301. }
  83302. var result = new MorphTarget(name, influence);
  83303. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83305. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  83306. }
  83307. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  83308. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  83309. }
  83310. return result;
  83311. };
  83312. return MorphTarget;
  83313. }());
  83314. BABYLON.MorphTarget = MorphTarget;
  83315. })(BABYLON || (BABYLON = {}));
  83316. //# sourceMappingURL=babylon.morphTarget.js.map
  83317. "use strict";
  83318. var BABYLON;
  83319. (function (BABYLON) {
  83320. var MorphTargetManager = /** @class */ (function () {
  83321. function MorphTargetManager(scene) {
  83322. if (scene === void 0) { scene = null; }
  83323. this._targets = new Array();
  83324. this._targetObservable = new Array();
  83325. this._activeTargets = new BABYLON.SmartArray(16);
  83326. this._supportsNormals = false;
  83327. this._supportsTangents = false;
  83328. this._vertexCount = 0;
  83329. this._uniqueId = 0;
  83330. this._tempInfluences = new Array();
  83331. if (!scene) {
  83332. scene = BABYLON.Engine.LastCreatedScene;
  83333. }
  83334. this._scene = scene;
  83335. if (this._scene) {
  83336. this._scene.morphTargetManagers.push(this);
  83337. this._uniqueId = this._scene.getUniqueId();
  83338. }
  83339. }
  83340. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  83341. get: function () {
  83342. return this._uniqueId;
  83343. },
  83344. enumerable: true,
  83345. configurable: true
  83346. });
  83347. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  83348. get: function () {
  83349. return this._vertexCount;
  83350. },
  83351. enumerable: true,
  83352. configurable: true
  83353. });
  83354. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  83355. get: function () {
  83356. return this._supportsNormals;
  83357. },
  83358. enumerable: true,
  83359. configurable: true
  83360. });
  83361. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  83362. get: function () {
  83363. return this._supportsTangents;
  83364. },
  83365. enumerable: true,
  83366. configurable: true
  83367. });
  83368. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  83369. get: function () {
  83370. return this._targets.length;
  83371. },
  83372. enumerable: true,
  83373. configurable: true
  83374. });
  83375. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  83376. get: function () {
  83377. return this._activeTargets.length;
  83378. },
  83379. enumerable: true,
  83380. configurable: true
  83381. });
  83382. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  83383. get: function () {
  83384. return this._influences;
  83385. },
  83386. enumerable: true,
  83387. configurable: true
  83388. });
  83389. MorphTargetManager.prototype.getActiveTarget = function (index) {
  83390. return this._activeTargets.data[index];
  83391. };
  83392. MorphTargetManager.prototype.getTarget = function (index) {
  83393. return this._targets[index];
  83394. };
  83395. MorphTargetManager.prototype.addTarget = function (target) {
  83396. var _this = this;
  83397. this._targets.push(target);
  83398. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  83399. _this._syncActiveTargets(needUpdate);
  83400. }));
  83401. this._syncActiveTargets(true);
  83402. };
  83403. MorphTargetManager.prototype.removeTarget = function (target) {
  83404. var index = this._targets.indexOf(target);
  83405. if (index >= 0) {
  83406. this._targets.splice(index, 1);
  83407. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  83408. this._syncActiveTargets(true);
  83409. }
  83410. };
  83411. /**
  83412. * Serializes the current manager into a Serialization object.
  83413. * Returns the serialized object.
  83414. */
  83415. MorphTargetManager.prototype.serialize = function () {
  83416. var serializationObject = {};
  83417. serializationObject.id = this.uniqueId;
  83418. serializationObject.targets = [];
  83419. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83420. var target = _a[_i];
  83421. serializationObject.targets.push(target.serialize());
  83422. }
  83423. return serializationObject;
  83424. };
  83425. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  83426. var influenceCount = 0;
  83427. this._activeTargets.reset();
  83428. this._supportsNormals = true;
  83429. this._supportsTangents = true;
  83430. this._vertexCount = 0;
  83431. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83432. var target = _a[_i];
  83433. this._activeTargets.push(target);
  83434. this._tempInfluences[influenceCount++] = target.influence;
  83435. var positions = target.getPositions();
  83436. if (positions) {
  83437. this._supportsNormals = this._supportsNormals && target.hasNormals;
  83438. this._supportsTangents = this._supportsTangents && target.hasTangents;
  83439. var vertexCount = positions.length / 3;
  83440. if (this._vertexCount === 0) {
  83441. this._vertexCount = vertexCount;
  83442. }
  83443. else if (this._vertexCount !== vertexCount) {
  83444. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  83445. return;
  83446. }
  83447. }
  83448. }
  83449. if (!this._influences || this._influences.length !== influenceCount) {
  83450. this._influences = new Float32Array(influenceCount);
  83451. }
  83452. for (var index = 0; index < influenceCount; index++) {
  83453. this._influences[index] = this._tempInfluences[index];
  83454. }
  83455. if (needUpdate && this._scene) {
  83456. // Flag meshes as dirty to resync with the active targets
  83457. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  83458. var mesh = _c[_b];
  83459. if (mesh.morphTargetManager === this) {
  83460. mesh._syncGeometryWithMorphTargetManager();
  83461. }
  83462. }
  83463. }
  83464. };
  83465. // Statics
  83466. MorphTargetManager.Parse = function (serializationObject, scene) {
  83467. var result = new MorphTargetManager(scene);
  83468. result._uniqueId = serializationObject.id;
  83469. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  83470. var targetData = _a[_i];
  83471. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  83472. }
  83473. return result;
  83474. };
  83475. return MorphTargetManager;
  83476. }());
  83477. BABYLON.MorphTargetManager = MorphTargetManager;
  83478. })(BABYLON || (BABYLON = {}));
  83479. //# sourceMappingURL=babylon.morphTargetManager.js.map
  83480. "use strict";
  83481. var BABYLON;
  83482. (function (BABYLON) {
  83483. var Octree = /** @class */ (function () {
  83484. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  83485. if (maxDepth === void 0) { maxDepth = 2; }
  83486. this.maxDepth = maxDepth;
  83487. this.dynamicContent = new Array();
  83488. this._maxBlockCapacity = maxBlockCapacity || 64;
  83489. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  83490. this._creationFunc = creationFunc;
  83491. }
  83492. // Methods
  83493. Octree.prototype.update = function (worldMin, worldMax, entries) {
  83494. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  83495. };
  83496. Octree.prototype.addMesh = function (entry) {
  83497. for (var index = 0; index < this.blocks.length; index++) {
  83498. var block = this.blocks[index];
  83499. block.addEntry(entry);
  83500. }
  83501. };
  83502. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  83503. this._selectionContent.reset();
  83504. for (var index = 0; index < this.blocks.length; index++) {
  83505. var block = this.blocks[index];
  83506. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  83507. }
  83508. if (allowDuplicate) {
  83509. this._selectionContent.concat(this.dynamicContent);
  83510. }
  83511. else {
  83512. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83513. }
  83514. return this._selectionContent;
  83515. };
  83516. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  83517. this._selectionContent.reset();
  83518. for (var index = 0; index < this.blocks.length; index++) {
  83519. var block = this.blocks[index];
  83520. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  83521. }
  83522. if (allowDuplicate) {
  83523. this._selectionContent.concat(this.dynamicContent);
  83524. }
  83525. else {
  83526. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83527. }
  83528. return this._selectionContent;
  83529. };
  83530. Octree.prototype.intersectsRay = function (ray) {
  83531. this._selectionContent.reset();
  83532. for (var index = 0; index < this.blocks.length; index++) {
  83533. var block = this.blocks[index];
  83534. block.intersectsRay(ray, this._selectionContent);
  83535. }
  83536. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  83537. return this._selectionContent;
  83538. };
  83539. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  83540. target.blocks = new Array();
  83541. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  83542. // Segmenting space
  83543. for (var x = 0; x < 2; x++) {
  83544. for (var y = 0; y < 2; y++) {
  83545. for (var z = 0; z < 2; z++) {
  83546. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  83547. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  83548. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  83549. block.addEntries(entries);
  83550. target.blocks.push(block);
  83551. }
  83552. }
  83553. }
  83554. };
  83555. Octree.CreationFuncForMeshes = function (entry, block) {
  83556. var boundingInfo = entry.getBoundingInfo();
  83557. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  83558. block.entries.push(entry);
  83559. }
  83560. };
  83561. Octree.CreationFuncForSubMeshes = function (entry, block) {
  83562. var boundingInfo = entry.getBoundingInfo();
  83563. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  83564. block.entries.push(entry);
  83565. }
  83566. };
  83567. return Octree;
  83568. }());
  83569. BABYLON.Octree = Octree;
  83570. })(BABYLON || (BABYLON = {}));
  83571. //# sourceMappingURL=babylon.octree.js.map
  83572. "use strict";
  83573. var BABYLON;
  83574. (function (BABYLON) {
  83575. var OctreeBlock = /** @class */ (function () {
  83576. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  83577. this.entries = new Array();
  83578. this._boundingVectors = new Array();
  83579. this._capacity = capacity;
  83580. this._depth = depth;
  83581. this._maxDepth = maxDepth;
  83582. this._creationFunc = creationFunc;
  83583. this._minPoint = minPoint;
  83584. this._maxPoint = maxPoint;
  83585. this._boundingVectors.push(minPoint.clone());
  83586. this._boundingVectors.push(maxPoint.clone());
  83587. this._boundingVectors.push(minPoint.clone());
  83588. this._boundingVectors[2].x = maxPoint.x;
  83589. this._boundingVectors.push(minPoint.clone());
  83590. this._boundingVectors[3].y = maxPoint.y;
  83591. this._boundingVectors.push(minPoint.clone());
  83592. this._boundingVectors[4].z = maxPoint.z;
  83593. this._boundingVectors.push(maxPoint.clone());
  83594. this._boundingVectors[5].z = minPoint.z;
  83595. this._boundingVectors.push(maxPoint.clone());
  83596. this._boundingVectors[6].x = minPoint.x;
  83597. this._boundingVectors.push(maxPoint.clone());
  83598. this._boundingVectors[7].y = minPoint.y;
  83599. }
  83600. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  83601. // Property
  83602. get: function () {
  83603. return this._capacity;
  83604. },
  83605. enumerable: true,
  83606. configurable: true
  83607. });
  83608. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  83609. get: function () {
  83610. return this._minPoint;
  83611. },
  83612. enumerable: true,
  83613. configurable: true
  83614. });
  83615. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  83616. get: function () {
  83617. return this._maxPoint;
  83618. },
  83619. enumerable: true,
  83620. configurable: true
  83621. });
  83622. // Methods
  83623. OctreeBlock.prototype.addEntry = function (entry) {
  83624. if (this.blocks) {
  83625. for (var index = 0; index < this.blocks.length; index++) {
  83626. var block = this.blocks[index];
  83627. block.addEntry(entry);
  83628. }
  83629. return;
  83630. }
  83631. this._creationFunc(entry, this);
  83632. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  83633. this.createInnerBlocks();
  83634. }
  83635. };
  83636. OctreeBlock.prototype.addEntries = function (entries) {
  83637. for (var index = 0; index < entries.length; index++) {
  83638. var mesh = entries[index];
  83639. this.addEntry(mesh);
  83640. }
  83641. };
  83642. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  83643. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  83644. if (this.blocks) {
  83645. for (var index = 0; index < this.blocks.length; index++) {
  83646. var block = this.blocks[index];
  83647. block.select(frustumPlanes, selection, allowDuplicate);
  83648. }
  83649. return;
  83650. }
  83651. if (allowDuplicate) {
  83652. selection.concat(this.entries);
  83653. }
  83654. else {
  83655. selection.concatWithNoDuplicate(this.entries);
  83656. }
  83657. }
  83658. };
  83659. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  83660. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  83661. if (this.blocks) {
  83662. for (var index = 0; index < this.blocks.length; index++) {
  83663. var block = this.blocks[index];
  83664. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  83665. }
  83666. return;
  83667. }
  83668. if (allowDuplicate) {
  83669. selection.concat(this.entries);
  83670. }
  83671. else {
  83672. selection.concatWithNoDuplicate(this.entries);
  83673. }
  83674. }
  83675. };
  83676. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  83677. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  83678. if (this.blocks) {
  83679. for (var index = 0; index < this.blocks.length; index++) {
  83680. var block = this.blocks[index];
  83681. block.intersectsRay(ray, selection);
  83682. }
  83683. return;
  83684. }
  83685. selection.concatWithNoDuplicate(this.entries);
  83686. }
  83687. };
  83688. OctreeBlock.prototype.createInnerBlocks = function () {
  83689. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  83690. };
  83691. return OctreeBlock;
  83692. }());
  83693. BABYLON.OctreeBlock = OctreeBlock;
  83694. })(BABYLON || (BABYLON = {}));
  83695. //# sourceMappingURL=babylon.octreeBlock.js.map
  83696. "use strict";
  83697. var BABYLON;
  83698. (function (BABYLON) {
  83699. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  83700. __extends(VRDistortionCorrectionPostProcess, _super);
  83701. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  83702. var _this = _super.call(this, name, "vrDistortionCorrection", [
  83703. 'LensCenter',
  83704. 'Scale',
  83705. 'ScaleIn',
  83706. 'HmdWarpParam'
  83707. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  83708. _this._isRightEye = isRightEye;
  83709. _this._distortionFactors = vrMetrics.distortionK;
  83710. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  83711. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  83712. _this.adaptScaleToCurrentViewport = true;
  83713. _this.onSizeChangedObservable.add(function () {
  83714. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  83715. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  83716. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  83717. });
  83718. _this.onApplyObservable.add(function (effect) {
  83719. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  83720. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  83721. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  83722. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  83723. });
  83724. return _this;
  83725. }
  83726. return VRDistortionCorrectionPostProcess;
  83727. }(BABYLON.PostProcess));
  83728. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  83729. })(BABYLON || (BABYLON = {}));
  83730. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  83731. "use strict";
  83732. var BABYLON;
  83733. (function (BABYLON) {
  83734. var AnaglyphPostProcess = /** @class */ (function (_super) {
  83735. __extends(AnaglyphPostProcess, _super);
  83736. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  83737. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  83738. _this._passedProcess = rigCameras[0]._rigPostProcess;
  83739. _this.onApplyObservable.add(function (effect) {
  83740. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  83741. });
  83742. return _this;
  83743. }
  83744. return AnaglyphPostProcess;
  83745. }(BABYLON.PostProcess));
  83746. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  83747. })(BABYLON || (BABYLON = {}));
  83748. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  83749. "use strict";
  83750. var BABYLON;
  83751. (function (BABYLON) {
  83752. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  83753. __extends(StereoscopicInterlacePostProcess, _super);
  83754. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  83755. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  83756. _this._passedProcess = rigCameras[0]._rigPostProcess;
  83757. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  83758. _this.onSizeChangedObservable.add(function () {
  83759. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  83760. });
  83761. _this.onApplyObservable.add(function (effect) {
  83762. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  83763. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  83764. });
  83765. return _this;
  83766. }
  83767. return StereoscopicInterlacePostProcess;
  83768. }(BABYLON.PostProcess));
  83769. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  83770. })(BABYLON || (BABYLON = {}));
  83771. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  83772. "use strict";
  83773. var BABYLON;
  83774. (function (BABYLON) {
  83775. /**
  83776. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  83777. * Screen rotation is taken into account.
  83778. */
  83779. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  83780. function FreeCameraDeviceOrientationInput() {
  83781. var _this = this;
  83782. this._screenOrientationAngle = 0;
  83783. this._screenQuaternion = new BABYLON.Quaternion();
  83784. this._alpha = 0;
  83785. this._beta = 0;
  83786. this._gamma = 0;
  83787. this._orientationChanged = function () {
  83788. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  83789. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  83790. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  83791. };
  83792. this._deviceOrientation = function (evt) {
  83793. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  83794. _this._beta = evt.beta !== null ? evt.beta : 0;
  83795. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  83796. };
  83797. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  83798. this._orientationChanged();
  83799. }
  83800. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  83801. get: function () {
  83802. return this._camera;
  83803. },
  83804. set: function (camera) {
  83805. this._camera = camera;
  83806. if (this._camera != null && !this._camera.rotationQuaternion) {
  83807. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  83808. }
  83809. },
  83810. enumerable: true,
  83811. configurable: true
  83812. });
  83813. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  83814. window.addEventListener("orientationchange", this._orientationChanged);
  83815. window.addEventListener("deviceorientation", this._deviceOrientation);
  83816. //In certain cases, the attach control is called AFTER orientation was changed,
  83817. //So this is needed.
  83818. this._orientationChanged();
  83819. };
  83820. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  83821. window.removeEventListener("orientationchange", this._orientationChanged);
  83822. window.removeEventListener("deviceorientation", this._deviceOrientation);
  83823. };
  83824. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  83825. //if no device orientation provided, don't update the rotation.
  83826. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  83827. if (!this._alpha)
  83828. return;
  83829. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  83830. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  83831. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  83832. //Mirror on XY Plane
  83833. this._camera.rotationQuaternion.z *= -1;
  83834. this._camera.rotationQuaternion.w *= -1;
  83835. };
  83836. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  83837. return "FreeCameraDeviceOrientationInput";
  83838. };
  83839. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  83840. return "deviceOrientation";
  83841. };
  83842. return FreeCameraDeviceOrientationInput;
  83843. }());
  83844. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  83845. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  83846. })(BABYLON || (BABYLON = {}));
  83847. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  83848. "use strict";
  83849. var BABYLON;
  83850. (function (BABYLON) {
  83851. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  83852. function ArcRotateCameraVRDeviceOrientationInput() {
  83853. this.alphaCorrection = 1;
  83854. this.betaCorrection = 1;
  83855. this.gammaCorrection = 1;
  83856. this._alpha = 0;
  83857. this._gamma = 0;
  83858. this._dirty = false;
  83859. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  83860. }
  83861. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  83862. this.camera.attachControl(element, noPreventDefault);
  83863. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  83864. };
  83865. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  83866. if (evt.alpha !== null) {
  83867. this._alpha = +evt.alpha | 0;
  83868. }
  83869. if (evt.gamma !== null) {
  83870. this._gamma = +evt.gamma | 0;
  83871. }
  83872. this._dirty = true;
  83873. };
  83874. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  83875. if (this._dirty) {
  83876. this._dirty = false;
  83877. if (this._gamma < 0) {
  83878. this._gamma = 180 + this._gamma;
  83879. }
  83880. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  83881. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  83882. }
  83883. };
  83884. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  83885. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  83886. };
  83887. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  83888. return "ArcRotateCameraVRDeviceOrientationInput";
  83889. };
  83890. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  83891. return "VRDeviceOrientation";
  83892. };
  83893. return ArcRotateCameraVRDeviceOrientationInput;
  83894. }());
  83895. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  83896. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  83897. })(BABYLON || (BABYLON = {}));
  83898. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  83899. "use strict";
  83900. var BABYLON;
  83901. (function (BABYLON) {
  83902. var VRCameraMetrics = /** @class */ (function () {
  83903. function VRCameraMetrics() {
  83904. this.compensateDistortion = true;
  83905. }
  83906. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  83907. get: function () {
  83908. return this.hResolution / (2 * this.vResolution);
  83909. },
  83910. enumerable: true,
  83911. configurable: true
  83912. });
  83913. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  83914. get: function () {
  83915. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  83916. },
  83917. enumerable: true,
  83918. configurable: true
  83919. });
  83920. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  83921. get: function () {
  83922. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  83923. var h = (4 * meters) / this.hScreenSize;
  83924. return BABYLON.Matrix.Translation(h, 0, 0);
  83925. },
  83926. enumerable: true,
  83927. configurable: true
  83928. });
  83929. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  83930. get: function () {
  83931. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  83932. var h = (4 * meters) / this.hScreenSize;
  83933. return BABYLON.Matrix.Translation(-h, 0, 0);
  83934. },
  83935. enumerable: true,
  83936. configurable: true
  83937. });
  83938. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  83939. get: function () {
  83940. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  83941. },
  83942. enumerable: true,
  83943. configurable: true
  83944. });
  83945. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  83946. get: function () {
  83947. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  83948. },
  83949. enumerable: true,
  83950. configurable: true
  83951. });
  83952. VRCameraMetrics.GetDefault = function () {
  83953. var result = new VRCameraMetrics();
  83954. result.hResolution = 1280;
  83955. result.vResolution = 800;
  83956. result.hScreenSize = 0.149759993;
  83957. result.vScreenSize = 0.0935999975;
  83958. result.vScreenCenter = 0.0467999987;
  83959. result.eyeToScreenDistance = 0.0410000011;
  83960. result.lensSeparationDistance = 0.0635000020;
  83961. result.interpupillaryDistance = 0.0640000030;
  83962. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  83963. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  83964. result.postProcessScaleFactor = 1.714605507808412;
  83965. result.lensCenterOffset = 0.151976421;
  83966. return result;
  83967. };
  83968. return VRCameraMetrics;
  83969. }());
  83970. BABYLON.VRCameraMetrics = VRCameraMetrics;
  83971. })(BABYLON || (BABYLON = {}));
  83972. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  83973. "use strict";
  83974. var BABYLON;
  83975. (function (BABYLON) {
  83976. /**
  83977. * This represents a WebVR camera.
  83978. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  83979. * @example http://doc.babylonjs.com/how_to/webvr_camera
  83980. */
  83981. var WebVRFreeCamera = /** @class */ (function (_super) {
  83982. __extends(WebVRFreeCamera, _super);
  83983. /**
  83984. * Instantiates a WebVRFreeCamera.
  83985. * @param name The name of the WebVRFreeCamera
  83986. * @param position The starting anchor position for the camera
  83987. * @param scene The scene the camera belongs to
  83988. * @param webVROptions a set of customizable options for the webVRCamera
  83989. */
  83990. function WebVRFreeCamera(name, position, scene, webVROptions) {
  83991. if (webVROptions === void 0) { webVROptions = {}; }
  83992. var _this = _super.call(this, name, position, scene) || this;
  83993. _this.webVROptions = webVROptions;
  83994. /**
  83995. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  83996. */
  83997. _this._vrDevice = null;
  83998. /**
  83999. * The rawPose of the vrDevice.
  84000. */
  84001. _this.rawPose = null;
  84002. _this._specsVersion = "1.1";
  84003. _this._attached = false;
  84004. _this._descendants = [];
  84005. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  84006. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  84007. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  84008. _this._standingMatrix = null;
  84009. /**
  84010. * Represents device position in babylon space.
  84011. */
  84012. _this.devicePosition = BABYLON.Vector3.Zero();
  84013. /**
  84014. * Represents device rotation in babylon space.
  84015. */
  84016. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  84017. /**
  84018. * The scale of the device to be used when translating from device space to babylon space.
  84019. */
  84020. _this.deviceScaleFactor = 1;
  84021. _this._deviceToWorld = BABYLON.Matrix.Identity();
  84022. _this._worldToDevice = BABYLON.Matrix.Identity();
  84023. /**
  84024. * References to the webVR controllers for the vrDevice.
  84025. */
  84026. _this.controllers = [];
  84027. /**
  84028. * Emits an event when a controller is attached.
  84029. */
  84030. _this.onControllersAttachedObservable = new BABYLON.Observable();
  84031. /**
  84032. * Emits an event when a controller's mesh has been loaded;
  84033. */
  84034. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  84035. /**
  84036. * If the rig cameras be used as parent instead of this camera.
  84037. */
  84038. _this.rigParenting = true;
  84039. _this._defaultHeight = undefined;
  84040. _this._workingVector = BABYLON.Vector3.Zero();
  84041. _this._oneVector = BABYLON.Vector3.One();
  84042. _this._workingMatrix = BABYLON.Matrix.Identity();
  84043. _this._cache.position = BABYLON.Vector3.Zero();
  84044. if (webVROptions.defaultHeight) {
  84045. _this._defaultHeight = webVROptions.defaultHeight;
  84046. _this.position.y = _this._defaultHeight;
  84047. }
  84048. _this.minZ = 0.1;
  84049. //legacy support - the compensation boolean was removed.
  84050. if (arguments.length === 5) {
  84051. _this.webVROptions = arguments[4];
  84052. }
  84053. // default webVR options
  84054. if (_this.webVROptions.trackPosition == undefined) {
  84055. _this.webVROptions.trackPosition = true;
  84056. }
  84057. if (_this.webVROptions.controllerMeshes == undefined) {
  84058. _this.webVROptions.controllerMeshes = true;
  84059. }
  84060. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  84061. _this.webVROptions.defaultLightingOnControllers = true;
  84062. }
  84063. _this.rotationQuaternion = new BABYLON.Quaternion();
  84064. if (_this.webVROptions && _this.webVROptions.positionScale) {
  84065. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  84066. }
  84067. //enable VR
  84068. var engine = _this.getEngine();
  84069. _this._onVREnabled = function (success) { if (success) {
  84070. _this.initControllers();
  84071. } };
  84072. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  84073. engine.initWebVR().add(function (event) {
  84074. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  84075. return;
  84076. }
  84077. _this._vrDevice = event.vrDisplay;
  84078. //reset the rig parameters.
  84079. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  84080. if (_this._attached) {
  84081. _this.getEngine().enableVR();
  84082. }
  84083. });
  84084. if (typeof (VRFrameData) !== "undefined")
  84085. _this._frameData = new VRFrameData();
  84086. /**
  84087. * The idea behind the following lines:
  84088. * objects that have the camera as parent should actually have the rig cameras as a parent.
  84089. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  84090. * the second will not show it correctly.
  84091. *
  84092. * To solve this - each object that has the camera as parent will be added to a protected array.
  84093. * When the rig camera renders, it will take this array and set all of those to be its children.
  84094. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  84095. * Amazing!
  84096. */
  84097. scene.onBeforeCameraRenderObservable.add(function (camera) {
  84098. if (camera.parent === _this && _this.rigParenting) {
  84099. _this._descendants = _this.getDescendants(true, function (n) {
  84100. // don't take the cameras or the controllers!
  84101. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  84102. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  84103. return !isController && !isRigCamera;
  84104. });
  84105. _this._descendants.forEach(function (node) {
  84106. node.parent = camera;
  84107. });
  84108. }
  84109. });
  84110. scene.onAfterCameraRenderObservable.add(function (camera) {
  84111. if (camera.parent === _this && _this.rigParenting) {
  84112. _this._descendants.forEach(function (node) {
  84113. node.parent = _this;
  84114. });
  84115. }
  84116. });
  84117. return _this;
  84118. }
  84119. /**
  84120. * Gets the device distance from the ground in meters.
  84121. * @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.
  84122. */
  84123. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  84124. if (this._standingMatrix) {
  84125. // Add standing matrix offset to get real offset from ground in room
  84126. this._standingMatrix.getTranslationToRef(this._workingVector);
  84127. return this._deviceRoomPosition.y + this._workingVector.y;
  84128. }
  84129. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  84130. return this._defaultHeight || 0;
  84131. };
  84132. /**
  84133. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84134. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  84135. */
  84136. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  84137. var _this = this;
  84138. if (callback === void 0) { callback = function (bool) { }; }
  84139. // Use standing matrix if available
  84140. this.getEngine().initWebVRAsync().then(function (result) {
  84141. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  84142. callback(false);
  84143. }
  84144. else {
  84145. _this._standingMatrix = new BABYLON.Matrix();
  84146. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  84147. if (!_this.getScene().useRightHandedSystem) {
  84148. [2, 6, 8, 9, 14].forEach(function (num) {
  84149. if (_this._standingMatrix) {
  84150. _this._standingMatrix.m[num] *= -1;
  84151. }
  84152. });
  84153. }
  84154. callback(true);
  84155. }
  84156. });
  84157. };
  84158. /**
  84159. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84160. * @returns A promise with a boolean set to if the standing matrix is supported.
  84161. */
  84162. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  84163. var _this = this;
  84164. return new Promise(function (res, rej) {
  84165. _this.useStandingMatrix(function (supported) {
  84166. res(supported);
  84167. });
  84168. });
  84169. };
  84170. /**
  84171. * Disposes the camera
  84172. */
  84173. WebVRFreeCamera.prototype.dispose = function () {
  84174. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  84175. _super.prototype.dispose.call(this);
  84176. };
  84177. /**
  84178. * Gets a vrController by name.
  84179. * @param name The name of the controller to retreive
  84180. * @returns the controller matching the name specified or null if not found
  84181. */
  84182. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  84183. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  84184. var gp = _a[_i];
  84185. if (gp.hand === name) {
  84186. return gp;
  84187. }
  84188. }
  84189. return null;
  84190. };
  84191. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  84192. /**
  84193. * The controller corrisponding to the users left hand.
  84194. */
  84195. get: function () {
  84196. if (!this._leftController) {
  84197. this._leftController = this.getControllerByName("left");
  84198. }
  84199. return this._leftController;
  84200. },
  84201. enumerable: true,
  84202. configurable: true
  84203. });
  84204. ;
  84205. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  84206. /**
  84207. * The controller corrisponding to the users right hand.
  84208. */
  84209. get: function () {
  84210. if (!this._rightController) {
  84211. this._rightController = this.getControllerByName("right");
  84212. }
  84213. return this._rightController;
  84214. },
  84215. enumerable: true,
  84216. configurable: true
  84217. });
  84218. ;
  84219. /**
  84220. * Casts a ray forward from the vrCamera's gaze.
  84221. * @param length Length of the ray (default: 100)
  84222. * @returns the ray corrisponding to the gaze
  84223. */
  84224. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  84225. if (length === void 0) { length = 100; }
  84226. if (this.leftCamera) {
  84227. // Use left eye to avoid computation to compute center on every call
  84228. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  84229. }
  84230. else {
  84231. return _super.prototype.getForwardRay.call(this, length);
  84232. }
  84233. };
  84234. /**
  84235. * Updates the camera based on device's frame data
  84236. */
  84237. WebVRFreeCamera.prototype._checkInputs = function () {
  84238. if (this._vrDevice && this._vrDevice.isPresenting) {
  84239. this._vrDevice.getFrameData(this._frameData);
  84240. this.updateFromDevice(this._frameData.pose);
  84241. }
  84242. _super.prototype._checkInputs.call(this);
  84243. };
  84244. /**
  84245. * Updates the poseControlled values based on the input device pose.
  84246. * @param poseData Pose coming from the device
  84247. */
  84248. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  84249. if (poseData && poseData.orientation) {
  84250. this.rawPose = poseData;
  84251. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  84252. if (this.getScene().useRightHandedSystem) {
  84253. this._deviceRoomRotationQuaternion.z *= -1;
  84254. this._deviceRoomRotationQuaternion.w *= -1;
  84255. }
  84256. if (this.webVROptions.trackPosition && this.rawPose.position) {
  84257. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  84258. if (this.getScene().useRightHandedSystem) {
  84259. this._deviceRoomPosition.z *= -1;
  84260. }
  84261. }
  84262. }
  84263. };
  84264. /**
  84265. * WebVR's attach control will start broadcasting frames to the device.
  84266. * Note that in certain browsers (chrome for example) this function must be called
  84267. * within a user-interaction callback. Example:
  84268. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  84269. *
  84270. * @param element html element to attach the vrDevice to
  84271. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  84272. */
  84273. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  84274. _super.prototype.attachControl.call(this, element, noPreventDefault);
  84275. this._attached = true;
  84276. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  84277. if (this._vrDevice) {
  84278. this.getEngine().enableVR();
  84279. }
  84280. };
  84281. /**
  84282. * Detaches the camera from the html element and disables VR
  84283. *
  84284. * @param element html element to detach from
  84285. */
  84286. WebVRFreeCamera.prototype.detachControl = function (element) {
  84287. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  84288. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  84289. _super.prototype.detachControl.call(this, element);
  84290. this._attached = false;
  84291. this.getEngine().disableVR();
  84292. };
  84293. /**
  84294. * @returns the name of this class
  84295. */
  84296. WebVRFreeCamera.prototype.getClassName = function () {
  84297. return "WebVRFreeCamera";
  84298. };
  84299. /**
  84300. * Calls resetPose on the vrDisplay
  84301. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  84302. */
  84303. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  84304. //uses the vrDisplay's "resetPose()".
  84305. //pitch and roll won't be affected.
  84306. this._vrDevice.resetPose();
  84307. };
  84308. /**
  84309. * Updates the rig cameras (left and right eye)
  84310. */
  84311. WebVRFreeCamera.prototype._updateRigCameras = function () {
  84312. var camLeft = this._rigCameras[0];
  84313. var camRight = this._rigCameras[1];
  84314. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84315. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84316. camLeft.position.copyFrom(this._deviceRoomPosition);
  84317. camRight.position.copyFrom(this._deviceRoomPosition);
  84318. };
  84319. /**
  84320. * Updates the cached values of the camera
  84321. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  84322. */
  84323. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  84324. var _this = this;
  84325. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  84326. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  84327. if (!this.updateCacheCalled) {
  84328. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  84329. this.updateCacheCalled = true;
  84330. this.update();
  84331. }
  84332. // Set working vector to the device position in room space rotated by the new rotation
  84333. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  84334. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  84335. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  84336. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  84337. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  84338. // Add translation from anchor position
  84339. this._deviceToWorld.getTranslationToRef(this._workingVector);
  84340. this._workingVector.addInPlace(this.position);
  84341. this._workingVector.subtractInPlace(this._cache.position);
  84342. this._deviceToWorld.setTranslation(this._workingVector);
  84343. // Set an inverted matrix to be used when updating the camera
  84344. this._deviceToWorld.invertToRef(this._worldToDevice);
  84345. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  84346. this.controllers.forEach(function (controller) {
  84347. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  84348. controller.update();
  84349. });
  84350. }
  84351. if (!ignoreParentClass) {
  84352. _super.prototype._updateCache.call(this);
  84353. }
  84354. this.updateCacheCalled = false;
  84355. };
  84356. /**
  84357. * Updates the current device position and rotation in the babylon world
  84358. */
  84359. WebVRFreeCamera.prototype.update = function () {
  84360. // Get current device position in babylon world
  84361. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  84362. // Get current device rotation in babylon world
  84363. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  84364. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  84365. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  84366. _super.prototype.update.call(this);
  84367. };
  84368. /**
  84369. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  84370. * @returns an identity matrix
  84371. */
  84372. WebVRFreeCamera.prototype._getViewMatrix = function () {
  84373. return BABYLON.Matrix.Identity();
  84374. };
  84375. /**
  84376. * This function is called by the two RIG cameras.
  84377. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  84378. */
  84379. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  84380. var _this = this;
  84381. // Update the parent camera prior to using a child camera to avoid desynchronization
  84382. var parentCamera = this._cameraRigParams["parentCamera"];
  84383. parentCamera._updateCache();
  84384. //WebVR 1.1
  84385. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  84386. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  84387. if (!this.getScene().useRightHandedSystem) {
  84388. [2, 6, 8, 9, 14].forEach(function (num) {
  84389. _this._webvrViewMatrix.m[num] *= -1;
  84390. });
  84391. }
  84392. // update the camera rotation matrix
  84393. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  84394. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  84395. // Computing target and final matrix
  84396. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  84397. // should the view matrix be updated with scale and position offset?
  84398. if (parentCamera.deviceScaleFactor !== 1) {
  84399. this._webvrViewMatrix.invert();
  84400. // scale the position, if set
  84401. if (parentCamera.deviceScaleFactor) {
  84402. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  84403. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  84404. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  84405. }
  84406. this._webvrViewMatrix.invert();
  84407. }
  84408. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  84409. return this._webvrViewMatrix;
  84410. };
  84411. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  84412. var _this = this;
  84413. var parentCamera = this.parent;
  84414. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  84415. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  84416. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  84417. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  84418. //babylon compatible matrix
  84419. if (!this.getScene().useRightHandedSystem) {
  84420. [8, 9, 10, 11].forEach(function (num) {
  84421. _this._projectionMatrix.m[num] *= -1;
  84422. });
  84423. }
  84424. return this._projectionMatrix;
  84425. };
  84426. /**
  84427. * Initializes the controllers and their meshes
  84428. */
  84429. WebVRFreeCamera.prototype.initControllers = function () {
  84430. var _this = this;
  84431. this.controllers = [];
  84432. var manager = this.getScene().gamepadManager;
  84433. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  84434. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  84435. var webVrController = gamepad;
  84436. if (webVrController.defaultModel) {
  84437. webVrController.defaultModel.setEnabled(false);
  84438. }
  84439. if (webVrController.hand === "right") {
  84440. _this._rightController = null;
  84441. }
  84442. if (webVrController.hand === "left") {
  84443. _this._leftController = null;
  84444. }
  84445. var controllerIndex = _this.controllers.indexOf(webVrController);
  84446. if (controllerIndex !== -1) {
  84447. _this.controllers.splice(controllerIndex, 1);
  84448. }
  84449. }
  84450. });
  84451. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  84452. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  84453. var webVrController_1 = gamepad;
  84454. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  84455. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  84456. if (_this.webVROptions.controllerMeshes) {
  84457. if (webVrController_1.defaultModel) {
  84458. webVrController_1.defaultModel.setEnabled(true);
  84459. }
  84460. else {
  84461. // Load the meshes
  84462. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  84463. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  84464. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  84465. if (_this.webVROptions.defaultLightingOnControllers) {
  84466. if (!_this._lightOnControllers) {
  84467. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  84468. }
  84469. var activateLightOnSubMeshes_1 = function (mesh, light) {
  84470. var children = mesh.getChildren();
  84471. if (children.length !== 0) {
  84472. children.forEach(function (mesh) {
  84473. light.includedOnlyMeshes.push(mesh);
  84474. activateLightOnSubMeshes_1(mesh, light);
  84475. });
  84476. }
  84477. };
  84478. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  84479. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  84480. }
  84481. });
  84482. }
  84483. }
  84484. webVrController_1.attachToPoseControlledCamera(_this);
  84485. // since this is async - sanity check. Is the controller already stored?
  84486. if (_this.controllers.indexOf(webVrController_1) === -1) {
  84487. //add to the controllers array
  84488. _this.controllers.push(webVrController_1);
  84489. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  84490. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  84491. // So we're overriding setting left & right manually to be sure
  84492. var firstViveWandDetected = false;
  84493. for (var i = 0; i < _this.controllers.length; i++) {
  84494. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  84495. if (!firstViveWandDetected) {
  84496. firstViveWandDetected = true;
  84497. _this.controllers[i].hand = "left";
  84498. }
  84499. else {
  84500. _this.controllers[i].hand = "right";
  84501. }
  84502. }
  84503. }
  84504. //did we find enough controllers? Great! let the developer know.
  84505. if (_this.controllers.length >= 2) {
  84506. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  84507. }
  84508. }
  84509. }
  84510. });
  84511. };
  84512. return WebVRFreeCamera;
  84513. }(BABYLON.FreeCamera));
  84514. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  84515. })(BABYLON || (BABYLON = {}));
  84516. //# sourceMappingURL=babylon.webVRCamera.js.map
  84517. "use strict";
  84518. var BABYLON;
  84519. (function (BABYLON) {
  84520. // We're mainly based on the logic defined into the FreeCamera code
  84521. /**
  84522. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  84523. * being tilted forward or back and left or right.
  84524. */
  84525. var DeviceOrientationCamera = /** @class */ (function (_super) {
  84526. __extends(DeviceOrientationCamera, _super);
  84527. /**
  84528. * Creates a new device orientation camera
  84529. * @param name The name of the camera
  84530. * @param position The start position camera
  84531. * @param scene The scene the camera belongs to
  84532. */
  84533. function DeviceOrientationCamera(name, position, scene) {
  84534. var _this = _super.call(this, name, position, scene) || this;
  84535. _this._quaternionCache = new BABYLON.Quaternion();
  84536. _this.inputs.addDeviceOrientation();
  84537. return _this;
  84538. }
  84539. /**
  84540. * Gets the current instance class name ("DeviceOrientationCamera").
  84541. * This helps avoiding instanceof at run time.
  84542. * @returns the class name
  84543. */
  84544. DeviceOrientationCamera.prototype.getClassName = function () {
  84545. return "DeviceOrientationCamera";
  84546. };
  84547. /**
  84548. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  84549. */
  84550. DeviceOrientationCamera.prototype._checkInputs = function () {
  84551. _super.prototype._checkInputs.call(this);
  84552. this._quaternionCache.copyFrom(this.rotationQuaternion);
  84553. if (this._initialQuaternion) {
  84554. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  84555. }
  84556. };
  84557. /**
  84558. * Reset the camera to its default orientation on the specified axis only.
  84559. * @param axis The axis to reset
  84560. */
  84561. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  84562. var _this = this;
  84563. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  84564. //can only work if this camera has a rotation quaternion already.
  84565. if (!this.rotationQuaternion)
  84566. return;
  84567. if (!this._initialQuaternion) {
  84568. this._initialQuaternion = new BABYLON.Quaternion();
  84569. }
  84570. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  84571. ['x', 'y', 'z'].forEach(function (axisName) {
  84572. if (!axis[axisName]) {
  84573. _this._initialQuaternion[axisName] = 0;
  84574. }
  84575. else {
  84576. _this._initialQuaternion[axisName] *= -1;
  84577. }
  84578. });
  84579. this._initialQuaternion.normalize();
  84580. //force rotation update
  84581. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  84582. };
  84583. return DeviceOrientationCamera;
  84584. }(BABYLON.FreeCamera));
  84585. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  84586. })(BABYLON || (BABYLON = {}));
  84587. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  84588. "use strict";
  84589. var BABYLON;
  84590. (function (BABYLON) {
  84591. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  84592. __extends(VRDeviceOrientationFreeCamera, _super);
  84593. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  84594. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84595. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84596. var _this = _super.call(this, name, position, scene) || this;
  84597. vrCameraMetrics.compensateDistortion = compensateDistortion;
  84598. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  84599. return _this;
  84600. }
  84601. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  84602. return "VRDeviceOrientationFreeCamera";
  84603. };
  84604. return VRDeviceOrientationFreeCamera;
  84605. }(BABYLON.DeviceOrientationCamera));
  84606. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  84607. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  84608. __extends(VRDeviceOrientationGamepadCamera, _super);
  84609. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  84610. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84611. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84612. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  84613. _this.inputs.addGamepad();
  84614. return _this;
  84615. }
  84616. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  84617. return "VRDeviceOrientationGamepadCamera";
  84618. };
  84619. return VRDeviceOrientationGamepadCamera;
  84620. }(VRDeviceOrientationFreeCamera));
  84621. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  84622. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  84623. __extends(VRDeviceOrientationArcRotateCamera, _super);
  84624. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  84625. if (compensateDistortion === void 0) { compensateDistortion = true; }
  84626. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  84627. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84628. vrCameraMetrics.compensateDistortion = compensateDistortion;
  84629. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  84630. _this.inputs.addVRDeviceOrientation();
  84631. return _this;
  84632. }
  84633. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  84634. return "VRDeviceOrientationArcRotateCamera";
  84635. };
  84636. return VRDeviceOrientationArcRotateCamera;
  84637. }(BABYLON.ArcRotateCamera));
  84638. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  84639. })(BABYLON || (BABYLON = {}));
  84640. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  84641. "use strict";
  84642. var BABYLON;
  84643. (function (BABYLON) {
  84644. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  84645. __extends(AnaglyphFreeCamera, _super);
  84646. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  84647. var _this = _super.call(this, name, position, scene) || this;
  84648. _this.interaxialDistance = interaxialDistance;
  84649. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84650. return _this;
  84651. }
  84652. AnaglyphFreeCamera.prototype.getClassName = function () {
  84653. return "AnaglyphFreeCamera";
  84654. };
  84655. return AnaglyphFreeCamera;
  84656. }(BABYLON.FreeCamera));
  84657. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  84658. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  84659. __extends(AnaglyphArcRotateCamera, _super);
  84660. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  84661. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84662. _this.interaxialDistance = interaxialDistance;
  84663. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84664. return _this;
  84665. }
  84666. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  84667. return "AnaglyphArcRotateCamera";
  84668. };
  84669. return AnaglyphArcRotateCamera;
  84670. }(BABYLON.ArcRotateCamera));
  84671. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  84672. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  84673. __extends(AnaglyphGamepadCamera, _super);
  84674. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  84675. var _this = _super.call(this, name, position, scene) || this;
  84676. _this.interaxialDistance = interaxialDistance;
  84677. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84678. return _this;
  84679. }
  84680. AnaglyphGamepadCamera.prototype.getClassName = function () {
  84681. return "AnaglyphGamepadCamera";
  84682. };
  84683. return AnaglyphGamepadCamera;
  84684. }(BABYLON.GamepadCamera));
  84685. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  84686. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  84687. __extends(AnaglyphUniversalCamera, _super);
  84688. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  84689. var _this = _super.call(this, name, position, scene) || this;
  84690. _this.interaxialDistance = interaxialDistance;
  84691. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  84692. return _this;
  84693. }
  84694. AnaglyphUniversalCamera.prototype.getClassName = function () {
  84695. return "AnaglyphUniversalCamera";
  84696. };
  84697. return AnaglyphUniversalCamera;
  84698. }(BABYLON.UniversalCamera));
  84699. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  84700. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  84701. __extends(StereoscopicFreeCamera, _super);
  84702. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84703. var _this = _super.call(this, name, position, scene) || this;
  84704. _this.interaxialDistance = interaxialDistance;
  84705. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84706. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84707. return _this;
  84708. }
  84709. StereoscopicFreeCamera.prototype.getClassName = function () {
  84710. return "StereoscopicFreeCamera";
  84711. };
  84712. return StereoscopicFreeCamera;
  84713. }(BABYLON.FreeCamera));
  84714. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  84715. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  84716. __extends(StereoscopicArcRotateCamera, _super);
  84717. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  84718. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  84719. _this.interaxialDistance = interaxialDistance;
  84720. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84721. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84722. return _this;
  84723. }
  84724. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  84725. return "StereoscopicArcRotateCamera";
  84726. };
  84727. return StereoscopicArcRotateCamera;
  84728. }(BABYLON.ArcRotateCamera));
  84729. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  84730. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  84731. __extends(StereoscopicGamepadCamera, _super);
  84732. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84733. var _this = _super.call(this, name, position, scene) || this;
  84734. _this.interaxialDistance = interaxialDistance;
  84735. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84736. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84737. return _this;
  84738. }
  84739. StereoscopicGamepadCamera.prototype.getClassName = function () {
  84740. return "StereoscopicGamepadCamera";
  84741. };
  84742. return StereoscopicGamepadCamera;
  84743. }(BABYLON.GamepadCamera));
  84744. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  84745. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  84746. __extends(StereoscopicUniversalCamera, _super);
  84747. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  84748. var _this = _super.call(this, name, position, scene) || this;
  84749. _this.interaxialDistance = interaxialDistance;
  84750. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  84751. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  84752. return _this;
  84753. }
  84754. StereoscopicUniversalCamera.prototype.getClassName = function () {
  84755. return "StereoscopicUniversalCamera";
  84756. };
  84757. return StereoscopicUniversalCamera;
  84758. }(BABYLON.UniversalCamera));
  84759. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  84760. })(BABYLON || (BABYLON = {}));
  84761. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  84762. "use strict";
  84763. var BABYLON;
  84764. (function (BABYLON) {
  84765. var VRExperienceHelperGazer = /** @class */ (function () {
  84766. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  84767. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  84768. this.scene = scene;
  84769. this._pointerDownOnMeshAsked = false;
  84770. this._isActionableMesh = false;
  84771. this._teleportationRequestInitiated = false;
  84772. this._teleportationBackRequestInitiated = false;
  84773. this._dpadPressed = true;
  84774. this._activePointer = false;
  84775. this._id = VRExperienceHelperGazer._idCounter++;
  84776. // Gaze tracker
  84777. if (!gazeTrackerToClone) {
  84778. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  84779. this._gazeTracker.bakeCurrentTransformIntoVertices();
  84780. this._gazeTracker.isPickable = false;
  84781. this._gazeTracker.isVisible = false;
  84782. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  84783. targetMat.specularColor = BABYLON.Color3.Black();
  84784. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  84785. targetMat.backFaceCulling = false;
  84786. this._gazeTracker.material = targetMat;
  84787. }
  84788. else {
  84789. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  84790. }
  84791. }
  84792. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  84793. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  84794. };
  84795. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  84796. this._pointerDownOnMeshAsked = true;
  84797. if (this._currentMeshSelected && this._currentHit) {
  84798. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  84799. }
  84800. };
  84801. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  84802. if (this._currentMeshSelected && this._currentHit) {
  84803. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  84804. }
  84805. this._pointerDownOnMeshAsked = false;
  84806. };
  84807. VRExperienceHelperGazer.prototype._activatePointer = function () {
  84808. this._activePointer = true;
  84809. };
  84810. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  84811. this._activePointer = false;
  84812. };
  84813. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  84814. };
  84815. VRExperienceHelperGazer.prototype.dispose = function () {
  84816. this._interactionsEnabled = false;
  84817. this._teleportationEnabled = false;
  84818. };
  84819. VRExperienceHelperGazer._idCounter = 0;
  84820. return VRExperienceHelperGazer;
  84821. }());
  84822. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  84823. __extends(VRExperienceHelperControllerGazer, _super);
  84824. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  84825. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  84826. _this.webVRController = webVRController;
  84827. // Laser pointer
  84828. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  84829. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  84830. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  84831. laserPointerMaterial.alpha = 0.6;
  84832. _this._laserPointer.material = laserPointerMaterial;
  84833. _this._laserPointer.rotation.x = Math.PI / 2;
  84834. _this._laserPointer.position.z = -0.5;
  84835. _this._laserPointer.isVisible = false;
  84836. if (!webVRController.mesh) {
  84837. // Create an empty mesh that is used prior to loading the high quality model
  84838. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  84839. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  84840. preloadPointerPose.rotation.x = -0.7;
  84841. preloadMesh.addChild(preloadPointerPose);
  84842. webVRController.attachToMesh(preloadMesh);
  84843. }
  84844. _this._setLaserPointerParent(webVRController.mesh);
  84845. return _this;
  84846. }
  84847. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  84848. return this.webVRController.getForwardRay(length);
  84849. };
  84850. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  84851. _super.prototype._activatePointer.call(this);
  84852. this._laserPointer.isVisible = true;
  84853. };
  84854. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  84855. _super.prototype._deactivatePointer.call(this);
  84856. this._laserPointer.isVisible = false;
  84857. };
  84858. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  84859. this._laserPointer.material.emissiveColor = color;
  84860. };
  84861. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  84862. var makeNotPick = function (root) {
  84863. root.name += " laserPointer";
  84864. root.getChildMeshes().forEach(function (c) {
  84865. makeNotPick(c);
  84866. });
  84867. };
  84868. makeNotPick(mesh);
  84869. var childMeshes = mesh.getChildMeshes();
  84870. this.webVRController._pointingPoseNode = null;
  84871. for (var i = 0; i < childMeshes.length; i++) {
  84872. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  84873. mesh = childMeshes[i];
  84874. this.webVRController._pointingPoseNode = mesh;
  84875. break;
  84876. }
  84877. }
  84878. this._laserPointer.parent = mesh;
  84879. };
  84880. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  84881. this._laserPointer.scaling.y = distance;
  84882. this._laserPointer.position.z = -distance / 2;
  84883. };
  84884. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  84885. _super.prototype.dispose.call(this);
  84886. this._laserPointer.dispose();
  84887. };
  84888. return VRExperienceHelperControllerGazer;
  84889. }(VRExperienceHelperGazer));
  84890. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  84891. __extends(VRExperienceHelperCameraGazer, _super);
  84892. function VRExperienceHelperCameraGazer(getCamera, scene) {
  84893. var _this = _super.call(this, scene) || this;
  84894. _this.getCamera = getCamera;
  84895. return _this;
  84896. }
  84897. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  84898. var camera = this.getCamera();
  84899. if (camera) {
  84900. return camera.getForwardRay(length);
  84901. }
  84902. else {
  84903. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  84904. }
  84905. };
  84906. return VRExperienceHelperCameraGazer;
  84907. }(VRExperienceHelperGazer));
  84908. /**
  84909. * Helps to quickly add VR support to an existing scene.
  84910. * See http://doc.babylonjs.com/how_to/webvr_helper
  84911. */
  84912. var VRExperienceHelper = /** @class */ (function () {
  84913. /**
  84914. * Instantiates a VRExperienceHelper.
  84915. * Helps to quickly add VR support to an existing scene.
  84916. * @param scene The scene the VRExperienceHelper belongs to.
  84917. * @param webVROptions Options to modify the vr experience helper's behavior.
  84918. */
  84919. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  84920. if (webVROptions === void 0) { webVROptions = {}; }
  84921. var _this = this;
  84922. this.webVROptions = webVROptions;
  84923. // Can the system support WebVR, even if a headset isn't plugged in?
  84924. this._webVRsupported = false;
  84925. // If WebVR is supported, is a headset plugged in and are we ready to present?
  84926. this._webVRready = false;
  84927. // Are we waiting for the requestPresent callback to complete?
  84928. this._webVRrequesting = false;
  84929. // Are we presenting to the headset right now?
  84930. this._webVRpresenting = false;
  84931. // Are we presenting in the fullscreen fallback?
  84932. this._fullscreenVRpresenting = false;
  84933. /**
  84934. * Observable raised when entering VR.
  84935. */
  84936. this.onEnteringVRObservable = new BABYLON.Observable();
  84937. /**
  84938. * Observable raised when exiting VR.
  84939. */
  84940. this.onExitingVRObservable = new BABYLON.Observable();
  84941. /**
  84942. * Observable raised when controller mesh is loaded.
  84943. */
  84944. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  84945. this._useCustomVRButton = false;
  84946. this._teleportationRequested = false;
  84947. this._teleportActive = false;
  84948. this._floorMeshesCollection = [];
  84949. this._rotationAllowed = true;
  84950. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  84951. this._rotationRightAsked = false;
  84952. this._rotationLeftAsked = false;
  84953. this._isDefaultTeleportationTarget = true;
  84954. this._teleportationFillColor = "#444444";
  84955. this._teleportationBorderColor = "#FFFFFF";
  84956. this._rotationAngle = 0;
  84957. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  84958. this._padSensibilityUp = 0.65;
  84959. this._padSensibilityDown = 0.35;
  84960. this.leftController = null;
  84961. this.rightController = null;
  84962. /**
  84963. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  84964. */
  84965. this.onNewMeshSelected = new BABYLON.Observable();
  84966. /**
  84967. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  84968. */
  84969. this.onNewMeshPicked = new BABYLON.Observable();
  84970. /**
  84971. * Observable raised before camera teleportation
  84972. */
  84973. this.onBeforeCameraTeleport = new BABYLON.Observable();
  84974. /**
  84975. * Observable raised after camera teleportation
  84976. */
  84977. this.onAfterCameraTeleport = new BABYLON.Observable();
  84978. /**
  84979. * Observable raised when current selected mesh gets unselected
  84980. */
  84981. this.onSelectedMeshUnselected = new BABYLON.Observable();
  84982. /**
  84983. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  84984. */
  84985. this.teleportationEnabled = true;
  84986. this._teleportationInitialized = false;
  84987. this._interactionsEnabled = false;
  84988. this._interactionsRequested = false;
  84989. this._displayGaze = true;
  84990. this._displayLaserPointer = true;
  84991. this._onResize = function () {
  84992. _this.moveButtonToBottomRight();
  84993. if (_this._fullscreenVRpresenting && _this._webVRready) {
  84994. _this.exitVR();
  84995. }
  84996. };
  84997. this._onFullscreenChange = function () {
  84998. if (document.fullscreen !== undefined) {
  84999. _this._fullscreenVRpresenting = document.fullscreen;
  85000. }
  85001. else if (document.mozFullScreen !== undefined) {
  85002. _this._fullscreenVRpresenting = document.mozFullScreen;
  85003. }
  85004. else if (document.webkitIsFullScreen !== undefined) {
  85005. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  85006. }
  85007. else if (document.msIsFullScreen !== undefined) {
  85008. _this._fullscreenVRpresenting = document.msIsFullScreen;
  85009. }
  85010. if (!_this._fullscreenVRpresenting && _this._canvas) {
  85011. _this.exitVR();
  85012. if (!_this._useCustomVRButton) {
  85013. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  85014. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  85015. }
  85016. }
  85017. };
  85018. this.beforeRender = function () {
  85019. if (_this.leftController && _this.leftController._activePointer) {
  85020. _this._castRayAndSelectObject(_this.leftController);
  85021. }
  85022. if (_this.rightController && _this.rightController._activePointer) {
  85023. _this._castRayAndSelectObject(_this.rightController);
  85024. }
  85025. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  85026. _this._castRayAndSelectObject(_this._cameraGazer);
  85027. }
  85028. else {
  85029. _this._cameraGazer._gazeTracker.isVisible = false;
  85030. }
  85031. };
  85032. this._onNewGamepadConnected = function (gamepad) {
  85033. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  85034. if (gamepad.leftStick) {
  85035. gamepad.onleftstickchanged(function (stickValues) {
  85036. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  85037. // Listening to classic/xbox gamepad only if no VR controller is active
  85038. if ((!_this.leftController && !_this.rightController) ||
  85039. ((_this.leftController && !_this.leftController._activePointer) &&
  85040. (_this.rightController && !_this.rightController._activePointer))) {
  85041. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  85042. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  85043. }
  85044. }
  85045. });
  85046. }
  85047. if (gamepad.rightStick) {
  85048. gamepad.onrightstickchanged(function (stickValues) {
  85049. if (_this._teleportationInitialized) {
  85050. _this._checkRotate(stickValues, _this._cameraGazer);
  85051. }
  85052. });
  85053. }
  85054. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  85055. gamepad.onbuttondown(function (buttonPressed) {
  85056. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85057. _this._cameraGazer._selectionPointerDown();
  85058. }
  85059. });
  85060. gamepad.onbuttonup(function (buttonPressed) {
  85061. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85062. _this._cameraGazer._selectionPointerUp();
  85063. }
  85064. });
  85065. }
  85066. }
  85067. else {
  85068. var webVRController = gamepad;
  85069. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  85070. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  85071. _this.rightController = controller;
  85072. }
  85073. else {
  85074. _this.leftController = controller;
  85075. }
  85076. _this._tryEnableInteractionOnController(controller);
  85077. }
  85078. };
  85079. // 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
  85080. this._tryEnableInteractionOnController = function (controller) {
  85081. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  85082. _this._enableInteractionOnController(controller);
  85083. }
  85084. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  85085. _this._enableTeleportationOnController(controller);
  85086. }
  85087. };
  85088. this._onNewGamepadDisconnected = function (gamepad) {
  85089. if (gamepad instanceof BABYLON.WebVRController) {
  85090. if (gamepad.hand === "left" && _this.leftController != null) {
  85091. _this.leftController.dispose();
  85092. _this.leftController = null;
  85093. }
  85094. if (gamepad.hand === "right" && _this.rightController != null) {
  85095. _this.rightController.dispose();
  85096. _this.rightController = null;
  85097. }
  85098. }
  85099. };
  85100. this._workingVector = BABYLON.Vector3.Zero();
  85101. this._workingQuaternion = BABYLON.Quaternion.Identity();
  85102. this._workingMatrix = BABYLON.Matrix.Identity();
  85103. this._scene = scene;
  85104. this._canvas = scene.getEngine().getRenderingCanvas();
  85105. // Parse options
  85106. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  85107. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  85108. }
  85109. if (webVROptions.createDeviceOrientationCamera === undefined) {
  85110. webVROptions.createDeviceOrientationCamera = true;
  85111. }
  85112. if (webVROptions.defaultHeight === undefined) {
  85113. webVROptions.defaultHeight = 1.7;
  85114. }
  85115. if (webVROptions.useCustomVRButton) {
  85116. this._useCustomVRButton = true;
  85117. if (webVROptions.customVRButton) {
  85118. this._btnVR = webVROptions.customVRButton;
  85119. }
  85120. }
  85121. if (webVROptions.rayLength) {
  85122. this._rayLength = webVROptions.rayLength;
  85123. }
  85124. this._defaultHeight = webVROptions.defaultHeight;
  85125. if (webVROptions.positionScale) {
  85126. this._rayLength *= webVROptions.positionScale;
  85127. this._defaultHeight *= webVROptions.positionScale;
  85128. }
  85129. // Set position
  85130. if (this._scene.activeCamera) {
  85131. this._position = this._scene.activeCamera.position.clone();
  85132. }
  85133. else {
  85134. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  85135. }
  85136. // Set non-vr camera
  85137. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  85138. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  85139. // Copy data from existing camera
  85140. if (this._scene.activeCamera) {
  85141. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  85142. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  85143. // Set rotation from previous camera
  85144. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  85145. var targetCamera = this._scene.activeCamera;
  85146. if (targetCamera.rotationQuaternion) {
  85147. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  85148. }
  85149. else {
  85150. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  85151. }
  85152. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  85153. }
  85154. }
  85155. this._scene.activeCamera = this._deviceOrientationCamera;
  85156. if (this._canvas) {
  85157. this._scene.activeCamera.attachControl(this._canvas);
  85158. }
  85159. }
  85160. else {
  85161. this._existingCamera = this._scene.activeCamera;
  85162. }
  85163. // Create VR cameras
  85164. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85165. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  85166. }
  85167. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  85168. this._webVRCamera.useStandingMatrix();
  85169. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  85170. // Create default button
  85171. if (!this._useCustomVRButton) {
  85172. this._btnVR = document.createElement("BUTTON");
  85173. this._btnVR.className = "babylonVRicon";
  85174. this._btnVR.id = "babylonVRiconbtn";
  85175. this._btnVR.title = "Click to switch to VR";
  85176. 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) }";
  85177. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  85178. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  85179. // css += ".babylonVRicon.vrdisplaysupported { }";
  85180. // css += ".babylonVRicon.vrdisplayready { }";
  85181. // css += ".babylonVRicon.vrdisplayrequesting { }";
  85182. var style = document.createElement('style');
  85183. style.appendChild(document.createTextNode(css));
  85184. document.getElementsByTagName('head')[0].appendChild(style);
  85185. this.moveButtonToBottomRight();
  85186. }
  85187. // VR button click event
  85188. if (this._btnVR) {
  85189. this._btnVR.addEventListener("click", function () {
  85190. if (!_this.isInVRMode) {
  85191. _this.enterVR();
  85192. }
  85193. else {
  85194. _this.exitVR();
  85195. }
  85196. });
  85197. }
  85198. // Window events
  85199. window.addEventListener("resize", this._onResize);
  85200. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  85201. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  85202. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  85203. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  85204. // Display vr button when headset is connected
  85205. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85206. this.displayVRButton();
  85207. }
  85208. else {
  85209. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  85210. if (e.vrDisplay) {
  85211. _this.displayVRButton();
  85212. }
  85213. });
  85214. }
  85215. // Exiting VR mode using 'ESC' key on desktop
  85216. this._onKeyDown = function (event) {
  85217. if (event.keyCode === 27 && _this.isInVRMode) {
  85218. _this.exitVR();
  85219. }
  85220. };
  85221. document.addEventListener("keydown", this._onKeyDown);
  85222. // Exiting VR mode double tapping the touch screen
  85223. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  85224. if (_this.isInVRMode) {
  85225. _this.exitVR();
  85226. if (_this._fullscreenVRpresenting) {
  85227. _this._scene.getEngine().switchFullscreen(true);
  85228. }
  85229. }
  85230. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  85231. // Listen for WebVR display changes
  85232. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  85233. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  85234. this._onVRRequestPresentStart = function () {
  85235. _this._webVRrequesting = true;
  85236. _this.updateButtonVisibility();
  85237. };
  85238. this._onVRRequestPresentComplete = function (success) {
  85239. _this._webVRrequesting = false;
  85240. _this.updateButtonVisibility();
  85241. };
  85242. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  85243. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  85244. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  85245. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  85246. scene.onDisposeObservable.add(function () {
  85247. _this.dispose();
  85248. });
  85249. // Gamepad connection events
  85250. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  85251. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  85252. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  85253. this.updateButtonVisibility();
  85254. //create easing functions
  85255. this._circleEase = new BABYLON.CircleEase();
  85256. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  85257. }
  85258. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  85259. /** Return this.onEnteringVRObservable
  85260. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  85261. */
  85262. get: function () {
  85263. return this.onEnteringVRObservable;
  85264. },
  85265. enumerable: true,
  85266. configurable: true
  85267. });
  85268. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  85269. /** Return this.onExitingVRObservable
  85270. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  85271. */
  85272. get: function () {
  85273. return this.onExitingVRObservable;
  85274. },
  85275. enumerable: true,
  85276. configurable: true
  85277. });
  85278. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  85279. /** Return this.onControllerMeshLoadedObservable
  85280. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  85281. */
  85282. get: function () {
  85283. return this.onControllerMeshLoadedObservable;
  85284. },
  85285. enumerable: true,
  85286. configurable: true
  85287. });
  85288. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  85289. /**
  85290. * The mesh used to display where the user is going to teleport.
  85291. */
  85292. get: function () {
  85293. return this._teleportationTarget;
  85294. },
  85295. /**
  85296. * Sets the mesh to be used to display where the user is going to teleport.
  85297. */
  85298. set: function (value) {
  85299. if (value) {
  85300. value.name = "teleportationTarget";
  85301. this._isDefaultTeleportationTarget = false;
  85302. this._teleportationTarget = value;
  85303. }
  85304. },
  85305. enumerable: true,
  85306. configurable: true
  85307. });
  85308. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  85309. /**
  85310. * The mesh used to display where the user is selecting,
  85311. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  85312. * See http://doc.babylonjs.com/resources/baking_transformations
  85313. */
  85314. get: function () {
  85315. return this._cameraGazer._gazeTracker;
  85316. },
  85317. set: function (value) {
  85318. if (value) {
  85319. this._cameraGazer._gazeTracker = value;
  85320. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  85321. this._cameraGazer._gazeTracker.isPickable = false;
  85322. this._cameraGazer._gazeTracker.isVisible = false;
  85323. this._cameraGazer._gazeTracker.name = "gazeTracker";
  85324. if (this.leftController) {
  85325. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85326. }
  85327. if (this.rightController) {
  85328. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85329. }
  85330. }
  85331. },
  85332. enumerable: true,
  85333. configurable: true
  85334. });
  85335. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  85336. /**
  85337. * If the ray of the gaze should be displayed.
  85338. */
  85339. get: function () {
  85340. return this._displayGaze;
  85341. },
  85342. /**
  85343. * Sets if the ray of the gaze should be displayed.
  85344. */
  85345. set: function (value) {
  85346. this._displayGaze = value;
  85347. if (!value) {
  85348. this._cameraGazer._gazeTracker.isVisible = false;
  85349. if (this.leftController) {
  85350. this.leftController._gazeTracker.isVisible = false;
  85351. }
  85352. if (this.rightController) {
  85353. this.rightController._gazeTracker.isVisible = false;
  85354. }
  85355. }
  85356. },
  85357. enumerable: true,
  85358. configurable: true
  85359. });
  85360. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  85361. /**
  85362. * If the ray of the LaserPointer should be displayed.
  85363. */
  85364. get: function () {
  85365. return this._displayLaserPointer;
  85366. },
  85367. /**
  85368. * Sets if the ray of the LaserPointer should be displayed.
  85369. */
  85370. set: function (value) {
  85371. this._displayLaserPointer = value;
  85372. if (!value) {
  85373. if (this.rightController) {
  85374. this.rightController._deactivatePointer();
  85375. this.rightController._gazeTracker.isVisible = false;
  85376. }
  85377. if (this.leftController) {
  85378. this.leftController._deactivatePointer();
  85379. this.leftController._gazeTracker.isVisible = false;
  85380. }
  85381. }
  85382. else {
  85383. if (this.rightController) {
  85384. this.rightController._activatePointer();
  85385. }
  85386. else if (this.leftController) {
  85387. this.leftController._activatePointer();
  85388. }
  85389. }
  85390. },
  85391. enumerable: true,
  85392. configurable: true
  85393. });
  85394. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  85395. /**
  85396. * The deviceOrientationCamera used as the camera when not in VR.
  85397. */
  85398. get: function () {
  85399. return this._deviceOrientationCamera;
  85400. },
  85401. enumerable: true,
  85402. configurable: true
  85403. });
  85404. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  85405. /**
  85406. * Based on the current WebVR support, returns the current VR camera used.
  85407. */
  85408. get: function () {
  85409. if (this._webVRready) {
  85410. return this._webVRCamera;
  85411. }
  85412. else {
  85413. return this._scene.activeCamera;
  85414. }
  85415. },
  85416. enumerable: true,
  85417. configurable: true
  85418. });
  85419. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  85420. /**
  85421. * The webVRCamera which is used when in VR.
  85422. */
  85423. get: function () {
  85424. return this._webVRCamera;
  85425. },
  85426. enumerable: true,
  85427. configurable: true
  85428. });
  85429. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  85430. /**
  85431. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  85432. */
  85433. get: function () {
  85434. return this._vrDeviceOrientationCamera;
  85435. },
  85436. enumerable: true,
  85437. configurable: true
  85438. });
  85439. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  85440. get: function () {
  85441. var result = this._cameraGazer._teleportationRequestInitiated
  85442. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  85443. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  85444. return result;
  85445. },
  85446. enumerable: true,
  85447. configurable: true
  85448. });
  85449. // Raised when one of the controller has loaded successfully its associated default mesh
  85450. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  85451. if (this.leftController && this.leftController.webVRController == webVRController) {
  85452. if (webVRController.mesh) {
  85453. this.leftController._setLaserPointerParent(webVRController.mesh);
  85454. }
  85455. }
  85456. if (this.rightController && this.rightController.webVRController == webVRController) {
  85457. if (webVRController.mesh) {
  85458. this.rightController._setLaserPointerParent(webVRController.mesh);
  85459. }
  85460. }
  85461. try {
  85462. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  85463. }
  85464. catch (err) {
  85465. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  85466. }
  85467. };
  85468. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  85469. /**
  85470. * Gets a value indicating if we are currently in VR mode.
  85471. */
  85472. get: function () {
  85473. return this._webVRpresenting || this._fullscreenVRpresenting;
  85474. },
  85475. enumerable: true,
  85476. configurable: true
  85477. });
  85478. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  85479. var vrDisplay = this._scene.getEngine().getVRDevice();
  85480. if (vrDisplay) {
  85481. var wasPresenting = this._webVRpresenting;
  85482. // A VR display is connected
  85483. this._webVRpresenting = vrDisplay.isPresenting;
  85484. if (wasPresenting && !this._webVRpresenting)
  85485. this.exitVR();
  85486. }
  85487. else {
  85488. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  85489. }
  85490. this.updateButtonVisibility();
  85491. };
  85492. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  85493. this._webVRsupported = eventArgs.vrSupported;
  85494. this._webVRready = !!eventArgs.vrDisplay;
  85495. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  85496. this.updateButtonVisibility();
  85497. };
  85498. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  85499. if (this._canvas && !this._useCustomVRButton) {
  85500. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  85501. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  85502. }
  85503. };
  85504. VRExperienceHelper.prototype.displayVRButton = function () {
  85505. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  85506. document.body.appendChild(this._btnVR);
  85507. this._btnVRDisplayed = true;
  85508. }
  85509. };
  85510. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  85511. if (!this._btnVR || this._useCustomVRButton) {
  85512. return;
  85513. }
  85514. this._btnVR.className = "babylonVRicon";
  85515. if (this.isInVRMode) {
  85516. this._btnVR.className += " vrdisplaypresenting";
  85517. }
  85518. else {
  85519. if (this._webVRready)
  85520. this._btnVR.className += " vrdisplayready";
  85521. if (this._webVRsupported)
  85522. this._btnVR.className += " vrdisplaysupported";
  85523. if (this._webVRrequesting)
  85524. this._btnVR.className += " vrdisplayrequesting";
  85525. }
  85526. };
  85527. /**
  85528. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  85529. * Otherwise, will use the fullscreen API.
  85530. */
  85531. VRExperienceHelper.prototype.enterVR = function () {
  85532. if (this.onEnteringVRObservable) {
  85533. try {
  85534. this.onEnteringVRObservable.notifyObservers(this);
  85535. }
  85536. catch (err) {
  85537. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  85538. }
  85539. }
  85540. if (this._scene.activeCamera) {
  85541. this._position = this._scene.activeCamera.position.clone();
  85542. // make sure that we return to the last active camera
  85543. this._existingCamera = this._scene.activeCamera;
  85544. }
  85545. if (this._webVRrequesting)
  85546. return;
  85547. // If WebVR is supported and a headset is connected
  85548. if (this._webVRready) {
  85549. if (!this._webVRpresenting) {
  85550. this._webVRCamera.position = this._position;
  85551. this._scene.activeCamera = this._webVRCamera;
  85552. }
  85553. }
  85554. else if (this._vrDeviceOrientationCamera) {
  85555. this._vrDeviceOrientationCamera.position = this._position;
  85556. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  85557. this._scene.getEngine().switchFullscreen(true);
  85558. this.updateButtonVisibility();
  85559. }
  85560. if (this._scene.activeCamera && this._canvas) {
  85561. this._scene.activeCamera.attachControl(this._canvas);
  85562. }
  85563. if (this._interactionsEnabled) {
  85564. this._scene.registerBeforeRender(this.beforeRender);
  85565. }
  85566. };
  85567. /**
  85568. * Attempt to exit VR, or fullscreen.
  85569. */
  85570. VRExperienceHelper.prototype.exitVR = function () {
  85571. if (this.onExitingVRObservable) {
  85572. try {
  85573. this.onExitingVRObservable.notifyObservers(this);
  85574. }
  85575. catch (err) {
  85576. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  85577. }
  85578. }
  85579. if (this._webVRpresenting) {
  85580. this._scene.getEngine().disableVR();
  85581. }
  85582. if (this._scene.activeCamera) {
  85583. this._position = this._scene.activeCamera.position.clone();
  85584. }
  85585. if (this._deviceOrientationCamera) {
  85586. this._deviceOrientationCamera.position = this._position;
  85587. this._scene.activeCamera = this._deviceOrientationCamera;
  85588. if (this._canvas) {
  85589. this._scene.activeCamera.attachControl(this._canvas);
  85590. }
  85591. }
  85592. else if (this._existingCamera) {
  85593. this._existingCamera.position = this._position;
  85594. this._scene.activeCamera = this._existingCamera;
  85595. }
  85596. this.updateButtonVisibility();
  85597. if (this._interactionsEnabled) {
  85598. this._scene.unregisterBeforeRender(this.beforeRender);
  85599. }
  85600. };
  85601. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  85602. /**
  85603. * The position of the vr experience helper.
  85604. */
  85605. get: function () {
  85606. return this._position;
  85607. },
  85608. /**
  85609. * Sets the position of the vr experience helper.
  85610. */
  85611. set: function (value) {
  85612. this._position = value;
  85613. if (this._scene.activeCamera) {
  85614. this._scene.activeCamera.position = value;
  85615. }
  85616. },
  85617. enumerable: true,
  85618. configurable: true
  85619. });
  85620. /**
  85621. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  85622. */
  85623. VRExperienceHelper.prototype.enableInteractions = function () {
  85624. var _this = this;
  85625. if (!this._interactionsEnabled) {
  85626. this._interactionsRequested = true;
  85627. if (this.leftController) {
  85628. this._enableInteractionOnController(this.leftController);
  85629. }
  85630. if (this.rightController) {
  85631. this._enableInteractionOnController(this.rightController);
  85632. }
  85633. this.raySelectionPredicate = function (mesh) {
  85634. return mesh.isVisible;
  85635. };
  85636. this.meshSelectionPredicate = function (mesh) {
  85637. return true;
  85638. };
  85639. this._raySelectionPredicate = function (mesh) {
  85640. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  85641. && mesh.name.indexOf("teleportationTarget") === -1
  85642. && mesh.name.indexOf("torusTeleportation") === -1
  85643. && mesh.name.indexOf("laserPointer") === -1)) {
  85644. return _this.raySelectionPredicate(mesh);
  85645. }
  85646. return false;
  85647. };
  85648. this._interactionsEnabled = true;
  85649. }
  85650. };
  85651. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  85652. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  85653. if (this._floorMeshesCollection[i].id === mesh.id) {
  85654. return true;
  85655. }
  85656. }
  85657. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  85658. return true;
  85659. }
  85660. return false;
  85661. };
  85662. /**
  85663. * Adds a floor mesh to be used for teleportation.
  85664. * @param floorMesh the mesh to be used for teleportation.
  85665. */
  85666. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  85667. if (!this._floorMeshesCollection) {
  85668. return;
  85669. }
  85670. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  85671. return;
  85672. }
  85673. this._floorMeshesCollection.push(floorMesh);
  85674. };
  85675. /**
  85676. * Removes a floor mesh from being used for teleportation.
  85677. * @param floorMesh the mesh to be removed.
  85678. */
  85679. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  85680. if (!this._floorMeshesCollection) {
  85681. return;
  85682. }
  85683. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  85684. if (meshIndex !== -1) {
  85685. this._floorMeshesCollection.splice(meshIndex, 1);
  85686. }
  85687. };
  85688. /**
  85689. * Enables interactions and teleportation using the VR controllers and gaze.
  85690. * @param vrTeleportationOptions options to modify teleportation behavior.
  85691. */
  85692. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  85693. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  85694. if (!this._teleportationInitialized) {
  85695. this._teleportationRequested = true;
  85696. this.enableInteractions();
  85697. if (vrTeleportationOptions.floorMeshName) {
  85698. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  85699. }
  85700. if (vrTeleportationOptions.floorMeshes) {
  85701. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  85702. }
  85703. if (this.leftController != null) {
  85704. this._enableTeleportationOnController(this.leftController);
  85705. }
  85706. if (this.rightController != null) {
  85707. this._enableTeleportationOnController(this.rightController);
  85708. }
  85709. // Creates an image processing post process for the vignette not relying
  85710. // on the main scene configuration for image processing to reduce setup and spaces
  85711. // (gamma/linear) conflicts.
  85712. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  85713. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  85714. imageProcessingConfiguration.vignetteEnabled = true;
  85715. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  85716. this._webVRCamera.detachPostProcess(this._postProcessMove);
  85717. this._teleportationInitialized = true;
  85718. if (this._isDefaultTeleportationTarget) {
  85719. this._createTeleportationCircles();
  85720. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  85721. }
  85722. }
  85723. };
  85724. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  85725. var _this = this;
  85726. var controllerMesh = controller.webVRController.mesh;
  85727. if (controllerMesh) {
  85728. controller._interactionsEnabled = true;
  85729. controller._activatePointer();
  85730. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  85731. // Enabling / disabling laserPointer
  85732. if (_this._displayLaserPointer && stateObject.value === 1) {
  85733. if (controller._activePointer) {
  85734. controller._deactivatePointer();
  85735. }
  85736. else {
  85737. controller._activatePointer();
  85738. }
  85739. if (_this.displayGaze) {
  85740. controller._gazeTracker.isVisible = controller._activePointer;
  85741. }
  85742. }
  85743. });
  85744. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  85745. if (!controller._pointerDownOnMeshAsked) {
  85746. if (stateObject.value > _this._padSensibilityUp) {
  85747. controller._selectionPointerDown();
  85748. }
  85749. }
  85750. else if (stateObject.value < _this._padSensibilityDown) {
  85751. controller._selectionPointerUp();
  85752. }
  85753. });
  85754. }
  85755. };
  85756. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  85757. // Dont teleport if another gaze already requested teleportation
  85758. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  85759. return;
  85760. }
  85761. if (!gazer._teleportationRequestInitiated) {
  85762. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  85763. gazer._activatePointer();
  85764. gazer._teleportationRequestInitiated = true;
  85765. }
  85766. }
  85767. else {
  85768. // Listening to the proper controller values changes to confirm teleportation
  85769. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  85770. if (this._teleportActive) {
  85771. this._teleportCamera(this._haloCenter);
  85772. }
  85773. gazer._teleportationRequestInitiated = false;
  85774. }
  85775. }
  85776. };
  85777. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  85778. // Only rotate when user is not currently selecting a teleportation location
  85779. if (gazer._teleportationRequestInitiated) {
  85780. return;
  85781. }
  85782. if (!this._rotationLeftAsked) {
  85783. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  85784. this._rotationLeftAsked = true;
  85785. if (this._rotationAllowed) {
  85786. this._rotateCamera(false);
  85787. }
  85788. }
  85789. }
  85790. else {
  85791. if (stateObject.x > -this._padSensibilityDown) {
  85792. this._rotationLeftAsked = false;
  85793. }
  85794. }
  85795. if (!this._rotationRightAsked) {
  85796. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  85797. this._rotationRightAsked = true;
  85798. if (this._rotationAllowed) {
  85799. this._rotateCamera(true);
  85800. }
  85801. }
  85802. }
  85803. else {
  85804. if (stateObject.x < this._padSensibilityDown) {
  85805. this._rotationRightAsked = false;
  85806. }
  85807. }
  85808. };
  85809. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  85810. // Only teleport backwards when user is not currently selecting a teleportation location
  85811. if (gazer._teleportationRequestInitiated) {
  85812. return;
  85813. }
  85814. // Teleport backwards
  85815. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  85816. if (!gazer._teleportationBackRequestInitiated) {
  85817. if (!this.currentVRCamera) {
  85818. return;
  85819. }
  85820. // Get rotation and position of the current camera
  85821. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  85822. var position = this.currentVRCamera.position;
  85823. // If the camera has device position, use that instead
  85824. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  85825. rotation = this.currentVRCamera.deviceRotationQuaternion;
  85826. position = this.currentVRCamera.devicePosition;
  85827. }
  85828. // Get matrix with only the y rotation of the device rotation
  85829. rotation.toEulerAnglesToRef(this._workingVector);
  85830. this._workingVector.z = 0;
  85831. this._workingVector.x = 0;
  85832. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  85833. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  85834. // Rotate backwards ray by device rotation to cast at the ground behind the user
  85835. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  85836. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  85837. var ray = new BABYLON.Ray(position, this._workingVector);
  85838. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  85839. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  85840. this._teleportCamera(hit.pickedPoint);
  85841. }
  85842. gazer._teleportationBackRequestInitiated = true;
  85843. }
  85844. }
  85845. else {
  85846. gazer._teleportationBackRequestInitiated = false;
  85847. }
  85848. };
  85849. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  85850. var _this = this;
  85851. var controllerMesh = controller.webVRController.mesh;
  85852. if (controllerMesh) {
  85853. if (!controller._interactionsEnabled) {
  85854. this._enableInteractionOnController(controller);
  85855. }
  85856. controller._interactionsEnabled = true;
  85857. controller._teleportationEnabled = true;
  85858. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85859. controller._dpadPressed = false;
  85860. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  85861. controller._dpadPressed = stateObject.pressed;
  85862. if (!controller._dpadPressed) {
  85863. _this._rotationLeftAsked = false;
  85864. _this._rotationRightAsked = false;
  85865. controller._teleportationBackRequestInitiated = false;
  85866. }
  85867. });
  85868. }
  85869. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  85870. if (_this.teleportationEnabled) {
  85871. _this._checkTeleportBackwards(stateObject, controller);
  85872. _this._checkTeleportWithRay(stateObject, controller);
  85873. }
  85874. _this._checkRotate(stateObject, controller);
  85875. });
  85876. }
  85877. };
  85878. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  85879. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  85880. this._teleportationTarget.isPickable = false;
  85881. var length = 512;
  85882. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  85883. dynamicTexture.hasAlpha = true;
  85884. var context = dynamicTexture.getContext();
  85885. var centerX = length / 2;
  85886. var centerY = length / 2;
  85887. var radius = 200;
  85888. context.beginPath();
  85889. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  85890. context.fillStyle = this._teleportationFillColor;
  85891. context.fill();
  85892. context.lineWidth = 10;
  85893. context.strokeStyle = this._teleportationBorderColor;
  85894. context.stroke();
  85895. context.closePath();
  85896. dynamicTexture.update();
  85897. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  85898. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  85899. this._teleportationTarget.material = teleportationCircleMaterial;
  85900. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  85901. torus.isPickable = false;
  85902. torus.parent = this._teleportationTarget;
  85903. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  85904. var keys = [];
  85905. keys.push({
  85906. frame: 0,
  85907. value: 0
  85908. });
  85909. keys.push({
  85910. frame: 30,
  85911. value: 0.4
  85912. });
  85913. keys.push({
  85914. frame: 60,
  85915. value: 0
  85916. });
  85917. animationInnerCircle.setKeys(keys);
  85918. var easingFunction = new BABYLON.SineEase();
  85919. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  85920. animationInnerCircle.setEasingFunction(easingFunction);
  85921. torus.animations = [];
  85922. torus.animations.push(animationInnerCircle);
  85923. this._scene.beginAnimation(torus, 0, 60, true);
  85924. this._hideTeleportationTarget();
  85925. };
  85926. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  85927. this._teleportActive = true;
  85928. if (this._teleportationInitialized) {
  85929. this._teleportationTarget.isVisible = true;
  85930. if (this._isDefaultTeleportationTarget) {
  85931. this._teleportationTarget.getChildren()[0].isVisible = true;
  85932. }
  85933. }
  85934. };
  85935. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  85936. this._teleportActive = false;
  85937. if (this._teleportationInitialized) {
  85938. this._teleportationTarget.isVisible = false;
  85939. if (this._isDefaultTeleportationTarget) {
  85940. this._teleportationTarget.getChildren()[0].isVisible = false;
  85941. }
  85942. }
  85943. };
  85944. VRExperienceHelper.prototype._rotateCamera = function (right) {
  85945. var _this = this;
  85946. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  85947. return;
  85948. }
  85949. if (right) {
  85950. this._rotationAngle++;
  85951. }
  85952. else {
  85953. this._rotationAngle--;
  85954. }
  85955. this.currentVRCamera.animations = [];
  85956. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  85957. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  85958. var animationRotationKeys = [];
  85959. animationRotationKeys.push({
  85960. frame: 0,
  85961. value: this.currentVRCamera.rotationQuaternion
  85962. });
  85963. animationRotationKeys.push({
  85964. frame: 6,
  85965. value: target
  85966. });
  85967. animationRotation.setKeys(animationRotationKeys);
  85968. animationRotation.setEasingFunction(this._circleEase);
  85969. this.currentVRCamera.animations.push(animationRotation);
  85970. this._postProcessMove.animations = [];
  85971. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  85972. var vignetteWeightKeys = [];
  85973. vignetteWeightKeys.push({
  85974. frame: 0,
  85975. value: 0
  85976. });
  85977. vignetteWeightKeys.push({
  85978. frame: 3,
  85979. value: 4
  85980. });
  85981. vignetteWeightKeys.push({
  85982. frame: 6,
  85983. value: 0
  85984. });
  85985. animationPP.setKeys(vignetteWeightKeys);
  85986. animationPP.setEasingFunction(this._circleEase);
  85987. this._postProcessMove.animations.push(animationPP);
  85988. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  85989. var vignetteStretchKeys = [];
  85990. vignetteStretchKeys.push({
  85991. frame: 0,
  85992. value: 0
  85993. });
  85994. vignetteStretchKeys.push({
  85995. frame: 3,
  85996. value: 10
  85997. });
  85998. vignetteStretchKeys.push({
  85999. frame: 6,
  86000. value: 0
  86001. });
  86002. animationPP2.setKeys(vignetteStretchKeys);
  86003. animationPP2.setEasingFunction(this._circleEase);
  86004. this._postProcessMove.animations.push(animationPP2);
  86005. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86006. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86007. this._postProcessMove.samples = 4;
  86008. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86009. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  86010. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86011. });
  86012. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  86013. };
  86014. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  86015. if (hit.pickedPoint) {
  86016. if (gazer._teleportationRequestInitiated) {
  86017. this._displayTeleportationTarget();
  86018. this._haloCenter.copyFrom(hit.pickedPoint);
  86019. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  86020. }
  86021. var pickNormal = hit.getNormal(true, false);
  86022. if (pickNormal) {
  86023. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86024. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86025. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  86026. }
  86027. this._teleportationTarget.position.y += 0.1;
  86028. }
  86029. };
  86030. VRExperienceHelper.prototype._teleportCamera = function (location) {
  86031. var _this = this;
  86032. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86033. return;
  86034. }
  86035. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  86036. // offset of the headset from the anchor.
  86037. if (this.webVRCamera.leftCamera) {
  86038. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  86039. this._workingVector.subtractInPlace(this.webVRCamera.position);
  86040. location.subtractToRef(this._workingVector, this._workingVector);
  86041. }
  86042. else {
  86043. this._workingVector.copyFrom(location);
  86044. }
  86045. // Add height to account for user's height offset
  86046. if (this.isInVRMode) {
  86047. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  86048. }
  86049. else {
  86050. this._workingVector.y += this._defaultHeight;
  86051. }
  86052. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  86053. // Create animation from the camera's position to the new location
  86054. this.currentVRCamera.animations = [];
  86055. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86056. var animationCameraTeleportationKeys = [{
  86057. frame: 0,
  86058. value: this.currentVRCamera.position
  86059. },
  86060. {
  86061. frame: 11,
  86062. value: this._workingVector
  86063. }
  86064. ];
  86065. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  86066. animationCameraTeleportation.setEasingFunction(this._circleEase);
  86067. this.currentVRCamera.animations.push(animationCameraTeleportation);
  86068. this._postProcessMove.animations = [];
  86069. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86070. var vignetteWeightKeys = [];
  86071. vignetteWeightKeys.push({
  86072. frame: 0,
  86073. value: 0
  86074. });
  86075. vignetteWeightKeys.push({
  86076. frame: 5,
  86077. value: 8
  86078. });
  86079. vignetteWeightKeys.push({
  86080. frame: 11,
  86081. value: 0
  86082. });
  86083. animationPP.setKeys(vignetteWeightKeys);
  86084. this._postProcessMove.animations.push(animationPP);
  86085. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86086. var vignetteStretchKeys = [];
  86087. vignetteStretchKeys.push({
  86088. frame: 0,
  86089. value: 0
  86090. });
  86091. vignetteStretchKeys.push({
  86092. frame: 5,
  86093. value: 10
  86094. });
  86095. vignetteStretchKeys.push({
  86096. frame: 11,
  86097. value: 0
  86098. });
  86099. animationPP2.setKeys(vignetteStretchKeys);
  86100. this._postProcessMove.animations.push(animationPP2);
  86101. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86102. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86103. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86104. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  86105. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86106. });
  86107. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  86108. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  86109. });
  86110. this._hideTeleportationTarget();
  86111. };
  86112. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  86113. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86114. return;
  86115. }
  86116. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  86117. // Moving the gazeTracker on the mesh face targetted
  86118. if (hit && hit.pickedPoint) {
  86119. if (this._displayGaze) {
  86120. var multiplier = 1;
  86121. gazer._gazeTracker.isVisible = true;
  86122. if (gazer._isActionableMesh) {
  86123. multiplier = 3;
  86124. }
  86125. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  86126. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  86127. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  86128. var pickNormal = hit.getNormal();
  86129. // To avoid z-fighting
  86130. var deltaFighting = 0.002;
  86131. if (pickNormal) {
  86132. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86133. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86134. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  86135. }
  86136. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  86137. if (gazer._gazeTracker.position.x < 0) {
  86138. gazer._gazeTracker.position.x += deltaFighting;
  86139. }
  86140. else {
  86141. gazer._gazeTracker.position.x -= deltaFighting;
  86142. }
  86143. if (gazer._gazeTracker.position.y < 0) {
  86144. gazer._gazeTracker.position.y += deltaFighting;
  86145. }
  86146. else {
  86147. gazer._gazeTracker.position.y -= deltaFighting;
  86148. }
  86149. if (gazer._gazeTracker.position.z < 0) {
  86150. gazer._gazeTracker.position.z += deltaFighting;
  86151. }
  86152. else {
  86153. gazer._gazeTracker.position.z -= deltaFighting;
  86154. }
  86155. }
  86156. // Changing the size of the laser pointer based on the distance from the targetted point
  86157. gazer._updatePointerDistance(hit.distance);
  86158. }
  86159. else {
  86160. gazer._gazeTracker.isVisible = false;
  86161. }
  86162. if (hit && hit.pickedMesh) {
  86163. gazer._currentHit = hit;
  86164. if (gazer._pointerDownOnMeshAsked) {
  86165. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  86166. }
  86167. // The object selected is the floor, we're in a teleportation scenario
  86168. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  86169. // Moving the teleportation area to this targetted point
  86170. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  86171. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  86172. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86173. }
  86174. gazer._currentMeshSelected = null;
  86175. if (gazer._teleportationRequestInitiated) {
  86176. this._moveTeleportationSelectorTo(hit, gazer);
  86177. }
  86178. return;
  86179. }
  86180. // If not, we're in a selection scenario
  86181. //this._teleportationAllowed = false;
  86182. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  86183. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  86184. this.onNewMeshPicked.notifyObservers(hit);
  86185. gazer._currentMeshSelected = hit.pickedMesh;
  86186. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  86187. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  86188. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  86189. gazer._isActionableMesh = true;
  86190. }
  86191. else {
  86192. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86193. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86194. gazer._isActionableMesh = false;
  86195. }
  86196. try {
  86197. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  86198. }
  86199. catch (err) {
  86200. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  86201. }
  86202. }
  86203. else {
  86204. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86205. gazer._currentMeshSelected = null;
  86206. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86207. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86208. }
  86209. }
  86210. }
  86211. else {
  86212. gazer._currentHit = null;
  86213. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86214. gazer._currentMeshSelected = null;
  86215. //this._teleportationAllowed = false;
  86216. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86217. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86218. }
  86219. };
  86220. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  86221. if (mesh) {
  86222. this.onSelectedMeshUnselected.notifyObservers(mesh);
  86223. }
  86224. };
  86225. /**
  86226. * Sets the color of the laser ray from the vr controllers.
  86227. * @param color new color for the ray.
  86228. */
  86229. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  86230. if (this.leftController) {
  86231. this.leftController._setLaserPointerColor(color);
  86232. }
  86233. if (this.rightController) {
  86234. this.rightController._setLaserPointerColor(color);
  86235. }
  86236. };
  86237. /**
  86238. * Sets the color of the ray from the vr headsets gaze.
  86239. * @param color new color for the ray.
  86240. */
  86241. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  86242. if (!this._cameraGazer._gazeTracker.material) {
  86243. return;
  86244. }
  86245. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  86246. if (this.leftController) {
  86247. this.leftController._gazeTracker.material.emissiveColor = color;
  86248. }
  86249. if (this.rightController) {
  86250. this.rightController._gazeTracker.material.emissiveColor = color;
  86251. }
  86252. };
  86253. /**
  86254. * Exits VR and disposes of the vr experience helper
  86255. */
  86256. VRExperienceHelper.prototype.dispose = function () {
  86257. if (this.isInVRMode) {
  86258. this.exitVR();
  86259. }
  86260. if (this._postProcessMove) {
  86261. this._postProcessMove.dispose();
  86262. }
  86263. if (this._webVRCamera) {
  86264. this._webVRCamera.dispose();
  86265. }
  86266. if (this._vrDeviceOrientationCamera) {
  86267. this._vrDeviceOrientationCamera.dispose();
  86268. }
  86269. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  86270. document.body.removeChild(this._btnVR);
  86271. }
  86272. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  86273. this._deviceOrientationCamera.dispose();
  86274. }
  86275. if (this._cameraGazer) {
  86276. this._cameraGazer.dispose();
  86277. }
  86278. if (this.leftController) {
  86279. this.leftController.dispose();
  86280. }
  86281. if (this.rightController) {
  86282. this.rightController.dispose();
  86283. }
  86284. if (this._teleportationTarget) {
  86285. this._teleportationTarget.dispose();
  86286. }
  86287. this._floorMeshesCollection = [];
  86288. document.removeEventListener("keydown", this._onKeyDown);
  86289. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86290. window.removeEventListener("resize", this._onResize);
  86291. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  86292. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  86293. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  86294. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  86295. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  86296. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  86297. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  86298. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86299. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  86300. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  86301. this._scene.unregisterBeforeRender(this.beforeRender);
  86302. };
  86303. /**
  86304. * Gets the name of the VRExperienceHelper class
  86305. * @returns "VRExperienceHelper"
  86306. */
  86307. VRExperienceHelper.prototype.getClassName = function () {
  86308. return "VRExperienceHelper";
  86309. };
  86310. return VRExperienceHelper;
  86311. }());
  86312. BABYLON.VRExperienceHelper = VRExperienceHelper;
  86313. })(BABYLON || (BABYLON = {}));
  86314. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  86315. "use strict";
  86316. // Mainly based on these 2 articles :
  86317. // 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
  86318. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  86319. var BABYLON;
  86320. (function (BABYLON) {
  86321. var JoystickAxis;
  86322. (function (JoystickAxis) {
  86323. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  86324. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  86325. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  86326. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  86327. var VirtualJoystick = /** @class */ (function () {
  86328. function VirtualJoystick(leftJoystick) {
  86329. var _this = this;
  86330. if (leftJoystick) {
  86331. this._leftJoystick = true;
  86332. }
  86333. else {
  86334. this._leftJoystick = false;
  86335. }
  86336. VirtualJoystick._globalJoystickIndex++;
  86337. // By default left & right arrow keys are moving the X
  86338. // and up & down keys are moving the Y
  86339. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  86340. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  86341. this.reverseLeftRight = false;
  86342. this.reverseUpDown = false;
  86343. // collections of pointers
  86344. this._touches = new BABYLON.StringDictionary();
  86345. this.deltaPosition = BABYLON.Vector3.Zero();
  86346. this._joystickSensibility = 25;
  86347. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86348. this._onResize = function (evt) {
  86349. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86350. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86351. if (VirtualJoystick.vjCanvas) {
  86352. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  86353. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  86354. }
  86355. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  86356. };
  86357. // injecting a canvas element on top of the canvas 3D game
  86358. if (!VirtualJoystick.vjCanvas) {
  86359. window.addEventListener("resize", this._onResize, false);
  86360. VirtualJoystick.vjCanvas = document.createElement("canvas");
  86361. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86362. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86363. VirtualJoystick.vjCanvas.width = window.innerWidth;
  86364. VirtualJoystick.vjCanvas.height = window.innerHeight;
  86365. VirtualJoystick.vjCanvas.style.width = "100%";
  86366. VirtualJoystick.vjCanvas.style.height = "100%";
  86367. VirtualJoystick.vjCanvas.style.position = "absolute";
  86368. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  86369. VirtualJoystick.vjCanvas.style.top = "0px";
  86370. VirtualJoystick.vjCanvas.style.left = "0px";
  86371. VirtualJoystick.vjCanvas.style.zIndex = "5";
  86372. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  86373. // Support for jQuery PEP polyfill
  86374. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  86375. var context = VirtualJoystick.vjCanvas.getContext('2d');
  86376. if (!context) {
  86377. throw new Error("Unable to create canvas for virtual joystick");
  86378. }
  86379. VirtualJoystick.vjCanvasContext = context;
  86380. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  86381. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  86382. document.body.appendChild(VirtualJoystick.vjCanvas);
  86383. }
  86384. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  86385. this.pressed = false;
  86386. // default joystick color
  86387. this._joystickColor = "cyan";
  86388. this._joystickPointerID = -1;
  86389. // current joystick position
  86390. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  86391. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  86392. // origin joystick position
  86393. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  86394. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  86395. this._onPointerDownHandlerRef = function (evt) {
  86396. _this._onPointerDown(evt);
  86397. };
  86398. this._onPointerMoveHandlerRef = function (evt) {
  86399. _this._onPointerMove(evt);
  86400. };
  86401. this._onPointerUpHandlerRef = function (evt) {
  86402. _this._onPointerUp(evt);
  86403. };
  86404. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  86405. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  86406. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  86407. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  86408. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  86409. evt.preventDefault(); // Disables system menu
  86410. }, false);
  86411. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  86412. }
  86413. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  86414. this._joystickSensibility = newJoystickSensibility;
  86415. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86416. };
  86417. VirtualJoystick.prototype._onPointerDown = function (e) {
  86418. var positionOnScreenCondition;
  86419. e.preventDefault();
  86420. if (this._leftJoystick === true) {
  86421. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  86422. }
  86423. else {
  86424. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  86425. }
  86426. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  86427. // First contact will be dedicated to the virtual joystick
  86428. this._joystickPointerID = e.pointerId;
  86429. this._joystickPointerStartPos.x = e.clientX;
  86430. this._joystickPointerStartPos.y = e.clientY;
  86431. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  86432. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  86433. this._deltaJoystickVector.x = 0;
  86434. this._deltaJoystickVector.y = 0;
  86435. this.pressed = true;
  86436. this._touches.add(e.pointerId.toString(), e);
  86437. }
  86438. else {
  86439. // You can only trigger the action buttons with a joystick declared
  86440. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  86441. this._action();
  86442. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  86443. }
  86444. }
  86445. };
  86446. VirtualJoystick.prototype._onPointerMove = function (e) {
  86447. // If the current pointer is the one associated to the joystick (first touch contact)
  86448. if (this._joystickPointerID == e.pointerId) {
  86449. this._joystickPointerPos.x = e.clientX;
  86450. this._joystickPointerPos.y = e.clientY;
  86451. this._deltaJoystickVector = this._joystickPointerPos.clone();
  86452. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  86453. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  86454. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  86455. switch (this._axisTargetedByLeftAndRight) {
  86456. case JoystickAxis.X:
  86457. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  86458. break;
  86459. case JoystickAxis.Y:
  86460. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  86461. break;
  86462. case JoystickAxis.Z:
  86463. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  86464. break;
  86465. }
  86466. var directionUpDown = this.reverseUpDown ? 1 : -1;
  86467. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  86468. switch (this._axisTargetedByUpAndDown) {
  86469. case JoystickAxis.X:
  86470. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  86471. break;
  86472. case JoystickAxis.Y:
  86473. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  86474. break;
  86475. case JoystickAxis.Z:
  86476. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  86477. break;
  86478. }
  86479. }
  86480. else {
  86481. var data = this._touches.get(e.pointerId.toString());
  86482. if (data) {
  86483. data.x = e.clientX;
  86484. data.y = e.clientY;
  86485. }
  86486. }
  86487. };
  86488. VirtualJoystick.prototype._onPointerUp = function (e) {
  86489. if (this._joystickPointerID == e.pointerId) {
  86490. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  86491. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  86492. this._joystickPointerID = -1;
  86493. this.pressed = false;
  86494. }
  86495. else {
  86496. var touch = this._touches.get(e.pointerId.toString());
  86497. if (touch) {
  86498. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  86499. }
  86500. }
  86501. this._deltaJoystickVector.x = 0;
  86502. this._deltaJoystickVector.y = 0;
  86503. this._touches.remove(e.pointerId.toString());
  86504. };
  86505. /**
  86506. * Change the color of the virtual joystick
  86507. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  86508. */
  86509. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  86510. this._joystickColor = newColor;
  86511. };
  86512. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  86513. this._action = action;
  86514. };
  86515. // Define which axis you'd like to control for left & right
  86516. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  86517. switch (axis) {
  86518. case JoystickAxis.X:
  86519. case JoystickAxis.Y:
  86520. case JoystickAxis.Z:
  86521. this._axisTargetedByLeftAndRight = axis;
  86522. break;
  86523. default:
  86524. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  86525. break;
  86526. }
  86527. };
  86528. // Define which axis you'd like to control for up & down
  86529. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  86530. switch (axis) {
  86531. case JoystickAxis.X:
  86532. case JoystickAxis.Y:
  86533. case JoystickAxis.Z:
  86534. this._axisTargetedByUpAndDown = axis;
  86535. break;
  86536. default:
  86537. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  86538. break;
  86539. }
  86540. };
  86541. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  86542. var _this = this;
  86543. if (this.pressed) {
  86544. this._touches.forEach(function (key, touch) {
  86545. if (touch.pointerId === _this._joystickPointerID) {
  86546. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  86547. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  86548. VirtualJoystick.vjCanvasContext.beginPath();
  86549. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  86550. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86551. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  86552. VirtualJoystick.vjCanvasContext.stroke();
  86553. VirtualJoystick.vjCanvasContext.closePath();
  86554. VirtualJoystick.vjCanvasContext.beginPath();
  86555. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86556. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  86557. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  86558. VirtualJoystick.vjCanvasContext.stroke();
  86559. VirtualJoystick.vjCanvasContext.closePath();
  86560. VirtualJoystick.vjCanvasContext.beginPath();
  86561. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  86562. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  86563. VirtualJoystick.vjCanvasContext.stroke();
  86564. VirtualJoystick.vjCanvasContext.closePath();
  86565. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  86566. }
  86567. else {
  86568. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  86569. VirtualJoystick.vjCanvasContext.beginPath();
  86570. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  86571. VirtualJoystick.vjCanvasContext.beginPath();
  86572. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  86573. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  86574. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  86575. VirtualJoystick.vjCanvasContext.stroke();
  86576. VirtualJoystick.vjCanvasContext.closePath();
  86577. touch.prevX = touch.x;
  86578. touch.prevY = touch.y;
  86579. }
  86580. ;
  86581. });
  86582. }
  86583. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  86584. };
  86585. VirtualJoystick.prototype.releaseCanvas = function () {
  86586. if (VirtualJoystick.vjCanvas) {
  86587. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  86588. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  86589. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  86590. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  86591. window.removeEventListener("resize", this._onResize);
  86592. document.body.removeChild(VirtualJoystick.vjCanvas);
  86593. VirtualJoystick.vjCanvas = null;
  86594. }
  86595. };
  86596. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  86597. VirtualJoystick._globalJoystickIndex = 0;
  86598. return VirtualJoystick;
  86599. }());
  86600. BABYLON.VirtualJoystick = VirtualJoystick;
  86601. })(BABYLON || (BABYLON = {}));
  86602. //# sourceMappingURL=babylon.virtualJoystick.js.map
  86603. "use strict";
  86604. var BABYLON;
  86605. (function (BABYLON) {
  86606. // We're mainly based on the logic defined into the FreeCamera code
  86607. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  86608. __extends(VirtualJoysticksCamera, _super);
  86609. function VirtualJoysticksCamera(name, position, scene) {
  86610. var _this = _super.call(this, name, position, scene) || this;
  86611. _this.inputs.addVirtualJoystick();
  86612. return _this;
  86613. }
  86614. VirtualJoysticksCamera.prototype.getClassName = function () {
  86615. return "VirtualJoysticksCamera";
  86616. };
  86617. return VirtualJoysticksCamera;
  86618. }(BABYLON.FreeCamera));
  86619. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  86620. })(BABYLON || (BABYLON = {}));
  86621. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  86622. "use strict";
  86623. var BABYLON;
  86624. (function (BABYLON) {
  86625. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  86626. function FreeCameraVirtualJoystickInput() {
  86627. }
  86628. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  86629. return this._leftjoystick;
  86630. };
  86631. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  86632. return this._rightjoystick;
  86633. };
  86634. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  86635. if (this._leftjoystick) {
  86636. var camera = this.camera;
  86637. var speed = camera._computeLocalCameraSpeed() * 50;
  86638. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  86639. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  86640. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  86641. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  86642. if (!this._leftjoystick.pressed) {
  86643. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  86644. }
  86645. if (!this._rightjoystick.pressed) {
  86646. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  86647. }
  86648. }
  86649. };
  86650. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  86651. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  86652. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  86653. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  86654. this._leftjoystick.setJoystickSensibility(0.15);
  86655. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  86656. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  86657. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  86658. this._rightjoystick.reverseUpDown = true;
  86659. this._rightjoystick.setJoystickSensibility(0.05);
  86660. this._rightjoystick.setJoystickColor("yellow");
  86661. };
  86662. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  86663. this._leftjoystick.releaseCanvas();
  86664. this._rightjoystick.releaseCanvas();
  86665. };
  86666. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  86667. return "FreeCameraVirtualJoystickInput";
  86668. };
  86669. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  86670. return "virtualJoystick";
  86671. };
  86672. return FreeCameraVirtualJoystickInput;
  86673. }());
  86674. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  86675. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  86676. })(BABYLON || (BABYLON = {}));
  86677. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  86678. "use strict";
  86679. var BABYLON;
  86680. (function (BABYLON) {
  86681. var SimplificationSettings = /** @class */ (function () {
  86682. function SimplificationSettings(quality, distance, optimizeMesh) {
  86683. this.quality = quality;
  86684. this.distance = distance;
  86685. this.optimizeMesh = optimizeMesh;
  86686. }
  86687. return SimplificationSettings;
  86688. }());
  86689. BABYLON.SimplificationSettings = SimplificationSettings;
  86690. var SimplificationQueue = /** @class */ (function () {
  86691. function SimplificationQueue() {
  86692. this.running = false;
  86693. this._simplificationArray = [];
  86694. }
  86695. SimplificationQueue.prototype.addTask = function (task) {
  86696. this._simplificationArray.push(task);
  86697. };
  86698. SimplificationQueue.prototype.executeNext = function () {
  86699. var task = this._simplificationArray.pop();
  86700. if (task) {
  86701. this.running = true;
  86702. this.runSimplification(task);
  86703. }
  86704. else {
  86705. this.running = false;
  86706. }
  86707. };
  86708. SimplificationQueue.prototype.runSimplification = function (task) {
  86709. var _this = this;
  86710. if (task.parallelProcessing) {
  86711. //parallel simplifier
  86712. task.settings.forEach(function (setting) {
  86713. var simplifier = _this.getSimplifier(task);
  86714. simplifier.simplify(setting, function (newMesh) {
  86715. task.mesh.addLODLevel(setting.distance, newMesh);
  86716. newMesh.isVisible = true;
  86717. //check if it is the last
  86718. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  86719. //all done, run the success callback.
  86720. task.successCallback();
  86721. }
  86722. _this.executeNext();
  86723. });
  86724. });
  86725. }
  86726. else {
  86727. //single simplifier.
  86728. var simplifier = this.getSimplifier(task);
  86729. var runDecimation = function (setting, callback) {
  86730. simplifier.simplify(setting, function (newMesh) {
  86731. task.mesh.addLODLevel(setting.distance, newMesh);
  86732. newMesh.isVisible = true;
  86733. //run the next quality level
  86734. callback();
  86735. });
  86736. };
  86737. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  86738. runDecimation(task.settings[loop.index], function () {
  86739. loop.executeNext();
  86740. });
  86741. }, function () {
  86742. //execution ended, run the success callback.
  86743. if (task.successCallback) {
  86744. task.successCallback();
  86745. }
  86746. _this.executeNext();
  86747. });
  86748. }
  86749. };
  86750. SimplificationQueue.prototype.getSimplifier = function (task) {
  86751. switch (task.simplificationType) {
  86752. case SimplificationType.QUADRATIC:
  86753. default:
  86754. return new QuadraticErrorSimplification(task.mesh);
  86755. }
  86756. };
  86757. return SimplificationQueue;
  86758. }());
  86759. BABYLON.SimplificationQueue = SimplificationQueue;
  86760. /**
  86761. * The implemented types of simplification.
  86762. * At the moment only Quadratic Error Decimation is implemented.
  86763. */
  86764. var SimplificationType;
  86765. (function (SimplificationType) {
  86766. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  86767. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  86768. var DecimationTriangle = /** @class */ (function () {
  86769. function DecimationTriangle(vertices) {
  86770. this.vertices = vertices;
  86771. this.error = new Array(4);
  86772. this.deleted = false;
  86773. this.isDirty = false;
  86774. this.deletePending = false;
  86775. this.borderFactor = 0;
  86776. }
  86777. return DecimationTriangle;
  86778. }());
  86779. BABYLON.DecimationTriangle = DecimationTriangle;
  86780. var DecimationVertex = /** @class */ (function () {
  86781. function DecimationVertex(position, id) {
  86782. this.position = position;
  86783. this.id = id;
  86784. this.isBorder = true;
  86785. this.q = new QuadraticMatrix();
  86786. this.triangleCount = 0;
  86787. this.triangleStart = 0;
  86788. this.originalOffsets = [];
  86789. }
  86790. DecimationVertex.prototype.updatePosition = function (newPosition) {
  86791. this.position.copyFrom(newPosition);
  86792. };
  86793. return DecimationVertex;
  86794. }());
  86795. BABYLON.DecimationVertex = DecimationVertex;
  86796. var QuadraticMatrix = /** @class */ (function () {
  86797. function QuadraticMatrix(data) {
  86798. this.data = new Array(10);
  86799. for (var i = 0; i < 10; ++i) {
  86800. if (data && data[i]) {
  86801. this.data[i] = data[i];
  86802. }
  86803. else {
  86804. this.data[i] = 0;
  86805. }
  86806. }
  86807. }
  86808. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  86809. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  86810. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  86811. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  86812. return det;
  86813. };
  86814. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  86815. for (var i = 0; i < 10; ++i) {
  86816. this.data[i] += matrix.data[i];
  86817. }
  86818. };
  86819. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  86820. for (var i = 0; i < 10; ++i) {
  86821. this.data[i] += data[i];
  86822. }
  86823. };
  86824. QuadraticMatrix.prototype.add = function (matrix) {
  86825. var m = new QuadraticMatrix();
  86826. for (var i = 0; i < 10; ++i) {
  86827. m.data[i] = this.data[i] + matrix.data[i];
  86828. }
  86829. return m;
  86830. };
  86831. QuadraticMatrix.FromData = function (a, b, c, d) {
  86832. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  86833. };
  86834. //returning an array to avoid garbage collection
  86835. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  86836. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  86837. };
  86838. return QuadraticMatrix;
  86839. }());
  86840. BABYLON.QuadraticMatrix = QuadraticMatrix;
  86841. var Reference = /** @class */ (function () {
  86842. function Reference(vertexId, triangleId) {
  86843. this.vertexId = vertexId;
  86844. this.triangleId = triangleId;
  86845. }
  86846. return Reference;
  86847. }());
  86848. BABYLON.Reference = Reference;
  86849. /**
  86850. * An implementation of the Quadratic Error simplification algorithm.
  86851. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  86852. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  86853. * @author RaananW
  86854. */
  86855. var QuadraticErrorSimplification = /** @class */ (function () {
  86856. function QuadraticErrorSimplification(_mesh) {
  86857. this._mesh = _mesh;
  86858. this.syncIterations = 5000;
  86859. this.aggressiveness = 7;
  86860. this.decimationIterations = 100;
  86861. this.boundingBoxEpsilon = BABYLON.Epsilon;
  86862. }
  86863. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  86864. var _this = this;
  86865. this.initDecimatedMesh();
  86866. //iterating through the submeshes array, one after the other.
  86867. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  86868. _this.initWithMesh(loop.index, function () {
  86869. _this.runDecimation(settings, loop.index, function () {
  86870. loop.executeNext();
  86871. });
  86872. }, settings.optimizeMesh);
  86873. }, function () {
  86874. setTimeout(function () {
  86875. successCallback(_this._reconstructedMesh);
  86876. }, 0);
  86877. });
  86878. };
  86879. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  86880. var _this = this;
  86881. var targetCount = ~~(this.triangles.length * settings.quality);
  86882. var deletedTriangles = 0;
  86883. var triangleCount = this.triangles.length;
  86884. var iterationFunction = function (iteration, callback) {
  86885. setTimeout(function () {
  86886. if (iteration % 5 === 0) {
  86887. _this.updateMesh(iteration === 0);
  86888. }
  86889. for (var i = 0; i < _this.triangles.length; ++i) {
  86890. _this.triangles[i].isDirty = false;
  86891. }
  86892. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  86893. var trianglesIterator = function (i) {
  86894. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  86895. var t = _this.triangles[tIdx];
  86896. if (!t)
  86897. return;
  86898. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  86899. return;
  86900. }
  86901. for (var j = 0; j < 3; ++j) {
  86902. if (t.error[j] < threshold) {
  86903. var deleted0 = [];
  86904. var deleted1 = [];
  86905. var v0 = t.vertices[j];
  86906. var v1 = t.vertices[(j + 1) % 3];
  86907. if (v0.isBorder || v1.isBorder)
  86908. continue;
  86909. var p = BABYLON.Vector3.Zero();
  86910. var n = BABYLON.Vector3.Zero();
  86911. var uv = BABYLON.Vector2.Zero();
  86912. var color = new BABYLON.Color4(0, 0, 0, 1);
  86913. _this.calculateError(v0, v1, p, n, uv, color);
  86914. var delTr = new Array();
  86915. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  86916. continue;
  86917. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  86918. continue;
  86919. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  86920. continue;
  86921. var uniqueArray = new Array();
  86922. delTr.forEach(function (deletedT) {
  86923. if (uniqueArray.indexOf(deletedT) === -1) {
  86924. deletedT.deletePending = true;
  86925. uniqueArray.push(deletedT);
  86926. }
  86927. });
  86928. if (uniqueArray.length % 2 !== 0) {
  86929. continue;
  86930. }
  86931. v0.q = v1.q.add(v0.q);
  86932. v0.updatePosition(p);
  86933. var tStart = _this.references.length;
  86934. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  86935. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  86936. var tCount = _this.references.length - tStart;
  86937. if (tCount <= v0.triangleCount) {
  86938. if (tCount) {
  86939. for (var c = 0; c < tCount; c++) {
  86940. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  86941. }
  86942. }
  86943. }
  86944. else {
  86945. v0.triangleStart = tStart;
  86946. }
  86947. v0.triangleCount = tCount;
  86948. break;
  86949. }
  86950. }
  86951. };
  86952. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  86953. }, 0);
  86954. };
  86955. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  86956. if (triangleCount - deletedTriangles <= targetCount)
  86957. loop.breakLoop();
  86958. else {
  86959. iterationFunction(loop.index, function () {
  86960. loop.executeNext();
  86961. });
  86962. }
  86963. }, function () {
  86964. setTimeout(function () {
  86965. //reconstruct this part of the mesh
  86966. _this.reconstructMesh(submeshIndex);
  86967. successCallback();
  86968. }, 0);
  86969. });
  86970. };
  86971. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  86972. var _this = this;
  86973. this.vertices = [];
  86974. this.triangles = [];
  86975. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86976. var indices = this._mesh.getIndices();
  86977. var submesh = this._mesh.subMeshes[submeshIndex];
  86978. var findInVertices = function (positionToSearch) {
  86979. if (optimizeMesh) {
  86980. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  86981. if (_this.vertices[ii].position.equals(positionToSearch)) {
  86982. return _this.vertices[ii];
  86983. }
  86984. }
  86985. }
  86986. return null;
  86987. };
  86988. var vertexReferences = [];
  86989. var vertexInit = function (i) {
  86990. if (!positionData) {
  86991. return;
  86992. }
  86993. var offset = i + submesh.verticesStart;
  86994. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  86995. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  86996. vertex.originalOffsets.push(offset);
  86997. if (vertex.id === _this.vertices.length) {
  86998. _this.vertices.push(vertex);
  86999. }
  87000. vertexReferences.push(vertex.id);
  87001. };
  87002. //var totalVertices = mesh.getTotalVertices();
  87003. var totalVertices = submesh.verticesCount;
  87004. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  87005. var indicesInit = function (i) {
  87006. if (!indices) {
  87007. return;
  87008. }
  87009. var offset = (submesh.indexStart / 3) + i;
  87010. var pos = (offset * 3);
  87011. var i0 = indices[pos + 0];
  87012. var i1 = indices[pos + 1];
  87013. var i2 = indices[pos + 2];
  87014. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  87015. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  87016. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  87017. var triangle = new DecimationTriangle([v0, v1, v2]);
  87018. triangle.originalOffset = pos;
  87019. _this.triangles.push(triangle);
  87020. };
  87021. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  87022. _this.init(callback);
  87023. });
  87024. });
  87025. };
  87026. QuadraticErrorSimplification.prototype.init = function (callback) {
  87027. var _this = this;
  87028. var triangleInit1 = function (i) {
  87029. var t = _this.triangles[i];
  87030. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  87031. for (var j = 0; j < 3; j++) {
  87032. 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))));
  87033. }
  87034. };
  87035. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  87036. var triangleInit2 = function (i) {
  87037. var t = _this.triangles[i];
  87038. for (var j = 0; j < 3; ++j) {
  87039. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  87040. }
  87041. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87042. };
  87043. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  87044. callback();
  87045. });
  87046. });
  87047. };
  87048. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  87049. var newTriangles = [];
  87050. var i;
  87051. for (i = 0; i < this.vertices.length; ++i) {
  87052. this.vertices[i].triangleCount = 0;
  87053. }
  87054. var t;
  87055. var j;
  87056. for (i = 0; i < this.triangles.length; ++i) {
  87057. if (!this.triangles[i].deleted) {
  87058. t = this.triangles[i];
  87059. for (j = 0; j < 3; ++j) {
  87060. t.vertices[j].triangleCount = 1;
  87061. }
  87062. newTriangles.push(t);
  87063. }
  87064. }
  87065. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  87066. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  87067. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  87068. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  87069. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  87070. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87071. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  87072. var vertexCount = 0;
  87073. for (i = 0; i < this.vertices.length; ++i) {
  87074. var vertex = this.vertices[i];
  87075. vertex.id = vertexCount;
  87076. if (vertex.triangleCount) {
  87077. vertex.originalOffsets.forEach(function (originalOffset) {
  87078. if (!normalData) {
  87079. return;
  87080. }
  87081. newPositionData.push(vertex.position.x);
  87082. newPositionData.push(vertex.position.y);
  87083. newPositionData.push(vertex.position.z);
  87084. newNormalData.push(normalData[originalOffset * 3]);
  87085. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  87086. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  87087. if (uvs && uvs.length) {
  87088. newUVsData.push(uvs[(originalOffset * 2)]);
  87089. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  87090. }
  87091. else if (colorsData && colorsData.length) {
  87092. newColorsData.push(colorsData[(originalOffset * 4)]);
  87093. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  87094. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  87095. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  87096. }
  87097. ++vertexCount;
  87098. });
  87099. }
  87100. }
  87101. var startingIndex = this._reconstructedMesh.getTotalIndices();
  87102. var startingVertex = this._reconstructedMesh.getTotalVertices();
  87103. var submeshesArray = this._reconstructedMesh.subMeshes;
  87104. this._reconstructedMesh.subMeshes = [];
  87105. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  87106. var originalIndices = this._mesh.getIndices();
  87107. for (i = 0; i < newTriangles.length; ++i) {
  87108. t = newTriangles[i]; //now get the new referencing point for each vertex
  87109. [0, 1, 2].forEach(function (idx) {
  87110. var id = originalIndices[t.originalOffset + idx];
  87111. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  87112. if (offset < 0)
  87113. offset = 0;
  87114. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  87115. });
  87116. }
  87117. //overwriting the old vertex buffers and indices.
  87118. this._reconstructedMesh.setIndices(newIndicesArray);
  87119. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  87120. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  87121. if (newUVsData.length > 0)
  87122. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  87123. if (newColorsData.length > 0)
  87124. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  87125. //create submesh
  87126. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  87127. if (submeshIndex > 0) {
  87128. this._reconstructedMesh.subMeshes = [];
  87129. submeshesArray.forEach(function (submesh) {
  87130. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  87131. });
  87132. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  87133. }
  87134. };
  87135. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  87136. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  87137. this._reconstructedMesh.material = this._mesh.material;
  87138. this._reconstructedMesh.parent = this._mesh.parent;
  87139. this._reconstructedMesh.isVisible = false;
  87140. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  87141. };
  87142. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  87143. for (var i = 0; i < vertex1.triangleCount; ++i) {
  87144. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  87145. if (t.deleted)
  87146. continue;
  87147. var s = this.references[vertex1.triangleStart + i].vertexId;
  87148. var v1 = t.vertices[(s + 1) % 3];
  87149. var v2 = t.vertices[(s + 2) % 3];
  87150. if ((v1 === vertex2 || v2 === vertex2)) {
  87151. deletedArray[i] = true;
  87152. delTr.push(t);
  87153. continue;
  87154. }
  87155. var d1 = v1.position.subtract(point);
  87156. d1 = d1.normalize();
  87157. var d2 = v2.position.subtract(point);
  87158. d2 = d2.normalize();
  87159. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  87160. return true;
  87161. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  87162. deletedArray[i] = false;
  87163. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  87164. return true;
  87165. }
  87166. return false;
  87167. };
  87168. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  87169. var newDeleted = deletedTriangles;
  87170. for (var i = 0; i < vertex.triangleCount; ++i) {
  87171. var ref = this.references[vertex.triangleStart + i];
  87172. var t = this.triangles[ref.triangleId];
  87173. if (t.deleted)
  87174. continue;
  87175. if (deletedArray[i] && t.deletePending) {
  87176. t.deleted = true;
  87177. newDeleted++;
  87178. continue;
  87179. }
  87180. t.vertices[ref.vertexId] = origVertex;
  87181. t.isDirty = true;
  87182. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  87183. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  87184. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  87185. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87186. this.references.push(ref);
  87187. }
  87188. return newDeleted;
  87189. };
  87190. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  87191. for (var i = 0; i < this.vertices.length; ++i) {
  87192. var vCount = [];
  87193. var vId = [];
  87194. var v = this.vertices[i];
  87195. var j;
  87196. for (j = 0; j < v.triangleCount; ++j) {
  87197. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  87198. for (var ii = 0; ii < 3; ii++) {
  87199. var ofs = 0;
  87200. var vv = triangle.vertices[ii];
  87201. while (ofs < vCount.length) {
  87202. if (vId[ofs] === vv.id)
  87203. break;
  87204. ++ofs;
  87205. }
  87206. if (ofs === vCount.length) {
  87207. vCount.push(1);
  87208. vId.push(vv.id);
  87209. }
  87210. else {
  87211. vCount[ofs]++;
  87212. }
  87213. }
  87214. }
  87215. for (j = 0; j < vCount.length; ++j) {
  87216. if (vCount[j] === 1) {
  87217. this.vertices[vId[j]].isBorder = true;
  87218. }
  87219. else {
  87220. this.vertices[vId[j]].isBorder = false;
  87221. }
  87222. }
  87223. }
  87224. };
  87225. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  87226. if (identifyBorders === void 0) { identifyBorders = false; }
  87227. var i;
  87228. if (!identifyBorders) {
  87229. var newTrianglesVector = [];
  87230. for (i = 0; i < this.triangles.length; ++i) {
  87231. if (!this.triangles[i].deleted) {
  87232. newTrianglesVector.push(this.triangles[i]);
  87233. }
  87234. }
  87235. this.triangles = newTrianglesVector;
  87236. }
  87237. for (i = 0; i < this.vertices.length; ++i) {
  87238. this.vertices[i].triangleCount = 0;
  87239. this.vertices[i].triangleStart = 0;
  87240. }
  87241. var t;
  87242. var j;
  87243. var v;
  87244. for (i = 0; i < this.triangles.length; ++i) {
  87245. t = this.triangles[i];
  87246. for (j = 0; j < 3; ++j) {
  87247. v = t.vertices[j];
  87248. v.triangleCount++;
  87249. }
  87250. }
  87251. var tStart = 0;
  87252. for (i = 0; i < this.vertices.length; ++i) {
  87253. this.vertices[i].triangleStart = tStart;
  87254. tStart += this.vertices[i].triangleCount;
  87255. this.vertices[i].triangleCount = 0;
  87256. }
  87257. var newReferences = new Array(this.triangles.length * 3);
  87258. for (i = 0; i < this.triangles.length; ++i) {
  87259. t = this.triangles[i];
  87260. for (j = 0; j < 3; ++j) {
  87261. v = t.vertices[j];
  87262. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  87263. v.triangleCount++;
  87264. }
  87265. }
  87266. this.references = newReferences;
  87267. if (identifyBorders) {
  87268. this.identifyBorder();
  87269. }
  87270. };
  87271. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  87272. var x = point.x;
  87273. var y = point.y;
  87274. var z = point.z;
  87275. 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
  87276. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  87277. };
  87278. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  87279. var q = vertex1.q.add(vertex2.q);
  87280. var border = vertex1.isBorder && vertex2.isBorder;
  87281. var error = 0;
  87282. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  87283. if (qDet !== 0 && !border) {
  87284. if (!pointResult) {
  87285. pointResult = BABYLON.Vector3.Zero();
  87286. }
  87287. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  87288. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  87289. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  87290. error = this.vertexError(q, pointResult);
  87291. }
  87292. else {
  87293. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  87294. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  87295. var error1 = this.vertexError(q, vertex1.position);
  87296. var error2 = this.vertexError(q, vertex2.position);
  87297. var error3 = this.vertexError(q, p3);
  87298. error = Math.min(error1, error2, error3);
  87299. if (error === error1) {
  87300. if (pointResult) {
  87301. pointResult.copyFrom(vertex1.position);
  87302. }
  87303. }
  87304. else if (error === error2) {
  87305. if (pointResult) {
  87306. pointResult.copyFrom(vertex2.position);
  87307. }
  87308. }
  87309. else {
  87310. if (pointResult) {
  87311. pointResult.copyFrom(p3);
  87312. }
  87313. }
  87314. }
  87315. return error;
  87316. };
  87317. return QuadraticErrorSimplification;
  87318. }());
  87319. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  87320. })(BABYLON || (BABYLON = {}));
  87321. //# sourceMappingURL=babylon.meshSimplification.js.map
  87322. "use strict";
  87323. var BABYLON;
  87324. (function (BABYLON) {
  87325. var MeshLODLevel = /** @class */ (function () {
  87326. function MeshLODLevel(distance, mesh) {
  87327. this.distance = distance;
  87328. this.mesh = mesh;
  87329. }
  87330. return MeshLODLevel;
  87331. }());
  87332. BABYLON.MeshLODLevel = MeshLODLevel;
  87333. })(BABYLON || (BABYLON = {}));
  87334. //# sourceMappingURL=babylon.meshLODLevel.js.map
  87335. "use strict";
  87336. var BABYLON;
  87337. (function (BABYLON) {
  87338. /**
  87339. * Defines the root class used to create scene optimization to use with SceneOptimizer
  87340. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87341. */
  87342. var SceneOptimization = /** @class */ (function () {
  87343. /**
  87344. * Creates the SceneOptimization object
  87345. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87346. * @param desc defines the description associated with the optimization
  87347. */
  87348. function SceneOptimization(
  87349. /**
  87350. * Defines the priority of this optimization (0 by default which means first in the list)
  87351. */
  87352. priority) {
  87353. if (priority === void 0) { priority = 0; }
  87354. this.priority = priority;
  87355. }
  87356. /**
  87357. * Gets a string describing the action executed by the current optimization
  87358. * @returns description string
  87359. */
  87360. SceneOptimization.prototype.getDescription = function () {
  87361. return "";
  87362. };
  87363. /**
  87364. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87365. * @param scene defines the current scene where to apply this optimization
  87366. * @param optimizer defines the current optimizer
  87367. * @returns true if everything that can be done was applied
  87368. */
  87369. SceneOptimization.prototype.apply = function (scene, optimizer) {
  87370. return true;
  87371. };
  87372. ;
  87373. return SceneOptimization;
  87374. }());
  87375. BABYLON.SceneOptimization = SceneOptimization;
  87376. /**
  87377. * Defines an optimization used to reduce the size of render target textures
  87378. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87379. */
  87380. var TextureOptimization = /** @class */ (function (_super) {
  87381. __extends(TextureOptimization, _super);
  87382. /**
  87383. * Creates the TextureOptimization object
  87384. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87385. * @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
  87386. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87387. */
  87388. function TextureOptimization(
  87389. /**
  87390. * Defines the priority of this optimization (0 by default which means first in the list)
  87391. */
  87392. priority,
  87393. /**
  87394. * 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
  87395. */
  87396. maximumSize,
  87397. /**
  87398. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87399. */
  87400. step) {
  87401. if (priority === void 0) { priority = 0; }
  87402. if (maximumSize === void 0) { maximumSize = 1024; }
  87403. if (step === void 0) { step = 0.5; }
  87404. var _this = _super.call(this, priority) || this;
  87405. _this.priority = priority;
  87406. _this.maximumSize = maximumSize;
  87407. _this.step = step;
  87408. return _this;
  87409. }
  87410. /**
  87411. * Gets a string describing the action executed by the current optimization
  87412. * @returns description string
  87413. */
  87414. TextureOptimization.prototype.getDescription = function () {
  87415. return "Reducing render target texture size to " + this.maximumSize;
  87416. };
  87417. /**
  87418. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87419. * @param scene defines the current scene where to apply this optimization
  87420. * @param optimizer defines the current optimizer
  87421. * @returns true if everything that can be done was applied
  87422. */
  87423. TextureOptimization.prototype.apply = function (scene, optimizer) {
  87424. var allDone = true;
  87425. for (var index = 0; index < scene.textures.length; index++) {
  87426. var texture = scene.textures[index];
  87427. if (!texture.canRescale || texture.getContext) {
  87428. continue;
  87429. }
  87430. var currentSize = texture.getSize();
  87431. var maxDimension = Math.max(currentSize.width, currentSize.height);
  87432. if (maxDimension > this.maximumSize) {
  87433. texture.scale(this.step);
  87434. allDone = false;
  87435. }
  87436. }
  87437. return allDone;
  87438. };
  87439. return TextureOptimization;
  87440. }(SceneOptimization));
  87441. BABYLON.TextureOptimization = TextureOptimization;
  87442. /**
  87443. * Defines an optimization used to increase or decrease the rendering resolution
  87444. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87445. */
  87446. var HardwareScalingOptimization = /** @class */ (function (_super) {
  87447. __extends(HardwareScalingOptimization, _super);
  87448. /**
  87449. * Creates the HardwareScalingOptimization object
  87450. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87451. * @param maximumScale defines the maximum scale to use (2 by default)
  87452. * @param step defines the step to use between two passes (0.5 by default)
  87453. */
  87454. function HardwareScalingOptimization(
  87455. /**
  87456. * Defines the priority of this optimization (0 by default which means first in the list)
  87457. */
  87458. priority,
  87459. /**
  87460. * Defines the maximum scale to use (2 by default)
  87461. */
  87462. maximumScale,
  87463. /**
  87464. * Defines the step to use between two passes (0.5 by default)
  87465. */
  87466. step) {
  87467. if (priority === void 0) { priority = 0; }
  87468. if (maximumScale === void 0) { maximumScale = 2; }
  87469. if (step === void 0) { step = 0.25; }
  87470. var _this = _super.call(this, priority) || this;
  87471. _this.priority = priority;
  87472. _this.maximumScale = maximumScale;
  87473. _this.step = step;
  87474. _this._currentScale = -1;
  87475. _this._directionOffset = 1;
  87476. return _this;
  87477. }
  87478. /**
  87479. * Gets a string describing the action executed by the current optimization
  87480. * @return description string
  87481. */
  87482. HardwareScalingOptimization.prototype.getDescription = function () {
  87483. return "Setting hardware scaling level to " + this._currentScale;
  87484. };
  87485. /**
  87486. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87487. * @param scene defines the current scene where to apply this optimization
  87488. * @param optimizer defines the current optimizer
  87489. * @returns true if everything that can be done was applied
  87490. */
  87491. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  87492. if (this._currentScale === -1) {
  87493. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  87494. if (this._currentScale > this.maximumScale) {
  87495. this._directionOffset = -1;
  87496. }
  87497. }
  87498. this._currentScale += this._directionOffset * this.step;
  87499. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  87500. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  87501. };
  87502. ;
  87503. return HardwareScalingOptimization;
  87504. }(SceneOptimization));
  87505. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  87506. /**
  87507. * Defines an optimization used to remove shadows
  87508. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87509. */
  87510. var ShadowsOptimization = /** @class */ (function (_super) {
  87511. __extends(ShadowsOptimization, _super);
  87512. function ShadowsOptimization() {
  87513. return _super !== null && _super.apply(this, arguments) || this;
  87514. }
  87515. /**
  87516. * Gets a string describing the action executed by the current optimization
  87517. * @return description string
  87518. */
  87519. ShadowsOptimization.prototype.getDescription = function () {
  87520. return "Turning shadows on/off";
  87521. };
  87522. /**
  87523. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87524. * @param scene defines the current scene where to apply this optimization
  87525. * @param optimizer defines the current optimizer
  87526. * @returns true if everything that can be done was applied
  87527. */
  87528. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  87529. scene.shadowsEnabled = optimizer.isInImprovementMode;
  87530. return true;
  87531. };
  87532. ;
  87533. return ShadowsOptimization;
  87534. }(SceneOptimization));
  87535. BABYLON.ShadowsOptimization = ShadowsOptimization;
  87536. /**
  87537. * Defines an optimization used to turn post-processes off
  87538. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87539. */
  87540. var PostProcessesOptimization = /** @class */ (function (_super) {
  87541. __extends(PostProcessesOptimization, _super);
  87542. function PostProcessesOptimization() {
  87543. return _super !== null && _super.apply(this, arguments) || this;
  87544. }
  87545. /**
  87546. * Gets a string describing the action executed by the current optimization
  87547. * @return description string
  87548. */
  87549. PostProcessesOptimization.prototype.getDescription = function () {
  87550. return "Turning post-processes on/off";
  87551. };
  87552. /**
  87553. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87554. * @param scene defines the current scene where to apply this optimization
  87555. * @param optimizer defines the current optimizer
  87556. * @returns true if everything that can be done was applied
  87557. */
  87558. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  87559. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  87560. return true;
  87561. };
  87562. ;
  87563. return PostProcessesOptimization;
  87564. }(SceneOptimization));
  87565. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  87566. /**
  87567. * Defines an optimization used to turn lens flares off
  87568. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87569. */
  87570. var LensFlaresOptimization = /** @class */ (function (_super) {
  87571. __extends(LensFlaresOptimization, _super);
  87572. function LensFlaresOptimization() {
  87573. return _super !== null && _super.apply(this, arguments) || this;
  87574. }
  87575. /**
  87576. * Gets a string describing the action executed by the current optimization
  87577. * @return description string
  87578. */
  87579. LensFlaresOptimization.prototype.getDescription = function () {
  87580. return "Turning lens flares on/off";
  87581. };
  87582. /**
  87583. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87584. * @param scene defines the current scene where to apply this optimization
  87585. * @param optimizer defines the current optimizer
  87586. * @returns true if everything that can be done was applied
  87587. */
  87588. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  87589. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  87590. return true;
  87591. };
  87592. ;
  87593. return LensFlaresOptimization;
  87594. }(SceneOptimization));
  87595. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  87596. /**
  87597. * Defines an optimization based on user defined callback.
  87598. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87599. */
  87600. var CustomOptimization = /** @class */ (function (_super) {
  87601. __extends(CustomOptimization, _super);
  87602. function CustomOptimization() {
  87603. return _super !== null && _super.apply(this, arguments) || this;
  87604. }
  87605. /**
  87606. * Gets a string describing the action executed by the current optimization
  87607. * @returns description string
  87608. */
  87609. CustomOptimization.prototype.getDescription = function () {
  87610. if (this.onGetDescription) {
  87611. return this.onGetDescription();
  87612. }
  87613. return "Running user defined callback";
  87614. };
  87615. /**
  87616. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87617. * @param scene defines the current scene where to apply this optimization
  87618. * @param optimizer defines the current optimizer
  87619. * @returns true if everything that can be done was applied
  87620. */
  87621. CustomOptimization.prototype.apply = function (scene, optimizer) {
  87622. if (this.onApply) {
  87623. return this.onApply(scene, optimizer);
  87624. }
  87625. return true;
  87626. };
  87627. ;
  87628. return CustomOptimization;
  87629. }(SceneOptimization));
  87630. BABYLON.CustomOptimization = CustomOptimization;
  87631. /**
  87632. * Defines an optimization used to turn particles off
  87633. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87634. */
  87635. var ParticlesOptimization = /** @class */ (function (_super) {
  87636. __extends(ParticlesOptimization, _super);
  87637. function ParticlesOptimization() {
  87638. return _super !== null && _super.apply(this, arguments) || this;
  87639. }
  87640. /**
  87641. * Gets a string describing the action executed by the current optimization
  87642. * @return description string
  87643. */
  87644. ParticlesOptimization.prototype.getDescription = function () {
  87645. return "Turning particles on/off";
  87646. };
  87647. /**
  87648. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87649. * @param scene defines the current scene where to apply this optimization
  87650. * @param optimizer defines the current optimizer
  87651. * @returns true if everything that can be done was applied
  87652. */
  87653. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  87654. scene.particlesEnabled = optimizer.isInImprovementMode;
  87655. return true;
  87656. };
  87657. ;
  87658. return ParticlesOptimization;
  87659. }(SceneOptimization));
  87660. BABYLON.ParticlesOptimization = ParticlesOptimization;
  87661. /**
  87662. * Defines an optimization used to turn render targets off
  87663. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87664. */
  87665. var RenderTargetsOptimization = /** @class */ (function (_super) {
  87666. __extends(RenderTargetsOptimization, _super);
  87667. function RenderTargetsOptimization() {
  87668. return _super !== null && _super.apply(this, arguments) || this;
  87669. }
  87670. /**
  87671. * Gets a string describing the action executed by the current optimization
  87672. * @return description string
  87673. */
  87674. RenderTargetsOptimization.prototype.getDescription = function () {
  87675. return "Turning render targets off";
  87676. };
  87677. /**
  87678. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87679. * @param scene defines the current scene where to apply this optimization
  87680. * @param optimizer defines the current optimizer
  87681. * @returns true if everything that can be done was applied
  87682. */
  87683. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  87684. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  87685. return true;
  87686. };
  87687. ;
  87688. return RenderTargetsOptimization;
  87689. }(SceneOptimization));
  87690. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  87691. /**
  87692. * Defines an optimization used to merge meshes with compatible materials
  87693. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87694. */
  87695. var MergeMeshesOptimization = /** @class */ (function (_super) {
  87696. __extends(MergeMeshesOptimization, _super);
  87697. function MergeMeshesOptimization() {
  87698. var _this = _super !== null && _super.apply(this, arguments) || this;
  87699. _this._canBeMerged = function (abstractMesh) {
  87700. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  87701. return false;
  87702. }
  87703. var mesh = abstractMesh;
  87704. if (!mesh.isVisible || !mesh.isEnabled()) {
  87705. return false;
  87706. }
  87707. if (mesh.instances.length > 0) {
  87708. return false;
  87709. }
  87710. if (mesh.skeleton || mesh.hasLODLevels) {
  87711. return false;
  87712. }
  87713. if (mesh.parent) {
  87714. return false;
  87715. }
  87716. return true;
  87717. };
  87718. return _this;
  87719. }
  87720. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  87721. /**
  87722. * Gets or sets a boolean which defines if optimization octree has to be updated
  87723. */
  87724. get: function () {
  87725. return MergeMeshesOptimization._UpdateSelectionTree;
  87726. },
  87727. /**
  87728. * Gets or sets a boolean which defines if optimization octree has to be updated
  87729. */
  87730. set: function (value) {
  87731. MergeMeshesOptimization._UpdateSelectionTree = value;
  87732. },
  87733. enumerable: true,
  87734. configurable: true
  87735. });
  87736. /**
  87737. * Gets a string describing the action executed by the current optimization
  87738. * @return description string
  87739. */
  87740. MergeMeshesOptimization.prototype.getDescription = function () {
  87741. return "Merging similar meshes together";
  87742. };
  87743. /**
  87744. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87745. * @param scene defines the current scene where to apply this optimization
  87746. * @param optimizer defines the current optimizer
  87747. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  87748. * @returns true if everything that can be done was applied
  87749. */
  87750. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  87751. var globalPool = scene.meshes.slice(0);
  87752. var globalLength = globalPool.length;
  87753. for (var index = 0; index < globalLength; index++) {
  87754. var currentPool = new Array();
  87755. var current = globalPool[index];
  87756. // Checks
  87757. if (!this._canBeMerged(current)) {
  87758. continue;
  87759. }
  87760. currentPool.push(current);
  87761. // Find compatible meshes
  87762. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  87763. var otherMesh = globalPool[subIndex];
  87764. if (!this._canBeMerged(otherMesh)) {
  87765. continue;
  87766. }
  87767. if (otherMesh.material !== current.material) {
  87768. continue;
  87769. }
  87770. if (otherMesh.checkCollisions !== current.checkCollisions) {
  87771. continue;
  87772. }
  87773. currentPool.push(otherMesh);
  87774. globalLength--;
  87775. globalPool.splice(subIndex, 1);
  87776. subIndex--;
  87777. }
  87778. if (currentPool.length < 2) {
  87779. continue;
  87780. }
  87781. // Merge meshes
  87782. BABYLON.Mesh.MergeMeshes(currentPool);
  87783. }
  87784. if (updateSelectionTree != undefined) {
  87785. if (updateSelectionTree) {
  87786. scene.createOrUpdateSelectionOctree();
  87787. }
  87788. }
  87789. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  87790. scene.createOrUpdateSelectionOctree();
  87791. }
  87792. return true;
  87793. };
  87794. ;
  87795. MergeMeshesOptimization._UpdateSelectionTree = false;
  87796. return MergeMeshesOptimization;
  87797. }(SceneOptimization));
  87798. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  87799. /**
  87800. * Defines a list of options used by SceneOptimizer
  87801. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87802. */
  87803. var SceneOptimizerOptions = /** @class */ (function () {
  87804. /**
  87805. * Creates a new list of options used by SceneOptimizer
  87806. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  87807. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  87808. */
  87809. function SceneOptimizerOptions(
  87810. /**
  87811. * Defines the target frame rate to reach (60 by default)
  87812. */
  87813. targetFrameRate,
  87814. /**
  87815. * Defines the interval between two checkes (2000ms by default)
  87816. */
  87817. trackerDuration) {
  87818. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  87819. if (trackerDuration === void 0) { trackerDuration = 2000; }
  87820. this.targetFrameRate = targetFrameRate;
  87821. this.trackerDuration = trackerDuration;
  87822. /**
  87823. * Gets the list of optimizations to apply
  87824. */
  87825. this.optimizations = new Array();
  87826. }
  87827. /**
  87828. * Add a new optimization
  87829. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  87830. * @returns the current SceneOptimizerOptions
  87831. */
  87832. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  87833. this.optimizations.push(optimization);
  87834. return this;
  87835. };
  87836. /**
  87837. * Add a new custom optimization
  87838. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  87839. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  87840. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87841. * @returns the current SceneOptimizerOptions
  87842. */
  87843. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  87844. if (priority === void 0) { priority = 0; }
  87845. var optimization = new CustomOptimization(priority);
  87846. optimization.onApply = onApply;
  87847. optimization.onGetDescription = onGetDescription;
  87848. this.optimizations.push(optimization);
  87849. return this;
  87850. };
  87851. /**
  87852. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  87853. * @param targetFrameRate defines the target frame rate (60 by default)
  87854. * @returns a SceneOptimizerOptions object
  87855. */
  87856. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  87857. var result = new SceneOptimizerOptions(targetFrameRate);
  87858. var priority = 0;
  87859. result.addOptimization(new MergeMeshesOptimization(priority));
  87860. result.addOptimization(new ShadowsOptimization(priority));
  87861. result.addOptimization(new LensFlaresOptimization(priority));
  87862. // Next priority
  87863. priority++;
  87864. result.addOptimization(new PostProcessesOptimization(priority));
  87865. result.addOptimization(new ParticlesOptimization(priority));
  87866. // Next priority
  87867. priority++;
  87868. result.addOptimization(new TextureOptimization(priority, 1024));
  87869. return result;
  87870. };
  87871. /**
  87872. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  87873. * @param targetFrameRate defines the target frame rate (60 by default)
  87874. * @returns a SceneOptimizerOptions object
  87875. */
  87876. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  87877. var result = new SceneOptimizerOptions(targetFrameRate);
  87878. var priority = 0;
  87879. result.addOptimization(new MergeMeshesOptimization(priority));
  87880. result.addOptimization(new ShadowsOptimization(priority));
  87881. result.addOptimization(new LensFlaresOptimization(priority));
  87882. // Next priority
  87883. priority++;
  87884. result.addOptimization(new PostProcessesOptimization(priority));
  87885. result.addOptimization(new ParticlesOptimization(priority));
  87886. // Next priority
  87887. priority++;
  87888. result.addOptimization(new TextureOptimization(priority, 512));
  87889. // Next priority
  87890. priority++;
  87891. result.addOptimization(new RenderTargetsOptimization(priority));
  87892. // Next priority
  87893. priority++;
  87894. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  87895. return result;
  87896. };
  87897. /**
  87898. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  87899. * @param targetFrameRate defines the target frame rate (60 by default)
  87900. * @returns a SceneOptimizerOptions object
  87901. */
  87902. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  87903. var result = new SceneOptimizerOptions(targetFrameRate);
  87904. var priority = 0;
  87905. result.addOptimization(new MergeMeshesOptimization(priority));
  87906. result.addOptimization(new ShadowsOptimization(priority));
  87907. result.addOptimization(new LensFlaresOptimization(priority));
  87908. // Next priority
  87909. priority++;
  87910. result.addOptimization(new PostProcessesOptimization(priority));
  87911. result.addOptimization(new ParticlesOptimization(priority));
  87912. // Next priority
  87913. priority++;
  87914. result.addOptimization(new TextureOptimization(priority, 256));
  87915. // Next priority
  87916. priority++;
  87917. result.addOptimization(new RenderTargetsOptimization(priority));
  87918. // Next priority
  87919. priority++;
  87920. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  87921. return result;
  87922. };
  87923. return SceneOptimizerOptions;
  87924. }());
  87925. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  87926. /**
  87927. * Class used to run optimizations in order to reach a target frame rate
  87928. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87929. */
  87930. var SceneOptimizer = /** @class */ (function () {
  87931. /**
  87932. * Creates a new SceneOptimizer
  87933. * @param scene defines the scene to work on
  87934. * @param options defines the options to use with the SceneOptimizer
  87935. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  87936. * @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)
  87937. */
  87938. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  87939. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  87940. if (improvementMode === void 0) { improvementMode = false; }
  87941. var _this = this;
  87942. this._isRunning = false;
  87943. this._currentPriorityLevel = 0;
  87944. this._targetFrameRate = 60;
  87945. this._trackerDuration = 2000;
  87946. this._currentFrameRate = 0;
  87947. this._improvementMode = false;
  87948. /**
  87949. * Defines an observable called when the optimizer reaches the target frame rate
  87950. */
  87951. this.onSuccessObservable = new BABYLON.Observable();
  87952. /**
  87953. * Defines an observable called when the optimizer enables an optimization
  87954. */
  87955. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  87956. /**
  87957. * Defines an observable called when the optimizer is not able to reach the target frame rate
  87958. */
  87959. this.onFailureObservable = new BABYLON.Observable();
  87960. if (!options) {
  87961. this._options = new SceneOptimizerOptions();
  87962. }
  87963. else {
  87964. this._options = options;
  87965. }
  87966. if (this._options.targetFrameRate) {
  87967. this._targetFrameRate = this._options.targetFrameRate;
  87968. }
  87969. if (this._options.trackerDuration) {
  87970. this._trackerDuration = this._options.trackerDuration;
  87971. }
  87972. if (autoGeneratePriorities) {
  87973. var priority = 0;
  87974. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  87975. var optim = _a[_i];
  87976. optim.priority = priority++;
  87977. }
  87978. }
  87979. this._improvementMode = improvementMode;
  87980. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87981. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  87982. _this._sceneDisposeObserver = null;
  87983. _this.dispose();
  87984. });
  87985. }
  87986. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  87987. /**
  87988. * Gets a boolean indicating if the optimizer is in improvement mode
  87989. */
  87990. get: function () {
  87991. return this._improvementMode;
  87992. },
  87993. enumerable: true,
  87994. configurable: true
  87995. });
  87996. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  87997. /**
  87998. * Gets the current priority level (0 at start)
  87999. */
  88000. get: function () {
  88001. return this._currentPriorityLevel;
  88002. },
  88003. enumerable: true,
  88004. configurable: true
  88005. });
  88006. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  88007. /**
  88008. * Gets the current frame rate checked by the SceneOptimizer
  88009. */
  88010. get: function () {
  88011. return this._currentFrameRate;
  88012. },
  88013. enumerable: true,
  88014. configurable: true
  88015. });
  88016. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  88017. /**
  88018. * Gets or sets the current target frame rate (60 by default)
  88019. */
  88020. get: function () {
  88021. return this._targetFrameRate;
  88022. },
  88023. /**
  88024. * Gets or sets the current target frame rate (60 by default)
  88025. */
  88026. set: function (value) {
  88027. this._targetFrameRate = value;
  88028. },
  88029. enumerable: true,
  88030. configurable: true
  88031. });
  88032. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  88033. /**
  88034. * Gets or sets the current interval between two checks (every 2000ms by default)
  88035. */
  88036. get: function () {
  88037. return this._trackerDuration;
  88038. },
  88039. /**
  88040. * Gets or sets the current interval between two checks (every 2000ms by default)
  88041. */
  88042. set: function (value) {
  88043. this._trackerDuration = value;
  88044. },
  88045. enumerable: true,
  88046. configurable: true
  88047. });
  88048. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  88049. /**
  88050. * Gets the list of active optimizations
  88051. */
  88052. get: function () {
  88053. return this._options.optimizations;
  88054. },
  88055. enumerable: true,
  88056. configurable: true
  88057. });
  88058. /**
  88059. * Stops the current optimizer
  88060. */
  88061. SceneOptimizer.prototype.stop = function () {
  88062. this._isRunning = false;
  88063. };
  88064. /**
  88065. * Reset the optimizer to initial step (current priority level = 0)
  88066. */
  88067. SceneOptimizer.prototype.reset = function () {
  88068. this._currentPriorityLevel = 0;
  88069. };
  88070. /**
  88071. * Start the optimizer. By default it will try to reach a specific framerate
  88072. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  88073. */
  88074. SceneOptimizer.prototype.start = function () {
  88075. var _this = this;
  88076. if (this._isRunning) {
  88077. return;
  88078. }
  88079. this._isRunning = true;
  88080. // Let's wait for the scene to be ready before running our check
  88081. this._scene.executeWhenReady(function () {
  88082. setTimeout(function () {
  88083. _this._checkCurrentState();
  88084. }, _this._trackerDuration);
  88085. });
  88086. };
  88087. SceneOptimizer.prototype._checkCurrentState = function () {
  88088. var _this = this;
  88089. if (!this._isRunning) {
  88090. return;
  88091. }
  88092. var scene = this._scene;
  88093. var options = this._options;
  88094. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  88095. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  88096. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  88097. this._isRunning = false;
  88098. this.onSuccessObservable.notifyObservers(this);
  88099. return;
  88100. }
  88101. // Apply current level of optimizations
  88102. var allDone = true;
  88103. var noOptimizationApplied = true;
  88104. for (var index = 0; index < options.optimizations.length; index++) {
  88105. var optimization = options.optimizations[index];
  88106. if (optimization.priority === this._currentPriorityLevel) {
  88107. noOptimizationApplied = false;
  88108. allDone = allDone && optimization.apply(scene, this);
  88109. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  88110. }
  88111. }
  88112. // If no optimization was applied, this is a failure :(
  88113. if (noOptimizationApplied) {
  88114. this._isRunning = false;
  88115. this.onFailureObservable.notifyObservers(this);
  88116. return;
  88117. }
  88118. // If all optimizations were done, move to next level
  88119. if (allDone) {
  88120. this._currentPriorityLevel++;
  88121. }
  88122. // Let's the system running for a specific amount of time before checking FPS
  88123. scene.executeWhenReady(function () {
  88124. setTimeout(function () {
  88125. _this._checkCurrentState();
  88126. }, _this._trackerDuration);
  88127. });
  88128. };
  88129. /**
  88130. * Release all resources
  88131. */
  88132. SceneOptimizer.prototype.dispose = function () {
  88133. this.stop();
  88134. this.onSuccessObservable.clear();
  88135. this.onFailureObservable.clear();
  88136. this.onNewOptimizationAppliedObservable.clear();
  88137. if (this._sceneDisposeObserver) {
  88138. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88139. }
  88140. };
  88141. /**
  88142. * Helper function to create a SceneOptimizer with one single line of code
  88143. * @param scene defines the scene to work on
  88144. * @param options defines the options to use with the SceneOptimizer
  88145. * @param onSuccess defines a callback to call on success
  88146. * @param onFailure defines a callback to call on failure
  88147. * @returns the new SceneOptimizer object
  88148. */
  88149. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  88150. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  88151. if (onSuccess) {
  88152. optimizer.onSuccessObservable.add(function () {
  88153. onSuccess();
  88154. });
  88155. }
  88156. if (onFailure) {
  88157. optimizer.onFailureObservable.add(function () {
  88158. onFailure();
  88159. });
  88160. }
  88161. optimizer.start();
  88162. return optimizer;
  88163. };
  88164. return SceneOptimizer;
  88165. }());
  88166. BABYLON.SceneOptimizer = SceneOptimizer;
  88167. })(BABYLON || (BABYLON = {}));
  88168. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  88169. "use strict";
  88170. var BABYLON;
  88171. (function (BABYLON) {
  88172. var OutlineRenderer = /** @class */ (function () {
  88173. function OutlineRenderer(scene) {
  88174. this.zOffset = 1;
  88175. this._scene = scene;
  88176. }
  88177. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  88178. var _this = this;
  88179. if (useOverlay === void 0) { useOverlay = false; }
  88180. var scene = this._scene;
  88181. var engine = this._scene.getEngine();
  88182. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  88183. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  88184. return;
  88185. }
  88186. var mesh = subMesh.getRenderingMesh();
  88187. var material = subMesh.getMaterial();
  88188. if (!material || !scene.activeCamera) {
  88189. return;
  88190. }
  88191. engine.enableEffect(this._effect);
  88192. // Logarithmic depth
  88193. if (material.useLogarithmicDepth) {
  88194. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  88195. }
  88196. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  88197. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  88198. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  88199. // Bones
  88200. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88201. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88202. }
  88203. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  88204. // Alpha test
  88205. if (material && material.needAlphaTesting()) {
  88206. var alphaTexture = material.getAlphaTestTexture();
  88207. if (alphaTexture) {
  88208. this._effect.setTexture("diffuseSampler", alphaTexture);
  88209. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88210. }
  88211. }
  88212. engine.setZOffset(-this.zOffset);
  88213. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  88214. engine.setZOffset(0);
  88215. };
  88216. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  88217. var defines = [];
  88218. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88219. var mesh = subMesh.getMesh();
  88220. var material = subMesh.getMaterial();
  88221. if (material) {
  88222. // Alpha test
  88223. if (material.needAlphaTesting()) {
  88224. defines.push("#define ALPHATEST");
  88225. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88226. attribs.push(BABYLON.VertexBuffer.UVKind);
  88227. defines.push("#define UV1");
  88228. }
  88229. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  88230. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88231. defines.push("#define UV2");
  88232. }
  88233. }
  88234. //Logarithmic depth
  88235. if (material.useLogarithmicDepth) {
  88236. defines.push("#define LOGARITHMICDEPTH");
  88237. }
  88238. }
  88239. // Bones
  88240. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88243. if (mesh.numBoneInfluencers > 4) {
  88244. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  88245. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  88246. }
  88247. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88248. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  88249. }
  88250. else {
  88251. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88252. }
  88253. // Instances
  88254. if (useInstances) {
  88255. defines.push("#define INSTANCES");
  88256. attribs.push("world0");
  88257. attribs.push("world1");
  88258. attribs.push("world2");
  88259. attribs.push("world3");
  88260. }
  88261. // Get correct effect
  88262. var join = defines.join("\n");
  88263. if (this._cachedDefines !== join) {
  88264. this._cachedDefines = join;
  88265. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  88266. }
  88267. return this._effect.isReady();
  88268. };
  88269. return OutlineRenderer;
  88270. }());
  88271. BABYLON.OutlineRenderer = OutlineRenderer;
  88272. })(BABYLON || (BABYLON = {}));
  88273. //# sourceMappingURL=babylon.outlineRenderer.js.map
  88274. "use strict";
  88275. var BABYLON;
  88276. (function (BABYLON) {
  88277. var FaceAdjacencies = /** @class */ (function () {
  88278. function FaceAdjacencies() {
  88279. this.edges = new Array();
  88280. this.edgesConnectedCount = 0;
  88281. }
  88282. return FaceAdjacencies;
  88283. }());
  88284. var EdgesRenderer = /** @class */ (function () {
  88285. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  88286. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  88287. if (epsilon === void 0) { epsilon = 0.95; }
  88288. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  88289. this.edgesWidthScalerForOrthographic = 1000.0;
  88290. this.edgesWidthScalerForPerspective = 50.0;
  88291. this._linesPositions = new Array();
  88292. this._linesNormals = new Array();
  88293. this._linesIndices = new Array();
  88294. this._buffers = {};
  88295. this._checkVerticesInsteadOfIndices = false;
  88296. this._source = source;
  88297. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  88298. this._epsilon = epsilon;
  88299. this._prepareRessources();
  88300. this._generateEdgesLines();
  88301. }
  88302. EdgesRenderer.prototype._prepareRessources = function () {
  88303. if (this._lineShader) {
  88304. return;
  88305. }
  88306. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  88307. attributes: ["position", "normal"],
  88308. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  88309. });
  88310. this._lineShader.disableDepthWrite = true;
  88311. this._lineShader.backFaceCulling = false;
  88312. };
  88313. EdgesRenderer.prototype._rebuild = function () {
  88314. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88315. if (buffer) {
  88316. buffer._rebuild();
  88317. }
  88318. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88319. if (buffer) {
  88320. buffer._rebuild();
  88321. }
  88322. var scene = this._source.getScene();
  88323. var engine = scene.getEngine();
  88324. this._ib = engine.createIndexBuffer(this._linesIndices);
  88325. };
  88326. EdgesRenderer.prototype.dispose = function () {
  88327. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88328. if (buffer) {
  88329. buffer.dispose();
  88330. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  88331. }
  88332. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88333. if (buffer) {
  88334. buffer.dispose();
  88335. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  88336. }
  88337. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  88338. this._lineShader.dispose();
  88339. };
  88340. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  88341. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  88342. return 0;
  88343. }
  88344. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  88345. return 1;
  88346. }
  88347. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  88348. return 2;
  88349. }
  88350. return -1;
  88351. };
  88352. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  88353. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  88354. return 0;
  88355. }
  88356. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  88357. return 1;
  88358. }
  88359. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  88360. return 2;
  88361. }
  88362. return -1;
  88363. };
  88364. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  88365. var needToCreateLine;
  88366. if (edge === undefined) {
  88367. needToCreateLine = true;
  88368. }
  88369. else {
  88370. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  88371. needToCreateLine = dotProduct < this._epsilon;
  88372. }
  88373. if (needToCreateLine) {
  88374. var offset = this._linesPositions.length / 3;
  88375. var normal = p0.subtract(p1);
  88376. normal.normalize();
  88377. // Positions
  88378. this._linesPositions.push(p0.x);
  88379. this._linesPositions.push(p0.y);
  88380. this._linesPositions.push(p0.z);
  88381. this._linesPositions.push(p0.x);
  88382. this._linesPositions.push(p0.y);
  88383. this._linesPositions.push(p0.z);
  88384. this._linesPositions.push(p1.x);
  88385. this._linesPositions.push(p1.y);
  88386. this._linesPositions.push(p1.z);
  88387. this._linesPositions.push(p1.x);
  88388. this._linesPositions.push(p1.y);
  88389. this._linesPositions.push(p1.z);
  88390. // Normals
  88391. this._linesNormals.push(p1.x);
  88392. this._linesNormals.push(p1.y);
  88393. this._linesNormals.push(p1.z);
  88394. this._linesNormals.push(-1);
  88395. this._linesNormals.push(p1.x);
  88396. this._linesNormals.push(p1.y);
  88397. this._linesNormals.push(p1.z);
  88398. this._linesNormals.push(1);
  88399. this._linesNormals.push(p0.x);
  88400. this._linesNormals.push(p0.y);
  88401. this._linesNormals.push(p0.z);
  88402. this._linesNormals.push(-1);
  88403. this._linesNormals.push(p0.x);
  88404. this._linesNormals.push(p0.y);
  88405. this._linesNormals.push(p0.z);
  88406. this._linesNormals.push(1);
  88407. // Indices
  88408. this._linesIndices.push(offset);
  88409. this._linesIndices.push(offset + 1);
  88410. this._linesIndices.push(offset + 2);
  88411. this._linesIndices.push(offset);
  88412. this._linesIndices.push(offset + 2);
  88413. this._linesIndices.push(offset + 3);
  88414. }
  88415. };
  88416. EdgesRenderer.prototype._generateEdgesLines = function () {
  88417. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88418. var indices = this._source.getIndices();
  88419. if (!indices || !positions) {
  88420. return;
  88421. }
  88422. // First let's find adjacencies
  88423. var adjacencies = new Array();
  88424. var faceNormals = new Array();
  88425. var index;
  88426. var faceAdjacencies;
  88427. // Prepare faces
  88428. for (index = 0; index < indices.length; index += 3) {
  88429. faceAdjacencies = new FaceAdjacencies();
  88430. var p0Index = indices[index];
  88431. var p1Index = indices[index + 1];
  88432. var p2Index = indices[index + 2];
  88433. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  88434. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  88435. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  88436. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  88437. faceNormal.normalize();
  88438. faceNormals.push(faceNormal);
  88439. adjacencies.push(faceAdjacencies);
  88440. }
  88441. // Scan
  88442. for (index = 0; index < adjacencies.length; index++) {
  88443. faceAdjacencies = adjacencies[index];
  88444. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  88445. var otherFaceAdjacencies = adjacencies[otherIndex];
  88446. if (faceAdjacencies.edgesConnectedCount === 3) {
  88447. break;
  88448. }
  88449. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  88450. continue;
  88451. }
  88452. var otherP0 = indices[otherIndex * 3];
  88453. var otherP1 = indices[otherIndex * 3 + 1];
  88454. var otherP2 = indices[otherIndex * 3 + 2];
  88455. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  88456. var otherEdgeIndex = 0;
  88457. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  88458. continue;
  88459. }
  88460. switch (edgeIndex) {
  88461. case 0:
  88462. if (this._checkVerticesInsteadOfIndices) {
  88463. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88464. }
  88465. else {
  88466. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  88467. }
  88468. break;
  88469. case 1:
  88470. if (this._checkVerticesInsteadOfIndices) {
  88471. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88472. }
  88473. else {
  88474. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  88475. }
  88476. break;
  88477. case 2:
  88478. if (this._checkVerticesInsteadOfIndices) {
  88479. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  88480. }
  88481. else {
  88482. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  88483. }
  88484. break;
  88485. }
  88486. if (otherEdgeIndex === -1) {
  88487. continue;
  88488. }
  88489. faceAdjacencies.edges[edgeIndex] = otherIndex;
  88490. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  88491. faceAdjacencies.edgesConnectedCount++;
  88492. otherFaceAdjacencies.edgesConnectedCount++;
  88493. if (faceAdjacencies.edgesConnectedCount === 3) {
  88494. break;
  88495. }
  88496. }
  88497. }
  88498. }
  88499. // Create lines
  88500. for (index = 0; index < adjacencies.length; index++) {
  88501. // 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
  88502. var current = adjacencies[index];
  88503. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  88504. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  88505. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  88506. }
  88507. // Merge into a single mesh
  88508. var engine = this._source.getScene().getEngine();
  88509. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  88510. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  88511. this._ib = engine.createIndexBuffer(this._linesIndices);
  88512. this._indicesCount = this._linesIndices.length;
  88513. };
  88514. EdgesRenderer.prototype.render = function () {
  88515. var scene = this._source.getScene();
  88516. if (!this._lineShader.isReady() || !scene.activeCamera) {
  88517. return;
  88518. }
  88519. var engine = scene.getEngine();
  88520. this._lineShader._preBind();
  88521. // VBOs
  88522. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  88523. scene.resetCachedMaterial();
  88524. this._lineShader.setColor4("color", this._source.edgesColor);
  88525. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  88526. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  88527. }
  88528. else {
  88529. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  88530. }
  88531. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  88532. this._lineShader.bind(this._source.getWorldMatrix());
  88533. // Draw order
  88534. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  88535. this._lineShader.unbind();
  88536. engine.setDepthWrite(true);
  88537. };
  88538. return EdgesRenderer;
  88539. }());
  88540. BABYLON.EdgesRenderer = EdgesRenderer;
  88541. })(BABYLON || (BABYLON = {}));
  88542. //# sourceMappingURL=babylon.edgesRenderer.js.map
  88543. "use strict";
  88544. var __assign = (this && this.__assign) || Object.assign || function(t) {
  88545. for (var s, i = 1, n = arguments.length; i < n; i++) {
  88546. s = arguments[i];
  88547. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  88548. t[p] = s[p];
  88549. }
  88550. return t;
  88551. };
  88552. var BABYLON;
  88553. (function (BABYLON) {
  88554. /**
  88555. * The effect layer Helps adding post process effect blended with the main pass.
  88556. *
  88557. * This can be for instance use to generate glow or higlight effects on the scene.
  88558. *
  88559. * The effect layer class can not be used directly and is intented to inherited from to be
  88560. * customized per effects.
  88561. */
  88562. var EffectLayer = /** @class */ (function () {
  88563. /**
  88564. * Instantiates a new effect Layer and references it in the scene.
  88565. * @param name The name of the layer
  88566. * @param scene The scene to use the layer in
  88567. */
  88568. function EffectLayer(
  88569. /** The Friendly of the effect in the scene */
  88570. name, scene) {
  88571. this._vertexBuffers = {};
  88572. this._maxSize = 0;
  88573. this._mainTextureDesiredSize = { width: 0, height: 0 };
  88574. this._shouldRender = true;
  88575. this._postProcesses = [];
  88576. this._textures = [];
  88577. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  88578. /**
  88579. * The clear color of the texture used to generate the glow map.
  88580. */
  88581. this.neutralColor = new BABYLON.Color4();
  88582. /**
  88583. * Specifies wether the highlight layer is enabled or not.
  88584. */
  88585. this.isEnabled = true;
  88586. /**
  88587. * An event triggered when the effect layer has been disposed.
  88588. */
  88589. this.onDisposeObservable = new BABYLON.Observable();
  88590. /**
  88591. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  88592. */
  88593. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  88594. /**
  88595. * An event triggered when the generated texture is being merged in the scene.
  88596. */
  88597. this.onBeforeComposeObservable = new BABYLON.Observable();
  88598. /**
  88599. * An event triggered when the generated texture has been merged in the scene.
  88600. */
  88601. this.onAfterComposeObservable = new BABYLON.Observable();
  88602. /**
  88603. * An event triggered when the efffect layer changes its size.
  88604. */
  88605. this.onSizeChangedObservable = new BABYLON.Observable();
  88606. this.name = name;
  88607. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88608. this._engine = scene.getEngine();
  88609. this._maxSize = this._engine.getCaps().maxTextureSize;
  88610. this._scene.effectLayers.push(this);
  88611. // Generate Buffers
  88612. this._generateIndexBuffer();
  88613. this._genrateVertexBuffer();
  88614. }
  88615. Object.defineProperty(EffectLayer.prototype, "camera", {
  88616. /**
  88617. * Gets the camera attached to the layer.
  88618. */
  88619. get: function () {
  88620. return this._effectLayerOptions.camera;
  88621. },
  88622. enumerable: true,
  88623. configurable: true
  88624. });
  88625. /**
  88626. * Initializes the effect layer with the required options.
  88627. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  88628. */
  88629. EffectLayer.prototype._init = function (options) {
  88630. // Adapt options
  88631. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  88632. this._setMainTextureSize();
  88633. this._createMainTexture();
  88634. this._createTextureAndPostProcesses();
  88635. this._mergeEffect = this._createMergeEffect();
  88636. };
  88637. /**
  88638. * Generates the index buffer of the full screen quad blending to the main canvas.
  88639. */
  88640. EffectLayer.prototype._generateIndexBuffer = function () {
  88641. // Indices
  88642. var indices = [];
  88643. indices.push(0);
  88644. indices.push(1);
  88645. indices.push(2);
  88646. indices.push(0);
  88647. indices.push(2);
  88648. indices.push(3);
  88649. this._indexBuffer = this._engine.createIndexBuffer(indices);
  88650. };
  88651. /**
  88652. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  88653. */
  88654. EffectLayer.prototype._genrateVertexBuffer = function () {
  88655. // VBO
  88656. var vertices = [];
  88657. vertices.push(1, 1);
  88658. vertices.push(-1, 1);
  88659. vertices.push(-1, -1);
  88660. vertices.push(1, -1);
  88661. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88662. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88663. };
  88664. /**
  88665. * Sets the main texture desired size which is the closest power of two
  88666. * of the engine canvas size.
  88667. */
  88668. EffectLayer.prototype._setMainTextureSize = function () {
  88669. if (this._effectLayerOptions.mainTextureFixedSize) {
  88670. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  88671. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  88672. }
  88673. else {
  88674. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  88675. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  88676. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  88677. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  88678. }
  88679. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  88680. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  88681. };
  88682. /**
  88683. * Creates the main texture for the effect layer.
  88684. */
  88685. EffectLayer.prototype._createMainTexture = function () {
  88686. var _this = this;
  88687. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  88688. width: this._mainTextureDesiredSize.width,
  88689. height: this._mainTextureDesiredSize.height
  88690. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88691. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  88692. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88693. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88694. this._mainTexture.anisotropicFilteringLevel = 1;
  88695. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88696. this._mainTexture.renderParticles = false;
  88697. this._mainTexture.renderList = null;
  88698. this._mainTexture.ignoreCameraViewport = true;
  88699. // Custom render function
  88700. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  88701. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  88702. var index;
  88703. var engine = _this._scene.getEngine();
  88704. if (depthOnlySubMeshes.length) {
  88705. engine.setColorWrite(false);
  88706. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  88707. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  88708. }
  88709. engine.setColorWrite(true);
  88710. }
  88711. for (index = 0; index < opaqueSubMeshes.length; index++) {
  88712. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  88713. }
  88714. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  88715. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  88716. }
  88717. for (index = 0; index < transparentSubMeshes.length; index++) {
  88718. _this._renderSubMesh(transparentSubMeshes.data[index]);
  88719. }
  88720. };
  88721. this._mainTexture.onClearObservable.add(function (engine) {
  88722. engine.clear(_this.neutralColor, true, true, true);
  88723. });
  88724. };
  88725. /**
  88726. * Checks for the readiness of the element composing the layer.
  88727. * @param subMesh the mesh to check for
  88728. * @param useInstances specify wether or not to use instances to render the mesh
  88729. * @param emissiveTexture the associated emissive texture used to generate the glow
  88730. * @return true if ready otherwise, false
  88731. */
  88732. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  88733. var material = subMesh.getMaterial();
  88734. if (!material) {
  88735. return false;
  88736. }
  88737. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  88738. return false;
  88739. }
  88740. var defines = [];
  88741. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88742. var mesh = subMesh.getMesh();
  88743. var uv1 = false;
  88744. var uv2 = false;
  88745. // Alpha test
  88746. if (material && material.needAlphaTesting()) {
  88747. var alphaTexture = material.getAlphaTestTexture();
  88748. if (alphaTexture) {
  88749. defines.push("#define ALPHATEST");
  88750. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  88751. alphaTexture.coordinatesIndex === 1) {
  88752. defines.push("#define DIFFUSEUV2");
  88753. uv2 = true;
  88754. }
  88755. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88756. defines.push("#define DIFFUSEUV1");
  88757. uv1 = true;
  88758. }
  88759. }
  88760. }
  88761. // Emissive
  88762. if (emissiveTexture) {
  88763. defines.push("#define EMISSIVE");
  88764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  88765. emissiveTexture.coordinatesIndex === 1) {
  88766. defines.push("#define EMISSIVEUV2");
  88767. uv2 = true;
  88768. }
  88769. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88770. defines.push("#define EMISSIVEUV1");
  88771. uv1 = true;
  88772. }
  88773. }
  88774. if (uv1) {
  88775. attribs.push(BABYLON.VertexBuffer.UVKind);
  88776. defines.push("#define UV1");
  88777. }
  88778. if (uv2) {
  88779. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88780. defines.push("#define UV2");
  88781. }
  88782. // Bones
  88783. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88784. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88785. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88786. if (mesh.numBoneInfluencers > 4) {
  88787. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  88788. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  88789. }
  88790. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88791. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  88792. }
  88793. else {
  88794. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88795. }
  88796. // Morph targets
  88797. var manager = mesh.morphTargetManager;
  88798. var morphInfluencers = 0;
  88799. if (manager) {
  88800. if (manager.numInfluencers > 0) {
  88801. defines.push("#define MORPHTARGETS");
  88802. morphInfluencers = manager.numInfluencers;
  88803. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  88804. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  88805. }
  88806. }
  88807. // Instances
  88808. if (useInstances) {
  88809. defines.push("#define INSTANCES");
  88810. attribs.push("world0");
  88811. attribs.push("world1");
  88812. attribs.push("world2");
  88813. attribs.push("world3");
  88814. }
  88815. // Get correct effect
  88816. var join = defines.join("\n");
  88817. if (this._cachedDefines !== join) {
  88818. this._cachedDefines = join;
  88819. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  88820. }
  88821. return this._effectLayerMapGenerationEffect.isReady();
  88822. };
  88823. /**
  88824. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  88825. */
  88826. EffectLayer.prototype.render = function () {
  88827. var currentEffect = this._mergeEffect;
  88828. // Check
  88829. if (!currentEffect.isReady())
  88830. return;
  88831. for (var i = 0; i < this._postProcesses.length; i++) {
  88832. if (!this._postProcesses[i].isReady()) {
  88833. return;
  88834. }
  88835. }
  88836. var engine = this._scene.getEngine();
  88837. this.onBeforeComposeObservable.notifyObservers(this);
  88838. // Render
  88839. engine.enableEffect(currentEffect);
  88840. engine.setState(false);
  88841. // VBOs
  88842. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88843. // Cache
  88844. var previousAlphaMode = engine.getAlphaMode();
  88845. // Go Blend.
  88846. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  88847. // Blends the map on the main canvas.
  88848. this._internalRender(currentEffect);
  88849. // Restore Alpha
  88850. engine.setAlphaMode(previousAlphaMode);
  88851. this.onAfterComposeObservable.notifyObservers(this);
  88852. // Handle size changes.
  88853. var size = this._mainTexture.getSize();
  88854. this._setMainTextureSize();
  88855. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  88856. // Recreate RTT and post processes on size change.
  88857. this.onSizeChangedObservable.notifyObservers(this);
  88858. this._disposeTextureAndPostProcesses();
  88859. this._createMainTexture();
  88860. this._createTextureAndPostProcesses();
  88861. }
  88862. };
  88863. /**
  88864. * Determine if a given mesh will be used in the current effect.
  88865. * @param mesh mesh to test
  88866. * @returns true if the mesh will be used
  88867. */
  88868. EffectLayer.prototype.hasMesh = function (mesh) {
  88869. return true;
  88870. };
  88871. /**
  88872. * Returns true if the layer contains information to display, otherwise false.
  88873. * @returns true if the glow layer should be rendered
  88874. */
  88875. EffectLayer.prototype.shouldRender = function () {
  88876. return this.isEnabled && this._shouldRender;
  88877. };
  88878. /**
  88879. * Returns true if the mesh should render, otherwise false.
  88880. * @param mesh The mesh to render
  88881. * @returns true if it should render otherwise false
  88882. */
  88883. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  88884. return true;
  88885. };
  88886. /**
  88887. * Returns true if the mesh should render, otherwise false.
  88888. * @param mesh The mesh to render
  88889. * @returns true if it should render otherwise false
  88890. */
  88891. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  88892. return true;
  88893. };
  88894. /**
  88895. * Renders the submesh passed in parameter to the generation map.
  88896. */
  88897. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  88898. var _this = this;
  88899. if (!this.shouldRender()) {
  88900. return;
  88901. }
  88902. var material = subMesh.getMaterial();
  88903. var mesh = subMesh.getRenderingMesh();
  88904. var scene = this._scene;
  88905. var engine = scene.getEngine();
  88906. if (!material) {
  88907. return;
  88908. }
  88909. // Do not block in blend mode.
  88910. if (material.needAlphaBlendingForMesh(mesh)) {
  88911. return;
  88912. }
  88913. // Culling
  88914. engine.setState(material.backFaceCulling);
  88915. // Managing instances
  88916. var batch = mesh._getInstancesRenderList(subMesh._id);
  88917. if (batch.mustReturn) {
  88918. return;
  88919. }
  88920. // Early Exit per mesh
  88921. if (!this._shouldRenderMesh(mesh)) {
  88922. return;
  88923. }
  88924. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  88925. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  88926. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  88927. engine.enableEffect(this._effectLayerMapGenerationEffect);
  88928. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  88929. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  88930. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  88931. // Alpha test
  88932. if (material && material.needAlphaTesting()) {
  88933. var alphaTexture = material.getAlphaTestTexture();
  88934. if (alphaTexture) {
  88935. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  88936. var textureMatrix = alphaTexture.getTextureMatrix();
  88937. if (textureMatrix) {
  88938. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  88939. }
  88940. }
  88941. }
  88942. // Glow emissive only
  88943. if (this._emissiveTextureAndColor.texture) {
  88944. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  88945. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  88946. }
  88947. // Bones
  88948. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88949. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88950. }
  88951. // Morph targets
  88952. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  88953. // Draw
  88954. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  88955. }
  88956. else {
  88957. // Need to reset refresh rate of the shadowMap
  88958. this._mainTexture.resetRefreshCounter();
  88959. }
  88960. };
  88961. /**
  88962. * Rebuild the required buffers.
  88963. * @ignore Internal use only.
  88964. */
  88965. EffectLayer.prototype._rebuild = function () {
  88966. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88967. if (vb) {
  88968. vb._rebuild();
  88969. }
  88970. this._generateIndexBuffer();
  88971. };
  88972. /**
  88973. * Dispose only the render target textures and post process.
  88974. */
  88975. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  88976. this._mainTexture.dispose();
  88977. for (var i = 0; i < this._postProcesses.length; i++) {
  88978. if (this._postProcesses[i]) {
  88979. this._postProcesses[i].dispose();
  88980. }
  88981. }
  88982. this._postProcesses = [];
  88983. for (var i = 0; i < this._textures.length; i++) {
  88984. if (this._textures[i]) {
  88985. this._textures[i].dispose();
  88986. }
  88987. }
  88988. this._textures = [];
  88989. };
  88990. /**
  88991. * Dispose the highlight layer and free resources.
  88992. */
  88993. EffectLayer.prototype.dispose = function () {
  88994. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88995. if (vertexBuffer) {
  88996. vertexBuffer.dispose();
  88997. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88998. }
  88999. if (this._indexBuffer) {
  89000. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89001. this._indexBuffer = null;
  89002. }
  89003. // Clean textures and post processes
  89004. this._disposeTextureAndPostProcesses();
  89005. // Remove from scene
  89006. var index = this._scene.effectLayers.indexOf(this, 0);
  89007. if (index > -1) {
  89008. this._scene.effectLayers.splice(index, 1);
  89009. }
  89010. // Callback
  89011. this.onDisposeObservable.notifyObservers(this);
  89012. this.onDisposeObservable.clear();
  89013. this.onBeforeRenderMainTextureObservable.clear();
  89014. this.onBeforeComposeObservable.clear();
  89015. this.onAfterComposeObservable.clear();
  89016. this.onSizeChangedObservable.clear();
  89017. };
  89018. /**
  89019. * Gets the class name of the effect layer
  89020. * @returns the string with the class name of the effect layer
  89021. */
  89022. EffectLayer.prototype.getClassName = function () {
  89023. return "EffectLayer";
  89024. };
  89025. __decorate([
  89026. BABYLON.serialize()
  89027. ], EffectLayer.prototype, "name", void 0);
  89028. __decorate([
  89029. BABYLON.serializeAsColor4()
  89030. ], EffectLayer.prototype, "neutralColor", void 0);
  89031. __decorate([
  89032. BABYLON.serialize()
  89033. ], EffectLayer.prototype, "isEnabled", void 0);
  89034. __decorate([
  89035. BABYLON.serializeAsCameraReference()
  89036. ], EffectLayer.prototype, "camera", null);
  89037. return EffectLayer;
  89038. }());
  89039. BABYLON.EffectLayer = EffectLayer;
  89040. })(BABYLON || (BABYLON = {}));
  89041. //# sourceMappingURL=babylon.effectLayer.js.map
  89042. "use strict";
  89043. var BABYLON;
  89044. (function (BABYLON) {
  89045. /**
  89046. * Special Glow Blur post process only blurring the alpha channel
  89047. * It enforces keeping the most luminous color in the color channel.
  89048. */
  89049. var GlowBlurPostProcess = /** @class */ (function (_super) {
  89050. __extends(GlowBlurPostProcess, _super);
  89051. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  89052. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89053. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  89054. _this.direction = direction;
  89055. _this.kernel = kernel;
  89056. _this.onApplyObservable.add(function (effect) {
  89057. effect.setFloat2("screenSize", _this.width, _this.height);
  89058. effect.setVector2("direction", _this.direction);
  89059. effect.setFloat("blurWidth", _this.kernel);
  89060. });
  89061. return _this;
  89062. }
  89063. return GlowBlurPostProcess;
  89064. }(BABYLON.PostProcess));
  89065. /**
  89066. * The highlight layer Helps adding a glow effect around a mesh.
  89067. *
  89068. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  89069. * glowy meshes to your scene.
  89070. *
  89071. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  89072. */
  89073. var HighlightLayer = /** @class */ (function (_super) {
  89074. __extends(HighlightLayer, _super);
  89075. /**
  89076. * Instantiates a new highlight Layer and references it to the scene..
  89077. * @param name The name of the layer
  89078. * @param scene The scene to use the layer in
  89079. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  89080. */
  89081. function HighlightLayer(name, scene, options) {
  89082. var _this = _super.call(this, name, scene) || this;
  89083. _this.name = name;
  89084. /**
  89085. * Specifies whether or not the inner glow is ACTIVE in the layer.
  89086. */
  89087. _this.innerGlow = true;
  89088. /**
  89089. * Specifies whether or not the outer glow is ACTIVE in the layer.
  89090. */
  89091. _this.outerGlow = true;
  89092. /**
  89093. * An event triggered when the highlight layer is being blurred.
  89094. */
  89095. _this.onBeforeBlurObservable = new BABYLON.Observable();
  89096. /**
  89097. * An event triggered when the highlight layer has been blurred.
  89098. */
  89099. _this.onAfterBlurObservable = new BABYLON.Observable();
  89100. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  89101. _this._meshes = {};
  89102. _this._excludedMeshes = {};
  89103. _this.neutralColor = HighlightLayer.NeutralColor;
  89104. // Warn on stencil
  89105. if (!_this._engine.isStencilEnable) {
  89106. 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 }");
  89107. }
  89108. // Adapt options
  89109. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89110. // Initialize the layer
  89111. _this._init({
  89112. alphaBlendingMode: _this._options.alphaBlendingMode,
  89113. camera: _this._options.camera,
  89114. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  89115. mainTextureRatio: _this._options.mainTextureRatio
  89116. });
  89117. // Do not render as long as no meshes have been added
  89118. _this._shouldRender = false;
  89119. return _this;
  89120. }
  89121. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  89122. /**
  89123. * Gets the horizontal size of the blur.
  89124. */
  89125. get: function () {
  89126. return this._horizontalBlurPostprocess.kernel;
  89127. },
  89128. /**
  89129. * Specifies the horizontal size of the blur.
  89130. */
  89131. set: function (value) {
  89132. this._horizontalBlurPostprocess.kernel = value;
  89133. },
  89134. enumerable: true,
  89135. configurable: true
  89136. });
  89137. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  89138. /**
  89139. * Gets the vertical size of the blur.
  89140. */
  89141. get: function () {
  89142. return this._verticalBlurPostprocess.kernel;
  89143. },
  89144. /**
  89145. * Specifies the vertical size of the blur.
  89146. */
  89147. set: function (value) {
  89148. this._verticalBlurPostprocess.kernel = value;
  89149. },
  89150. enumerable: true,
  89151. configurable: true
  89152. });
  89153. /**
  89154. * Get the effect name of the layer.
  89155. * @return The effect name
  89156. */
  89157. HighlightLayer.prototype.getEffectName = function () {
  89158. return HighlightLayer.EffectName;
  89159. };
  89160. /**
  89161. * Create the merge effect. This is the shader use to blit the information back
  89162. * to the main canvas at the end of the scene rendering.
  89163. */
  89164. HighlightLayer.prototype._createMergeEffect = function () {
  89165. // Effect
  89166. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  89167. };
  89168. /**
  89169. * Creates the render target textures and post processes used in the highlight layer.
  89170. */
  89171. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  89172. var _this = this;
  89173. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  89174. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  89175. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  89176. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  89177. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  89178. width: blurTextureWidth,
  89179. height: blurTextureHeight
  89180. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89181. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89182. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89183. this._blurTexture.anisotropicFilteringLevel = 16;
  89184. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89185. this._blurTexture.renderParticles = false;
  89186. this._blurTexture.ignoreCameraViewport = true;
  89187. this._textures = [this._blurTexture];
  89188. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  89189. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89190. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  89191. effect.setTexture("textureSampler", _this._mainTexture);
  89192. });
  89193. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89194. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89195. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89196. });
  89197. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89198. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  89199. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89200. });
  89201. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89202. }
  89203. else {
  89204. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  89205. width: blurTextureWidth,
  89206. height: blurTextureHeight
  89207. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89208. this._horizontalBlurPostprocess.width = blurTextureWidth;
  89209. this._horizontalBlurPostprocess.height = blurTextureHeight;
  89210. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89211. effect.setTexture("textureSampler", _this._mainTexture);
  89212. });
  89213. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  89214. width: blurTextureWidth,
  89215. height: blurTextureHeight
  89216. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89217. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89218. }
  89219. this._mainTexture.onAfterUnbindObservable.add(function () {
  89220. _this.onBeforeBlurObservable.notifyObservers(_this);
  89221. var internalTexture = _this._blurTexture.getInternalTexture();
  89222. if (internalTexture) {
  89223. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  89224. }
  89225. _this.onAfterBlurObservable.notifyObservers(_this);
  89226. });
  89227. // Prevent autoClear.
  89228. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  89229. };
  89230. /**
  89231. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  89232. */
  89233. HighlightLayer.prototype.needStencil = function () {
  89234. return true;
  89235. };
  89236. /**
  89237. * Checks for the readiness of the element composing the layer.
  89238. * @param subMesh the mesh to check for
  89239. * @param useInstances specify wether or not to use instances to render the mesh
  89240. * @param emissiveTexture the associated emissive texture used to generate the glow
  89241. * @return true if ready otherwise, false
  89242. */
  89243. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  89244. var material = subMesh.getMaterial();
  89245. var mesh = subMesh.getRenderingMesh();
  89246. if (!material || !mesh || !this._meshes) {
  89247. return false;
  89248. }
  89249. var emissiveTexture = null;
  89250. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89251. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89252. emissiveTexture = material.emissiveTexture;
  89253. }
  89254. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  89255. };
  89256. /**
  89257. * Implementation specific of rendering the generating effect on the main canvas.
  89258. * @param effect The effect used to render through
  89259. */
  89260. HighlightLayer.prototype._internalRender = function (effect) {
  89261. // Texture
  89262. effect.setTexture("textureSampler", this._blurTexture);
  89263. // Cache
  89264. var engine = this._engine;
  89265. var previousStencilBuffer = engine.getStencilBuffer();
  89266. var previousStencilFunction = engine.getStencilFunction();
  89267. var previousStencilMask = engine.getStencilMask();
  89268. var previousStencilOperationPass = engine.getStencilOperationPass();
  89269. var previousStencilOperationFail = engine.getStencilOperationFail();
  89270. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  89271. var previousStencilReference = engine.getStencilFunctionReference();
  89272. // Stencil operations
  89273. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  89274. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  89275. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  89276. // Draw order
  89277. engine.setStencilMask(0x00);
  89278. engine.setStencilBuffer(true);
  89279. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  89280. // 2 passes inner outer
  89281. if (this.outerGlow) {
  89282. effect.setFloat("offset", 0);
  89283. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  89284. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89285. }
  89286. if (this.innerGlow) {
  89287. effect.setFloat("offset", 1);
  89288. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  89289. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89290. }
  89291. // Restore Cache
  89292. engine.setStencilFunction(previousStencilFunction);
  89293. engine.setStencilMask(previousStencilMask);
  89294. engine.setStencilBuffer(previousStencilBuffer);
  89295. engine.setStencilOperationPass(previousStencilOperationPass);
  89296. engine.setStencilOperationFail(previousStencilOperationFail);
  89297. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  89298. engine.setStencilFunctionReference(previousStencilReference);
  89299. };
  89300. /**
  89301. * Returns true if the layer contains information to display, otherwise false.
  89302. */
  89303. HighlightLayer.prototype.shouldRender = function () {
  89304. if (_super.prototype.shouldRender.call(this)) {
  89305. return this._meshes ? true : false;
  89306. }
  89307. return false;
  89308. };
  89309. /**
  89310. * Returns true if the mesh should render, otherwise false.
  89311. * @param mesh The mesh to render
  89312. * @returns true if it should render otherwise false
  89313. */
  89314. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  89315. // Excluded Mesh
  89316. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  89317. return false;
  89318. }
  89319. ;
  89320. return true;
  89321. };
  89322. /**
  89323. * Sets the required values for both the emissive texture and and the main color.
  89324. */
  89325. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  89326. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89327. if (highlightLayerMesh) {
  89328. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  89329. }
  89330. else {
  89331. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  89332. }
  89333. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89334. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  89335. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  89336. }
  89337. else {
  89338. this._emissiveTextureAndColor.texture = null;
  89339. }
  89340. };
  89341. /**
  89342. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  89343. * @param mesh The mesh to exclude from the highlight layer
  89344. */
  89345. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  89346. if (!this._excludedMeshes) {
  89347. return;
  89348. }
  89349. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89350. if (!meshExcluded) {
  89351. this._excludedMeshes[mesh.uniqueId] = {
  89352. mesh: mesh,
  89353. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  89354. mesh.getEngine().setStencilBuffer(false);
  89355. }),
  89356. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  89357. mesh.getEngine().setStencilBuffer(true);
  89358. }),
  89359. };
  89360. }
  89361. };
  89362. /**
  89363. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  89364. * @param mesh The mesh to highlight
  89365. */
  89366. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  89367. if (!this._excludedMeshes) {
  89368. return;
  89369. }
  89370. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89371. if (meshExcluded) {
  89372. if (meshExcluded.beforeRender) {
  89373. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  89374. }
  89375. if (meshExcluded.afterRender) {
  89376. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  89377. }
  89378. }
  89379. this._excludedMeshes[mesh.uniqueId] = null;
  89380. };
  89381. /**
  89382. * Determine if a given mesh will be highlighted by the current HighlightLayer
  89383. * @param mesh mesh to test
  89384. * @returns true if the mesh will be highlighted by the current HighlightLayer
  89385. */
  89386. HighlightLayer.prototype.hasMesh = function (mesh) {
  89387. if (!this._meshes) {
  89388. return false;
  89389. }
  89390. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  89391. };
  89392. /**
  89393. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  89394. * @param mesh The mesh to highlight
  89395. * @param color The color of the highlight
  89396. * @param glowEmissiveOnly Extract the glow from the emissive texture
  89397. */
  89398. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  89399. var _this = this;
  89400. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  89401. if (!this._meshes) {
  89402. return;
  89403. }
  89404. var meshHighlight = this._meshes[mesh.uniqueId];
  89405. if (meshHighlight) {
  89406. meshHighlight.color = color;
  89407. }
  89408. else {
  89409. this._meshes[mesh.uniqueId] = {
  89410. mesh: mesh,
  89411. color: color,
  89412. // Lambda required for capture due to Observable this context
  89413. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  89414. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  89415. _this._defaultStencilReference(mesh);
  89416. }
  89417. else {
  89418. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  89419. }
  89420. }),
  89421. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  89422. glowEmissiveOnly: glowEmissiveOnly
  89423. };
  89424. }
  89425. this._shouldRender = true;
  89426. };
  89427. /**
  89428. * Remove a mesh from the highlight layer in order to make it stop glowing.
  89429. * @param mesh The mesh to highlight
  89430. */
  89431. HighlightLayer.prototype.removeMesh = function (mesh) {
  89432. if (!this._meshes) {
  89433. return;
  89434. }
  89435. var meshHighlight = this._meshes[mesh.uniqueId];
  89436. if (meshHighlight) {
  89437. if (meshHighlight.observerHighlight) {
  89438. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  89439. }
  89440. if (meshHighlight.observerDefault) {
  89441. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  89442. }
  89443. delete this._meshes[mesh.uniqueId];
  89444. }
  89445. this._shouldRender = false;
  89446. for (var meshHighlightToCheck in this._meshes) {
  89447. if (this._meshes[meshHighlightToCheck]) {
  89448. this._shouldRender = true;
  89449. break;
  89450. }
  89451. }
  89452. };
  89453. /**
  89454. * Force the stencil to the normal expected value for none glowing parts
  89455. */
  89456. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  89457. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  89458. };
  89459. /**
  89460. * Free any resources and references associated to a mesh.
  89461. * Internal use
  89462. * @param mesh The mesh to free.
  89463. */
  89464. HighlightLayer.prototype._disposeMesh = function (mesh) {
  89465. this.removeMesh(mesh);
  89466. this.removeExcludedMesh(mesh);
  89467. };
  89468. /**
  89469. * Dispose the highlight layer and free resources.
  89470. */
  89471. HighlightLayer.prototype.dispose = function () {
  89472. if (this._meshes) {
  89473. // Clean mesh references
  89474. for (var id in this._meshes) {
  89475. var meshHighlight = this._meshes[id];
  89476. if (meshHighlight && meshHighlight.mesh) {
  89477. if (meshHighlight.observerHighlight) {
  89478. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  89479. }
  89480. if (meshHighlight.observerDefault) {
  89481. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  89482. }
  89483. }
  89484. }
  89485. this._meshes = null;
  89486. }
  89487. if (this._excludedMeshes) {
  89488. for (var id in this._excludedMeshes) {
  89489. var meshHighlight = this._excludedMeshes[id];
  89490. if (meshHighlight) {
  89491. if (meshHighlight.beforeRender) {
  89492. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  89493. }
  89494. if (meshHighlight.afterRender) {
  89495. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  89496. }
  89497. }
  89498. }
  89499. this._excludedMeshes = null;
  89500. }
  89501. _super.prototype.dispose.call(this);
  89502. };
  89503. /**
  89504. * Effect Name of the highlight layer.
  89505. */
  89506. HighlightLayer.EffectName = "HighlightLayer";
  89507. /**
  89508. * The neutral color used during the preparation of the glow effect.
  89509. * This is black by default as the blend operation is a blend operation.
  89510. */
  89511. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  89512. /**
  89513. * Stencil value used for glowing meshes.
  89514. */
  89515. HighlightLayer.GlowingMeshStencilReference = 0x02;
  89516. /**
  89517. * Stencil value used for the other meshes in the scene.
  89518. */
  89519. HighlightLayer.NormalMeshStencilReference = 0x01;
  89520. return HighlightLayer;
  89521. }(BABYLON.EffectLayer));
  89522. BABYLON.HighlightLayer = HighlightLayer;
  89523. })(BABYLON || (BABYLON = {}));
  89524. //# sourceMappingURL=babylon.highlightLayer.js.map
  89525. "use strict";
  89526. var BABYLON;
  89527. (function (BABYLON) {
  89528. /**
  89529. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  89530. *
  89531. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  89532. * glowy meshes to your scene.
  89533. *
  89534. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  89535. */
  89536. var GlowLayer = /** @class */ (function (_super) {
  89537. __extends(GlowLayer, _super);
  89538. /**
  89539. * Instantiates a new glow Layer and references it to the scene.
  89540. * @param name The name of the layer
  89541. * @param scene The scene to use the layer in
  89542. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  89543. */
  89544. function GlowLayer(name, scene, options) {
  89545. var _this = _super.call(this, name, scene) || this;
  89546. _this._intensity = 1.0;
  89547. _this._includedOnlyMeshes = [];
  89548. _this._excludedMeshes = [];
  89549. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  89550. // Adapt options
  89551. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  89552. // Initialize the layer
  89553. _this._init({
  89554. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  89555. camera: _this._options.camera,
  89556. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  89557. mainTextureRatio: _this._options.mainTextureRatio
  89558. });
  89559. return _this;
  89560. }
  89561. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  89562. /**
  89563. * Gets the kernel size of the blur.
  89564. */
  89565. get: function () {
  89566. return this._horizontalBlurPostprocess1.kernel;
  89567. },
  89568. /**
  89569. * Sets the kernel size of the blur.
  89570. */
  89571. set: function (value) {
  89572. this._horizontalBlurPostprocess1.kernel = value;
  89573. this._verticalBlurPostprocess1.kernel = value;
  89574. this._horizontalBlurPostprocess2.kernel = value;
  89575. this._verticalBlurPostprocess2.kernel = value;
  89576. },
  89577. enumerable: true,
  89578. configurable: true
  89579. });
  89580. Object.defineProperty(GlowLayer.prototype, "intensity", {
  89581. /**
  89582. * Gets the glow intensity.
  89583. */
  89584. get: function () {
  89585. return this._intensity;
  89586. },
  89587. /**
  89588. * Sets the glow intensity.
  89589. */
  89590. set: function (value) {
  89591. this._intensity = value;
  89592. },
  89593. enumerable: true,
  89594. configurable: true
  89595. });
  89596. /**
  89597. * Get the effect name of the layer.
  89598. * @return The effect name
  89599. */
  89600. GlowLayer.prototype.getEffectName = function () {
  89601. return GlowLayer.EffectName;
  89602. };
  89603. /**
  89604. * Create the merge effect. This is the shader use to blit the information back
  89605. * to the main canvas at the end of the scene rendering.
  89606. */
  89607. GlowLayer.prototype._createMergeEffect = function () {
  89608. // Effect
  89609. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  89610. };
  89611. /**
  89612. * Creates the render target textures and post processes used in the glow layer.
  89613. */
  89614. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  89615. var _this = this;
  89616. var blurTextureWidth = this._mainTextureDesiredSize.width;
  89617. var blurTextureHeight = this._mainTextureDesiredSize.height;
  89618. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  89619. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  89620. var textureType = 0;
  89621. if (this._engine.getCaps().textureHalfFloatRender) {
  89622. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89623. }
  89624. else {
  89625. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89626. }
  89627. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  89628. width: blurTextureWidth,
  89629. height: blurTextureHeight
  89630. }, this._scene, false, true, textureType);
  89631. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89632. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89633. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89634. this._blurTexture1.renderParticles = false;
  89635. this._blurTexture1.ignoreCameraViewport = true;
  89636. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  89637. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  89638. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  89639. width: blurTextureWidth2,
  89640. height: blurTextureHeight2
  89641. }, this._scene, false, true, textureType);
  89642. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89643. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89644. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89645. this._blurTexture2.renderParticles = false;
  89646. this._blurTexture2.ignoreCameraViewport = true;
  89647. this._textures = [this._blurTexture1, this._blurTexture2];
  89648. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  89649. width: blurTextureWidth,
  89650. height: blurTextureHeight
  89651. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89652. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  89653. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  89654. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  89655. effect.setTexture("textureSampler", _this._mainTexture);
  89656. });
  89657. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  89658. width: blurTextureWidth,
  89659. height: blurTextureHeight
  89660. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89661. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  89662. width: blurTextureWidth2,
  89663. height: blurTextureHeight2
  89664. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89665. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  89666. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  89667. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  89668. effect.setTexture("textureSampler", _this._blurTexture1);
  89669. });
  89670. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  89671. width: blurTextureWidth2,
  89672. height: blurTextureHeight2
  89673. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  89674. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  89675. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  89676. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  89677. this._mainTexture.samples = this._options.mainTextureSamples;
  89678. this._mainTexture.onAfterUnbindObservable.add(function () {
  89679. var internalTexture = _this._blurTexture1.getInternalTexture();
  89680. if (internalTexture) {
  89681. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  89682. internalTexture = _this._blurTexture2.getInternalTexture();
  89683. if (internalTexture) {
  89684. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  89685. }
  89686. }
  89687. });
  89688. // Prevent autoClear.
  89689. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  89690. };
  89691. /**
  89692. * Checks for the readiness of the element composing the layer.
  89693. * @param subMesh the mesh to check for
  89694. * @param useInstances specify wether or not to use instances to render the mesh
  89695. * @param emissiveTexture the associated emissive texture used to generate the glow
  89696. * @return true if ready otherwise, false
  89697. */
  89698. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  89699. var material = subMesh.getMaterial();
  89700. var mesh = subMesh.getRenderingMesh();
  89701. if (!material || !mesh) {
  89702. return false;
  89703. }
  89704. var emissiveTexture = material.emissiveTexture;
  89705. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  89706. };
  89707. /**
  89708. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  89709. */
  89710. GlowLayer.prototype.needStencil = function () {
  89711. return false;
  89712. };
  89713. /**
  89714. * Implementation specific of rendering the generating effect on the main canvas.
  89715. * @param effect The effect used to render through
  89716. */
  89717. GlowLayer.prototype._internalRender = function (effect) {
  89718. // Texture
  89719. effect.setTexture("textureSampler", this._blurTexture1);
  89720. effect.setTexture("textureSampler2", this._blurTexture2);
  89721. effect.setFloat("offset", this._intensity);
  89722. // Cache
  89723. var engine = this._engine;
  89724. var previousStencilBuffer = engine.getStencilBuffer();
  89725. // Draw order
  89726. engine.setStencilBuffer(false);
  89727. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89728. // Draw order
  89729. engine.setStencilBuffer(previousStencilBuffer);
  89730. };
  89731. /**
  89732. * Sets the required values for both the emissive texture and and the main color.
  89733. */
  89734. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  89735. var textureLevel = 1.0;
  89736. if (this.customEmissiveTextureSelector) {
  89737. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  89738. }
  89739. else {
  89740. if (material) {
  89741. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  89742. if (this._emissiveTextureAndColor.texture) {
  89743. textureLevel = this._emissiveTextureAndColor.texture.level;
  89744. }
  89745. }
  89746. else {
  89747. this._emissiveTextureAndColor.texture = null;
  89748. }
  89749. }
  89750. if (this.customEmissiveColorSelector) {
  89751. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  89752. }
  89753. else {
  89754. if (material.emissiveColor) {
  89755. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  89756. }
  89757. else {
  89758. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  89759. }
  89760. }
  89761. };
  89762. /**
  89763. * Returns true if the mesh should render, otherwise false.
  89764. * @param mesh The mesh to render
  89765. * @returns true if it should render otherwise false
  89766. */
  89767. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  89768. return this.hasMesh(mesh);
  89769. };
  89770. /**
  89771. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  89772. * @param mesh The mesh to exclude from the glow layer
  89773. */
  89774. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  89775. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  89776. this._excludedMeshes.push(mesh.uniqueId);
  89777. }
  89778. };
  89779. /**
  89780. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  89781. * @param mesh The mesh to remove
  89782. */
  89783. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  89784. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  89785. if (index !== -1) {
  89786. this._excludedMeshes.splice(index, 1);
  89787. }
  89788. };
  89789. /**
  89790. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  89791. * @param mesh The mesh to include in the glow layer
  89792. */
  89793. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  89794. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  89795. this._includedOnlyMeshes.push(mesh.uniqueId);
  89796. }
  89797. };
  89798. /**
  89799. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  89800. * @param mesh The mesh to remove
  89801. */
  89802. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  89803. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  89804. if (index !== -1) {
  89805. this._includedOnlyMeshes.splice(index, 1);
  89806. }
  89807. };
  89808. /**
  89809. * Determine if a given mesh will be used in the glow layer
  89810. * @param mesh The mesh to test
  89811. * @returns true if the mesh will be highlighted by the current glow layer
  89812. */
  89813. GlowLayer.prototype.hasMesh = function (mesh) {
  89814. // Included Mesh
  89815. if (this._includedOnlyMeshes.length) {
  89816. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  89817. }
  89818. ;
  89819. // Excluded Mesh
  89820. if (this._excludedMeshes.length) {
  89821. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  89822. }
  89823. ;
  89824. return true;
  89825. };
  89826. /**
  89827. * Free any resources and references associated to a mesh.
  89828. * Internal use
  89829. * @param mesh The mesh to free.
  89830. */
  89831. GlowLayer.prototype._disposeMesh = function (mesh) {
  89832. this.removeIncludedOnlyMesh(mesh);
  89833. this.removeExcludedMesh(mesh);
  89834. };
  89835. /**
  89836. * Gets the class name of the effect layer
  89837. * @returns the string with the class name of the effect layer
  89838. */
  89839. GlowLayer.prototype.getClassName = function () {
  89840. return "GlowLayer";
  89841. };
  89842. /**
  89843. * Serializes this glow layer
  89844. * @returns a serialized glow layer object
  89845. */
  89846. GlowLayer.prototype.serialize = function () {
  89847. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89848. var index;
  89849. // Included meshes
  89850. serializationObject.includedMeshes = [];
  89851. if (this._includedOnlyMeshes.length) {
  89852. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  89853. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  89854. if (mesh) {
  89855. serializationObject.includedMeshes.push(mesh.id);
  89856. }
  89857. }
  89858. }
  89859. // Excluded meshes
  89860. serializationObject.excludedMeshes = [];
  89861. if (this._excludedMeshes.length) {
  89862. for (index = 0; index < this._excludedMeshes.length; index++) {
  89863. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  89864. if (mesh) {
  89865. serializationObject.excludedMeshes.push(mesh.id);
  89866. }
  89867. }
  89868. }
  89869. return serializationObject;
  89870. };
  89871. /**
  89872. * Creates a Glow Layer from parsed glow layer data
  89873. * @param parsedGlowLayer defines glow layer data
  89874. * @param scene defines the current scene
  89875. * @param rootUrl defines the root URL containing the glow layer information
  89876. * @returns a parsed Glow Layer
  89877. */
  89878. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  89879. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  89880. var index;
  89881. // Excluded meshes
  89882. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  89883. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  89884. if (mesh) {
  89885. gl.addExcludedMesh(mesh);
  89886. }
  89887. }
  89888. // Included meshes
  89889. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  89890. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  89891. if (mesh) {
  89892. gl.addIncludedOnlyMesh(mesh);
  89893. }
  89894. }
  89895. return gl;
  89896. };
  89897. /**
  89898. * Effect Name of the layer.
  89899. */
  89900. GlowLayer.EffectName = "GlowLayer";
  89901. /**
  89902. * The default blur kernel size used for the glow.
  89903. */
  89904. GlowLayer.DefaultBlurKernelSize = 32;
  89905. /**
  89906. * The default texture size ratio used for the glow.
  89907. */
  89908. GlowLayer.DefaultTextureRatio = 0.5;
  89909. __decorate([
  89910. BABYLON.serialize()
  89911. ], GlowLayer.prototype, "blurKernelSize", null);
  89912. __decorate([
  89913. BABYLON.serialize()
  89914. ], GlowLayer.prototype, "intensity", null);
  89915. __decorate([
  89916. BABYLON.serialize('options')
  89917. ], GlowLayer.prototype, "_options", void 0);
  89918. return GlowLayer;
  89919. }(BABYLON.EffectLayer));
  89920. BABYLON.GlowLayer = GlowLayer;
  89921. })(BABYLON || (BABYLON = {}));
  89922. //# sourceMappingURL=babylon.glowLayer.js.map
  89923. "use strict";
  89924. var BABYLON;
  89925. (function (BABYLON) {
  89926. /**
  89927. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  89928. */
  89929. var AssetTaskState;
  89930. (function (AssetTaskState) {
  89931. /**
  89932. * Initialization
  89933. */
  89934. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  89935. /**
  89936. * Running
  89937. */
  89938. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  89939. /**
  89940. * Done
  89941. */
  89942. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  89943. /**
  89944. * Error
  89945. */
  89946. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  89947. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  89948. /**
  89949. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  89950. */
  89951. var AbstractAssetTask = /** @class */ (function () {
  89952. /**
  89953. * Creates a new {BABYLON.AssetsManager}
  89954. * @param name defines the name of the task
  89955. */
  89956. function AbstractAssetTask(
  89957. /**
  89958. * Task name
  89959. */ name) {
  89960. this.name = name;
  89961. this._isCompleted = false;
  89962. this._taskState = AssetTaskState.INIT;
  89963. }
  89964. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  89965. /**
  89966. * Get if the task is completed
  89967. */
  89968. get: function () {
  89969. return this._isCompleted;
  89970. },
  89971. enumerable: true,
  89972. configurable: true
  89973. });
  89974. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  89975. /**
  89976. * Gets the current state of the task
  89977. */
  89978. get: function () {
  89979. return this._taskState;
  89980. },
  89981. enumerable: true,
  89982. configurable: true
  89983. });
  89984. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  89985. /**
  89986. * Gets the current error object (if task is in error)
  89987. */
  89988. get: function () {
  89989. return this._errorObject;
  89990. },
  89991. enumerable: true,
  89992. configurable: true
  89993. });
  89994. /**
  89995. * Internal only
  89996. * @ignore
  89997. */
  89998. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  89999. if (this._errorObject) {
  90000. return;
  90001. }
  90002. this._errorObject = {
  90003. message: message,
  90004. exception: exception
  90005. };
  90006. };
  90007. /**
  90008. * Execute the current task
  90009. * @param scene defines the scene where you want your assets to be loaded
  90010. * @param onSuccess is a callback called when the task is successfully executed
  90011. * @param onError is a callback called if an error occurs
  90012. */
  90013. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  90014. var _this = this;
  90015. this._taskState = AssetTaskState.RUNNING;
  90016. this.runTask(scene, function () {
  90017. _this.onDoneCallback(onSuccess, onError);
  90018. }, function (msg, exception) {
  90019. _this.onErrorCallback(onError, msg, exception);
  90020. });
  90021. };
  90022. /**
  90023. * Execute the current task
  90024. * @param scene defines the scene where you want your assets to be loaded
  90025. * @param onSuccess is a callback called when the task is successfully executed
  90026. * @param onError is a callback called if an error occurs
  90027. */
  90028. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90029. throw new Error("runTask is not implemented");
  90030. };
  90031. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  90032. this._taskState = AssetTaskState.ERROR;
  90033. this._errorObject = {
  90034. message: message,
  90035. exception: exception
  90036. };
  90037. if (this.onError) {
  90038. this.onError(this, message, exception);
  90039. }
  90040. onError();
  90041. };
  90042. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  90043. try {
  90044. this._taskState = AssetTaskState.DONE;
  90045. this._isCompleted = true;
  90046. if (this.onSuccess) {
  90047. this.onSuccess(this);
  90048. }
  90049. onSuccess();
  90050. }
  90051. catch (e) {
  90052. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  90053. }
  90054. };
  90055. return AbstractAssetTask;
  90056. }());
  90057. BABYLON.AbstractAssetTask = AbstractAssetTask;
  90058. /**
  90059. * Class used to share progress information about assets loading
  90060. */
  90061. var AssetsProgressEvent = /** @class */ (function () {
  90062. /**
  90063. * Creates a {BABYLON.AssetsProgressEvent}
  90064. * @param remainingCount defines the number of remaining tasks to process
  90065. * @param totalCount defines the total number of tasks
  90066. * @param task defines the task that was just processed
  90067. */
  90068. function AssetsProgressEvent(remainingCount, totalCount, task) {
  90069. this.remainingCount = remainingCount;
  90070. this.totalCount = totalCount;
  90071. this.task = task;
  90072. }
  90073. return AssetsProgressEvent;
  90074. }());
  90075. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  90076. /**
  90077. * Define a task used by {BABYLON.AssetsManager} to load meshes
  90078. */
  90079. var MeshAssetTask = /** @class */ (function (_super) {
  90080. __extends(MeshAssetTask, _super);
  90081. /**
  90082. * Creates a new {BABYLON.MeshAssetTask}
  90083. * @param name defines the name of the task
  90084. * @param meshesNames defines the list of mesh's names you want to load
  90085. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  90086. * @param sceneFilename defines the filename of the scene to load from
  90087. */
  90088. function MeshAssetTask(
  90089. /**
  90090. * Defines the name of the task
  90091. */
  90092. name,
  90093. /**
  90094. * Defines the list of mesh's names you want to load
  90095. */
  90096. meshesNames,
  90097. /**
  90098. * Defines the root url to use as a base to load your meshes and associated resources
  90099. */
  90100. rootUrl,
  90101. /**
  90102. * Defines the filename of the scene to load from
  90103. */
  90104. sceneFilename) {
  90105. var _this = _super.call(this, name) || this;
  90106. _this.name = name;
  90107. _this.meshesNames = meshesNames;
  90108. _this.rootUrl = rootUrl;
  90109. _this.sceneFilename = sceneFilename;
  90110. return _this;
  90111. }
  90112. /**
  90113. * Execute the current task
  90114. * @param scene defines the scene where you want your assets to be loaded
  90115. * @param onSuccess is a callback called when the task is successfully executed
  90116. * @param onError is a callback called if an error occurs
  90117. */
  90118. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90119. var _this = this;
  90120. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  90121. _this.loadedMeshes = meshes;
  90122. _this.loadedParticleSystems = particleSystems;
  90123. _this.loadedSkeletons = skeletons;
  90124. onSuccess();
  90125. }, null, function (scene, message, exception) {
  90126. onError(message, exception);
  90127. });
  90128. };
  90129. return MeshAssetTask;
  90130. }(AbstractAssetTask));
  90131. BABYLON.MeshAssetTask = MeshAssetTask;
  90132. /**
  90133. * Define a task used by {BABYLON.AssetsManager} to load text content
  90134. */
  90135. var TextFileAssetTask = /** @class */ (function (_super) {
  90136. __extends(TextFileAssetTask, _super);
  90137. /**
  90138. * Creates a new TextFileAssetTask object
  90139. * @param name defines the name of the task
  90140. * @param url defines the location of the file to load
  90141. */
  90142. function TextFileAssetTask(
  90143. /**
  90144. * Defines the name of the task
  90145. */
  90146. name,
  90147. /**
  90148. * Defines the location of the file to load
  90149. */
  90150. url) {
  90151. var _this = _super.call(this, name) || this;
  90152. _this.name = name;
  90153. _this.url = url;
  90154. return _this;
  90155. }
  90156. /**
  90157. * Execute the current task
  90158. * @param scene defines the scene where you want your assets to be loaded
  90159. * @param onSuccess is a callback called when the task is successfully executed
  90160. * @param onError is a callback called if an error occurs
  90161. */
  90162. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90163. var _this = this;
  90164. scene._loadFile(this.url, function (data) {
  90165. _this.text = data;
  90166. onSuccess();
  90167. }, undefined, false, false, function (request, exception) {
  90168. if (request) {
  90169. onError(request.status + " " + request.statusText, exception);
  90170. }
  90171. });
  90172. };
  90173. return TextFileAssetTask;
  90174. }(AbstractAssetTask));
  90175. BABYLON.TextFileAssetTask = TextFileAssetTask;
  90176. /**
  90177. * Define a task used by {BABYLON.AssetsManager} to load binary data
  90178. */
  90179. var BinaryFileAssetTask = /** @class */ (function (_super) {
  90180. __extends(BinaryFileAssetTask, _super);
  90181. /**
  90182. * Creates a new BinaryFileAssetTask object
  90183. * @param name defines the name of the new task
  90184. * @param url defines the location of the file to load
  90185. */
  90186. function BinaryFileAssetTask(
  90187. /**
  90188. * Defines the name of the task
  90189. */
  90190. name,
  90191. /**
  90192. * Defines the location of the file to load
  90193. */
  90194. url) {
  90195. var _this = _super.call(this, name) || this;
  90196. _this.name = name;
  90197. _this.url = url;
  90198. return _this;
  90199. }
  90200. /**
  90201. * Execute the current task
  90202. * @param scene defines the scene where you want your assets to be loaded
  90203. * @param onSuccess is a callback called when the task is successfully executed
  90204. * @param onError is a callback called if an error occurs
  90205. */
  90206. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90207. var _this = this;
  90208. scene._loadFile(this.url, function (data) {
  90209. _this.data = data;
  90210. onSuccess();
  90211. }, undefined, true, true, function (request, exception) {
  90212. if (request) {
  90213. onError(request.status + " " + request.statusText, exception);
  90214. }
  90215. });
  90216. };
  90217. return BinaryFileAssetTask;
  90218. }(AbstractAssetTask));
  90219. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  90220. /**
  90221. * Define a task used by {BABYLON.AssetsManager} to load images
  90222. */
  90223. var ImageAssetTask = /** @class */ (function (_super) {
  90224. __extends(ImageAssetTask, _super);
  90225. /**
  90226. * Creates a new ImageAssetTask
  90227. * @param name defines the name of the task
  90228. * @param url defines the location of the image to load
  90229. */
  90230. function ImageAssetTask(
  90231. /**
  90232. * Defines the name of the task
  90233. */
  90234. name,
  90235. /**
  90236. * Defines the location of the image to load
  90237. */
  90238. url) {
  90239. var _this = _super.call(this, name) || this;
  90240. _this.name = name;
  90241. _this.url = url;
  90242. return _this;
  90243. }
  90244. /**
  90245. * Execute the current task
  90246. * @param scene defines the scene where you want your assets to be loaded
  90247. * @param onSuccess is a callback called when the task is successfully executed
  90248. * @param onError is a callback called if an error occurs
  90249. */
  90250. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90251. var _this = this;
  90252. var img = new Image();
  90253. BABYLON.Tools.SetCorsBehavior(this.url, img);
  90254. img.onload = function () {
  90255. _this.image = img;
  90256. onSuccess();
  90257. };
  90258. img.onerror = function (err) {
  90259. onError("Error loading image", err);
  90260. };
  90261. img.src = this.url;
  90262. };
  90263. return ImageAssetTask;
  90264. }(AbstractAssetTask));
  90265. BABYLON.ImageAssetTask = ImageAssetTask;
  90266. /**
  90267. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  90268. */
  90269. var TextureAssetTask = /** @class */ (function (_super) {
  90270. __extends(TextureAssetTask, _super);
  90271. /**
  90272. * Creates a new TextureAssetTask object
  90273. * @param name defines the name of the task
  90274. * @param url defines the location of the file to load
  90275. * @param noMipmap defines if mipmap should not be generated (default is false)
  90276. * @param invertY defines if texture must be inverted on Y axis (default is false)
  90277. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90278. */
  90279. function TextureAssetTask(
  90280. /**
  90281. * Defines the name of the task
  90282. */
  90283. name,
  90284. /**
  90285. * Defines the location of the file to load
  90286. */
  90287. url,
  90288. /**
  90289. * Defines if mipmap should not be generated (default is false)
  90290. */
  90291. noMipmap,
  90292. /**
  90293. * Defines if texture must be inverted on Y axis (default is false)
  90294. */
  90295. invertY,
  90296. /**
  90297. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90298. */
  90299. samplingMode) {
  90300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90301. var _this = _super.call(this, name) || this;
  90302. _this.name = name;
  90303. _this.url = url;
  90304. _this.noMipmap = noMipmap;
  90305. _this.invertY = invertY;
  90306. _this.samplingMode = samplingMode;
  90307. return _this;
  90308. }
  90309. /**
  90310. * Execute the current task
  90311. * @param scene defines the scene where you want your assets to be loaded
  90312. * @param onSuccess is a callback called when the task is successfully executed
  90313. * @param onError is a callback called if an error occurs
  90314. */
  90315. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90316. var onload = function () {
  90317. onSuccess();
  90318. };
  90319. var onerror = function (message, exception) {
  90320. onError(message, exception);
  90321. };
  90322. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  90323. };
  90324. return TextureAssetTask;
  90325. }(AbstractAssetTask));
  90326. BABYLON.TextureAssetTask = TextureAssetTask;
  90327. /**
  90328. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  90329. */
  90330. var CubeTextureAssetTask = /** @class */ (function (_super) {
  90331. __extends(CubeTextureAssetTask, _super);
  90332. /**
  90333. * Creates a new CubeTextureAssetTask
  90334. * @param name defines the name of the task
  90335. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90336. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90337. * @param noMipmap defines if mipmaps should not be generated (default is false)
  90338. * @param files defines the explicit list of files (undefined by default)
  90339. */
  90340. function CubeTextureAssetTask(
  90341. /**
  90342. * Defines the name of the task
  90343. */
  90344. name,
  90345. /**
  90346. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90347. */
  90348. url,
  90349. /**
  90350. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90351. */
  90352. extensions,
  90353. /**
  90354. * Defines if mipmaps should not be generated (default is false)
  90355. */
  90356. noMipmap,
  90357. /**
  90358. * Defines the explicit list of files (undefined by default)
  90359. */
  90360. files) {
  90361. var _this = _super.call(this, name) || this;
  90362. _this.name = name;
  90363. _this.url = url;
  90364. _this.extensions = extensions;
  90365. _this.noMipmap = noMipmap;
  90366. _this.files = files;
  90367. return _this;
  90368. }
  90369. /**
  90370. * Execute the current task
  90371. * @param scene defines the scene where you want your assets to be loaded
  90372. * @param onSuccess is a callback called when the task is successfully executed
  90373. * @param onError is a callback called if an error occurs
  90374. */
  90375. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90376. var onload = function () {
  90377. onSuccess();
  90378. };
  90379. var onerror = function (message, exception) {
  90380. onError(message, exception);
  90381. };
  90382. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  90383. };
  90384. return CubeTextureAssetTask;
  90385. }(AbstractAssetTask));
  90386. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  90387. /**
  90388. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  90389. */
  90390. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  90391. __extends(HDRCubeTextureAssetTask, _super);
  90392. /**
  90393. * Creates a new HDRCubeTextureAssetTask object
  90394. * @param name defines the name of the task
  90395. * @param url defines the location of the file to load
  90396. * @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.
  90397. * @param noMipmap defines if mipmaps should not be generated (default is false)
  90398. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  90399. * @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)
  90400. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  90401. */
  90402. function HDRCubeTextureAssetTask(
  90403. /**
  90404. * Defines the name of the task
  90405. */
  90406. name,
  90407. /**
  90408. * Defines the location of the file to load
  90409. */
  90410. url,
  90411. /**
  90412. * 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.
  90413. */
  90414. size,
  90415. /**
  90416. * Defines if mipmaps should not be generated (default is false)
  90417. */
  90418. noMipmap,
  90419. /**
  90420. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  90421. */
  90422. generateHarmonics,
  90423. /**
  90424. * 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)
  90425. */
  90426. useInGammaSpace,
  90427. /**
  90428. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  90429. */
  90430. usePMREMGenerator) {
  90431. if (noMipmap === void 0) { noMipmap = false; }
  90432. if (generateHarmonics === void 0) { generateHarmonics = true; }
  90433. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  90434. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  90435. var _this = _super.call(this, name) || this;
  90436. _this.name = name;
  90437. _this.url = url;
  90438. _this.size = size;
  90439. _this.noMipmap = noMipmap;
  90440. _this.generateHarmonics = generateHarmonics;
  90441. _this.useInGammaSpace = useInGammaSpace;
  90442. _this.usePMREMGenerator = usePMREMGenerator;
  90443. return _this;
  90444. }
  90445. /**
  90446. * Execute the current task
  90447. * @param scene defines the scene where you want your assets to be loaded
  90448. * @param onSuccess is a callback called when the task is successfully executed
  90449. * @param onError is a callback called if an error occurs
  90450. */
  90451. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  90452. var onload = function () {
  90453. onSuccess();
  90454. };
  90455. var onerror = function (message, exception) {
  90456. onError(message, exception);
  90457. };
  90458. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  90459. };
  90460. return HDRCubeTextureAssetTask;
  90461. }(AbstractAssetTask));
  90462. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  90463. /**
  90464. * This class can be used to easily import assets into a scene
  90465. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  90466. */
  90467. var AssetsManager = /** @class */ (function () {
  90468. /**
  90469. * Creates a new AssetsManager
  90470. * @param scene defines the scene to work on
  90471. */
  90472. function AssetsManager(scene) {
  90473. this._isLoading = false;
  90474. this._tasks = new Array();
  90475. this._waitingTasksCount = 0;
  90476. this._totalTasksCount = 0;
  90477. /**
  90478. * Observable called when all tasks are processed
  90479. */
  90480. this.onTaskSuccessObservable = new BABYLON.Observable();
  90481. /**
  90482. * Observable called when a task had an error
  90483. */
  90484. this.onTaskErrorObservable = new BABYLON.Observable();
  90485. /**
  90486. * Observable called when a task is successful
  90487. */
  90488. this.onTasksDoneObservable = new BABYLON.Observable();
  90489. /**
  90490. * Observable called when a task is done (whatever the result is)
  90491. */
  90492. this.onProgressObservable = new BABYLON.Observable();
  90493. /**
  90494. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  90495. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  90496. */
  90497. this.useDefaultLoadingScreen = true;
  90498. this._scene = scene;
  90499. }
  90500. /**
  90501. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  90502. * @param taskName defines the name of the new task
  90503. * @param meshesNames defines the name of meshes to load
  90504. * @param rootUrl defines the root url to use to locate files
  90505. * @param sceneFilename defines the filename of the scene file
  90506. * @returns a new {BABYLON.MeshAssetTask} object
  90507. */
  90508. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  90509. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  90510. this._tasks.push(task);
  90511. return task;
  90512. };
  90513. /**
  90514. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  90515. * @param taskName defines the name of the new task
  90516. * @param url defines the url of the file to load
  90517. * @returns a new {BABYLON.TextFileAssetTask} object
  90518. */
  90519. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  90520. var task = new TextFileAssetTask(taskName, url);
  90521. this._tasks.push(task);
  90522. return task;
  90523. };
  90524. /**
  90525. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  90526. * @param taskName defines the name of the new task
  90527. * @param url defines the url of the file to load
  90528. * @returns a new {BABYLON.BinaryFileAssetTask} object
  90529. */
  90530. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  90531. var task = new BinaryFileAssetTask(taskName, url);
  90532. this._tasks.push(task);
  90533. return task;
  90534. };
  90535. /**
  90536. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  90537. * @param taskName defines the name of the new task
  90538. * @param url defines the url of the file to load
  90539. * @returns a new {BABYLON.ImageAssetTask} object
  90540. */
  90541. AssetsManager.prototype.addImageTask = function (taskName, url) {
  90542. var task = new ImageAssetTask(taskName, url);
  90543. this._tasks.push(task);
  90544. return task;
  90545. };
  90546. /**
  90547. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  90548. * @param taskName defines the name of the new task
  90549. * @param url defines the url of the file to load
  90550. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90551. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  90552. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  90553. * @returns a new {BABYLON.TextureAssetTask} object
  90554. */
  90555. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  90556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90557. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  90558. this._tasks.push(task);
  90559. return task;
  90560. };
  90561. /**
  90562. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  90563. * @param taskName defines the name of the new task
  90564. * @param url defines the url of the file to load
  90565. * @param extensions defines the extension to use to load the cube map (can be null)
  90566. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90567. * @param files defines the list of files to load (can be null)
  90568. * @returns a new {BABYLON.CubeTextureAssetTask} object
  90569. */
  90570. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  90571. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  90572. this._tasks.push(task);
  90573. return task;
  90574. };
  90575. /**
  90576. *
  90577. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  90578. * @param taskName defines the name of the new task
  90579. * @param url defines the url of the file to load
  90580. * @param size defines the size you want for the cubemap (can be null)
  90581. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  90582. * @param generateHarmonics defines if you want to automatically generate (true by default)
  90583. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  90584. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  90585. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  90586. */
  90587. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  90588. if (noMipmap === void 0) { noMipmap = false; }
  90589. if (generateHarmonics === void 0) { generateHarmonics = true; }
  90590. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  90591. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  90592. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  90593. this._tasks.push(task);
  90594. return task;
  90595. };
  90596. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  90597. var _this = this;
  90598. this._waitingTasksCount--;
  90599. try {
  90600. if (task.taskState === AssetTaskState.DONE) {
  90601. // Let's remove successfull tasks
  90602. BABYLON.Tools.SetImmediate(function () {
  90603. var index = _this._tasks.indexOf(task);
  90604. if (index > -1) {
  90605. _this._tasks.splice(index, 1);
  90606. }
  90607. });
  90608. }
  90609. if (this.onProgress) {
  90610. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  90611. }
  90612. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  90613. }
  90614. catch (e) {
  90615. BABYLON.Tools.Error("Error running progress callbacks.");
  90616. console.log(e);
  90617. }
  90618. if (this._waitingTasksCount === 0) {
  90619. try {
  90620. if (this.onFinish) {
  90621. this.onFinish(this._tasks);
  90622. }
  90623. this.onTasksDoneObservable.notifyObservers(this._tasks);
  90624. }
  90625. catch (e) {
  90626. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  90627. console.log(e);
  90628. }
  90629. this._isLoading = false;
  90630. this._scene.getEngine().hideLoadingUI();
  90631. }
  90632. };
  90633. AssetsManager.prototype._runTask = function (task) {
  90634. var _this = this;
  90635. var done = function () {
  90636. try {
  90637. if (_this.onTaskSuccess) {
  90638. _this.onTaskSuccess(task);
  90639. }
  90640. _this.onTaskSuccessObservable.notifyObservers(task);
  90641. _this._decreaseWaitingTasksCount(task);
  90642. }
  90643. catch (e) {
  90644. error("Error executing task success callbacks", e);
  90645. }
  90646. };
  90647. var error = function (message, exception) {
  90648. task._setErrorObject(message, exception);
  90649. if (_this.onTaskError) {
  90650. _this.onTaskError(task);
  90651. }
  90652. _this.onTaskErrorObservable.notifyObservers(task);
  90653. _this._decreaseWaitingTasksCount(task);
  90654. };
  90655. task.run(this._scene, done, error);
  90656. };
  90657. /**
  90658. * Reset the {BABYLON.AssetsManager} and remove all tasks
  90659. * @return the current instance of the {BABYLON.AssetsManager}
  90660. */
  90661. AssetsManager.prototype.reset = function () {
  90662. this._isLoading = false;
  90663. this._tasks = new Array();
  90664. return this;
  90665. };
  90666. /**
  90667. * Start the loading process
  90668. * @return the current instance of the {BABYLON.AssetsManager}
  90669. */
  90670. AssetsManager.prototype.load = function () {
  90671. if (this._isLoading) {
  90672. return this;
  90673. }
  90674. this._isLoading = true;
  90675. this._waitingTasksCount = this._tasks.length;
  90676. this._totalTasksCount = this._tasks.length;
  90677. if (this._waitingTasksCount === 0) {
  90678. this._isLoading = false;
  90679. if (this.onFinish) {
  90680. this.onFinish(this._tasks);
  90681. }
  90682. this.onTasksDoneObservable.notifyObservers(this._tasks);
  90683. return this;
  90684. }
  90685. if (this.useDefaultLoadingScreen) {
  90686. this._scene.getEngine().displayLoadingUI();
  90687. }
  90688. for (var index = 0; index < this._tasks.length; index++) {
  90689. var task = this._tasks[index];
  90690. this._runTask(task);
  90691. }
  90692. return this;
  90693. };
  90694. return AssetsManager;
  90695. }());
  90696. BABYLON.AssetsManager = AssetsManager;
  90697. })(BABYLON || (BABYLON = {}));
  90698. //# sourceMappingURL=babylon.assetsManager.js.map
  90699. "use strict";
  90700. var BABYLON;
  90701. (function (BABYLON) {
  90702. var serializedGeometries = [];
  90703. var serializeGeometry = function (geometry, serializationGeometries) {
  90704. if (serializedGeometries[geometry.id]) {
  90705. return;
  90706. }
  90707. if (geometry.doNotSerialize) {
  90708. return;
  90709. }
  90710. if (geometry instanceof BABYLON.BoxGeometry) {
  90711. serializationGeometries.boxes.push(geometry.serialize());
  90712. }
  90713. else if (geometry instanceof BABYLON.SphereGeometry) {
  90714. serializationGeometries.spheres.push(geometry.serialize());
  90715. }
  90716. else if (geometry instanceof BABYLON.CylinderGeometry) {
  90717. serializationGeometries.cylinders.push(geometry.serialize());
  90718. }
  90719. else if (geometry instanceof BABYLON.TorusGeometry) {
  90720. serializationGeometries.toruses.push(geometry.serialize());
  90721. }
  90722. else if (geometry instanceof BABYLON.GroundGeometry) {
  90723. serializationGeometries.grounds.push(geometry.serialize());
  90724. }
  90725. else if (geometry instanceof BABYLON.Plane) {
  90726. serializationGeometries.planes.push(geometry.serialize());
  90727. }
  90728. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  90729. serializationGeometries.torusKnots.push(geometry.serialize());
  90730. }
  90731. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  90732. throw new Error("Unknown primitive type");
  90733. }
  90734. else {
  90735. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  90736. }
  90737. serializedGeometries[geometry.id] = true;
  90738. };
  90739. var serializeMesh = function (mesh, serializationScene) {
  90740. var serializationObject = {};
  90741. // Geometry
  90742. var geometry = mesh._geometry;
  90743. if (geometry) {
  90744. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  90745. // 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
  90746. serializeGeometry(geometry, serializationScene.geometries);
  90747. }
  90748. }
  90749. // Custom
  90750. if (mesh.serialize) {
  90751. mesh.serialize(serializationObject);
  90752. }
  90753. return serializationObject;
  90754. };
  90755. var finalizeSingleMesh = function (mesh, serializationObject) {
  90756. //only works if the mesh is already loaded
  90757. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  90758. //serialize material
  90759. if (mesh.material) {
  90760. if (mesh.material instanceof BABYLON.StandardMaterial) {
  90761. serializationObject.materials = serializationObject.materials || [];
  90762. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  90763. serializationObject.materials.push(mesh.material.serialize());
  90764. }
  90765. }
  90766. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  90767. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  90768. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  90769. serializationObject.multiMaterials.push(mesh.material.serialize());
  90770. }
  90771. }
  90772. }
  90773. //serialize geometry
  90774. var geometry = mesh._geometry;
  90775. if (geometry) {
  90776. if (!serializationObject.geometries) {
  90777. serializationObject.geometries = {};
  90778. serializationObject.geometries.boxes = [];
  90779. serializationObject.geometries.spheres = [];
  90780. serializationObject.geometries.cylinders = [];
  90781. serializationObject.geometries.toruses = [];
  90782. serializationObject.geometries.grounds = [];
  90783. serializationObject.geometries.planes = [];
  90784. serializationObject.geometries.torusKnots = [];
  90785. serializationObject.geometries.vertexData = [];
  90786. }
  90787. serializeGeometry(geometry, serializationObject.geometries);
  90788. }
  90789. // Skeletons
  90790. if (mesh.skeleton) {
  90791. serializationObject.skeletons = serializationObject.skeletons || [];
  90792. serializationObject.skeletons.push(mesh.skeleton.serialize());
  90793. }
  90794. //serialize the actual mesh
  90795. serializationObject.meshes = serializationObject.meshes || [];
  90796. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  90797. }
  90798. };
  90799. var SceneSerializer = /** @class */ (function () {
  90800. function SceneSerializer() {
  90801. }
  90802. SceneSerializer.ClearCache = function () {
  90803. serializedGeometries = [];
  90804. };
  90805. SceneSerializer.Serialize = function (scene) {
  90806. var serializationObject = {};
  90807. SceneSerializer.ClearCache();
  90808. // Scene
  90809. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  90810. serializationObject.autoClear = scene.autoClear;
  90811. serializationObject.clearColor = scene.clearColor.asArray();
  90812. serializationObject.ambientColor = scene.ambientColor.asArray();
  90813. serializationObject.gravity = scene.gravity.asArray();
  90814. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  90815. serializationObject.workerCollisions = scene.workerCollisions;
  90816. // Fog
  90817. if (scene.fogMode && scene.fogMode !== 0) {
  90818. serializationObject.fogMode = scene.fogMode;
  90819. serializationObject.fogColor = scene.fogColor.asArray();
  90820. serializationObject.fogStart = scene.fogStart;
  90821. serializationObject.fogEnd = scene.fogEnd;
  90822. serializationObject.fogDensity = scene.fogDensity;
  90823. }
  90824. //Physics
  90825. if (scene.isPhysicsEnabled()) {
  90826. var physicEngine = scene.getPhysicsEngine();
  90827. if (physicEngine) {
  90828. serializationObject.physicsEnabled = true;
  90829. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  90830. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  90831. }
  90832. }
  90833. // Metadata
  90834. if (scene.metadata) {
  90835. serializationObject.metadata = scene.metadata;
  90836. }
  90837. // Morph targets
  90838. serializationObject.morphTargetManagers = [];
  90839. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  90840. var abstractMesh = _a[_i];
  90841. var manager = abstractMesh.morphTargetManager;
  90842. if (manager) {
  90843. serializationObject.morphTargetManagers.push(manager.serialize());
  90844. }
  90845. }
  90846. // Lights
  90847. serializationObject.lights = [];
  90848. var index;
  90849. var light;
  90850. for (index = 0; index < scene.lights.length; index++) {
  90851. light = scene.lights[index];
  90852. if (!light.doNotSerialize) {
  90853. serializationObject.lights.push(light.serialize());
  90854. }
  90855. }
  90856. // Cameras
  90857. serializationObject.cameras = [];
  90858. for (index = 0; index < scene.cameras.length; index++) {
  90859. var camera = scene.cameras[index];
  90860. if (!camera.doNotSerialize) {
  90861. serializationObject.cameras.push(camera.serialize());
  90862. }
  90863. }
  90864. if (scene.activeCamera) {
  90865. serializationObject.activeCameraID = scene.activeCamera.id;
  90866. }
  90867. // Animations
  90868. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  90869. // Materials
  90870. serializationObject.materials = [];
  90871. serializationObject.multiMaterials = [];
  90872. var material;
  90873. for (index = 0; index < scene.materials.length; index++) {
  90874. material = scene.materials[index];
  90875. if (!material.doNotSerialize) {
  90876. serializationObject.materials.push(material.serialize());
  90877. }
  90878. }
  90879. // MultiMaterials
  90880. serializationObject.multiMaterials = [];
  90881. for (index = 0; index < scene.multiMaterials.length; index++) {
  90882. var multiMaterial = scene.multiMaterials[index];
  90883. serializationObject.multiMaterials.push(multiMaterial.serialize());
  90884. }
  90885. // Environment texture
  90886. if (scene.environmentTexture) {
  90887. serializationObject.environmentTexture = scene.environmentTexture.name;
  90888. }
  90889. // Skeletons
  90890. serializationObject.skeletons = [];
  90891. for (index = 0; index < scene.skeletons.length; index++) {
  90892. var skeleton = scene.skeletons[index];
  90893. if (!skeleton.doNotSerialize) {
  90894. serializationObject.skeletons.push(skeleton.serialize());
  90895. }
  90896. }
  90897. // Transform nodes
  90898. serializationObject.transformNodes = [];
  90899. for (index = 0; index < scene.transformNodes.length; index++) {
  90900. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  90901. }
  90902. // Geometries
  90903. serializationObject.geometries = {};
  90904. serializationObject.geometries.boxes = [];
  90905. serializationObject.geometries.spheres = [];
  90906. serializationObject.geometries.cylinders = [];
  90907. serializationObject.geometries.toruses = [];
  90908. serializationObject.geometries.grounds = [];
  90909. serializationObject.geometries.planes = [];
  90910. serializationObject.geometries.torusKnots = [];
  90911. serializationObject.geometries.vertexData = [];
  90912. serializedGeometries = [];
  90913. var geometries = scene.getGeometries();
  90914. for (index = 0; index < geometries.length; index++) {
  90915. var geometry = geometries[index];
  90916. if (geometry.isReady()) {
  90917. serializeGeometry(geometry, serializationObject.geometries);
  90918. }
  90919. }
  90920. // Meshes
  90921. serializationObject.meshes = [];
  90922. for (index = 0; index < scene.meshes.length; index++) {
  90923. var abstractMesh = scene.meshes[index];
  90924. if (abstractMesh instanceof BABYLON.Mesh) {
  90925. var mesh = abstractMesh;
  90926. if (!mesh.doNotSerialize) {
  90927. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  90928. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  90929. }
  90930. }
  90931. }
  90932. }
  90933. // Particles Systems
  90934. serializationObject.particleSystems = [];
  90935. for (index = 0; index < scene.particleSystems.length; index++) {
  90936. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  90937. }
  90938. // Lens flares
  90939. serializationObject.lensFlareSystems = [];
  90940. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  90941. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  90942. }
  90943. // Shadows
  90944. serializationObject.shadowGenerators = [];
  90945. for (index = 0; index < scene.lights.length; index++) {
  90946. light = scene.lights[index];
  90947. var shadowGenerator = light.getShadowGenerator();
  90948. if (shadowGenerator) {
  90949. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  90950. }
  90951. }
  90952. // Action Manager
  90953. if (scene.actionManager) {
  90954. serializationObject.actions = scene.actionManager.serialize("scene");
  90955. }
  90956. // Audio
  90957. serializationObject.sounds = [];
  90958. for (index = 0; index < scene.soundTracks.length; index++) {
  90959. var soundtrack = scene.soundTracks[index];
  90960. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  90961. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  90962. }
  90963. }
  90964. return serializationObject;
  90965. };
  90966. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  90967. if (withParents === void 0) { withParents = false; }
  90968. if (withChildren === void 0) { withChildren = false; }
  90969. var serializationObject = {};
  90970. SceneSerializer.ClearCache();
  90971. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  90972. if (withParents || withChildren) {
  90973. //deliberate for loop! not for each, appended should be processed as well.
  90974. for (var i = 0; i < toSerialize.length; ++i) {
  90975. if (withChildren) {
  90976. toSerialize[i].getDescendants().forEach(function (node) {
  90977. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  90978. toSerialize.push(node);
  90979. }
  90980. });
  90981. }
  90982. //make sure the array doesn't contain the object already
  90983. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  90984. toSerialize.push(toSerialize[i].parent);
  90985. }
  90986. }
  90987. }
  90988. toSerialize.forEach(function (mesh) {
  90989. finalizeSingleMesh(mesh, serializationObject);
  90990. });
  90991. return serializationObject;
  90992. };
  90993. return SceneSerializer;
  90994. }());
  90995. BABYLON.SceneSerializer = SceneSerializer;
  90996. })(BABYLON || (BABYLON = {}));
  90997. //# sourceMappingURL=babylon.sceneSerializer.js.map
  90998. "use strict";
  90999. var BABYLON;
  91000. (function (BABYLON) {
  91001. var ReflectionProbe = /** @class */ (function () {
  91002. function ReflectionProbe(name, size, scene, generateMipMaps) {
  91003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  91004. var _this = this;
  91005. this.name = name;
  91006. this._viewMatrix = BABYLON.Matrix.Identity();
  91007. this._target = BABYLON.Vector3.Zero();
  91008. this._add = BABYLON.Vector3.Zero();
  91009. this._invertYAxis = false;
  91010. this.position = BABYLON.Vector3.Zero();
  91011. this._scene = scene;
  91012. this._scene.reflectionProbes.push(this);
  91013. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  91014. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  91015. switch (faceIndex) {
  91016. case 0:
  91017. _this._add.copyFromFloats(1, 0, 0);
  91018. break;
  91019. case 1:
  91020. _this._add.copyFromFloats(-1, 0, 0);
  91021. break;
  91022. case 2:
  91023. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  91024. break;
  91025. case 3:
  91026. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  91027. break;
  91028. case 4:
  91029. _this._add.copyFromFloats(0, 0, 1);
  91030. break;
  91031. case 5:
  91032. _this._add.copyFromFloats(0, 0, -1);
  91033. break;
  91034. }
  91035. if (_this._attachedMesh) {
  91036. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  91037. }
  91038. _this.position.addToRef(_this._add, _this._target);
  91039. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  91040. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  91041. scene._forcedViewPosition = _this.position;
  91042. });
  91043. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  91044. scene._forcedViewPosition = null;
  91045. scene.updateTransformMatrix(true);
  91046. });
  91047. if (scene.activeCamera) {
  91048. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  91049. }
  91050. }
  91051. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  91052. get: function () {
  91053. return this._renderTargetTexture.samples;
  91054. },
  91055. set: function (value) {
  91056. this._renderTargetTexture.samples = value;
  91057. },
  91058. enumerable: true,
  91059. configurable: true
  91060. });
  91061. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  91062. get: function () {
  91063. return this._renderTargetTexture.refreshRate;
  91064. },
  91065. set: function (value) {
  91066. this._renderTargetTexture.refreshRate = value;
  91067. },
  91068. enumerable: true,
  91069. configurable: true
  91070. });
  91071. ReflectionProbe.prototype.getScene = function () {
  91072. return this._scene;
  91073. };
  91074. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  91075. get: function () {
  91076. return this._renderTargetTexture;
  91077. },
  91078. enumerable: true,
  91079. configurable: true
  91080. });
  91081. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  91082. get: function () {
  91083. return this._renderTargetTexture.renderList;
  91084. },
  91085. enumerable: true,
  91086. configurable: true
  91087. });
  91088. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  91089. this._attachedMesh = mesh;
  91090. };
  91091. /**
  91092. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  91093. *
  91094. * @param renderingGroupId The rendering group id corresponding to its index
  91095. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  91096. */
  91097. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  91098. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  91099. };
  91100. ReflectionProbe.prototype.dispose = function () {
  91101. var index = this._scene.reflectionProbes.indexOf(this);
  91102. if (index !== -1) {
  91103. // Remove from the scene if found
  91104. this._scene.reflectionProbes.splice(index, 1);
  91105. }
  91106. if (this._renderTargetTexture) {
  91107. this._renderTargetTexture.dispose();
  91108. this._renderTargetTexture = null;
  91109. }
  91110. };
  91111. return ReflectionProbe;
  91112. }());
  91113. BABYLON.ReflectionProbe = ReflectionProbe;
  91114. })(BABYLON || (BABYLON = {}));
  91115. //# sourceMappingURL=babylon.reflectionProbe.js.map
  91116. "use strict";
  91117. var BABYLON;
  91118. (function (BABYLON) {
  91119. var Layer = /** @class */ (function () {
  91120. function Layer(name, imgUrl, scene, isBackground, color) {
  91121. this.name = name;
  91122. this.scale = new BABYLON.Vector2(1, 1);
  91123. this.offset = new BABYLON.Vector2(0, 0);
  91124. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  91125. this.layerMask = 0x0FFFFFFF;
  91126. this._vertexBuffers = {};
  91127. // Events
  91128. /**
  91129. * An event triggered when the layer is disposed.
  91130. */
  91131. this.onDisposeObservable = new BABYLON.Observable();
  91132. /**
  91133. * An event triggered before rendering the scene
  91134. */
  91135. this.onBeforeRenderObservable = new BABYLON.Observable();
  91136. /**
  91137. * An event triggered after rendering the scene
  91138. */
  91139. this.onAfterRenderObservable = new BABYLON.Observable();
  91140. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  91141. this.isBackground = isBackground === undefined ? true : isBackground;
  91142. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  91143. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  91144. this._scene.layers.push(this);
  91145. var engine = this._scene.getEngine();
  91146. // VBO
  91147. var vertices = [];
  91148. vertices.push(1, 1);
  91149. vertices.push(-1, 1);
  91150. vertices.push(-1, -1);
  91151. vertices.push(1, -1);
  91152. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91153. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91154. this._createIndexBuffer();
  91155. // Effects
  91156. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  91157. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  91158. }
  91159. Object.defineProperty(Layer.prototype, "onDispose", {
  91160. set: function (callback) {
  91161. if (this._onDisposeObserver) {
  91162. this.onDisposeObservable.remove(this._onDisposeObserver);
  91163. }
  91164. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  91165. },
  91166. enumerable: true,
  91167. configurable: true
  91168. });
  91169. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  91170. set: function (callback) {
  91171. if (this._onBeforeRenderObserver) {
  91172. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  91173. }
  91174. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  91175. },
  91176. enumerable: true,
  91177. configurable: true
  91178. });
  91179. Object.defineProperty(Layer.prototype, "onAfterRender", {
  91180. set: function (callback) {
  91181. if (this._onAfterRenderObserver) {
  91182. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91183. }
  91184. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  91185. },
  91186. enumerable: true,
  91187. configurable: true
  91188. });
  91189. Layer.prototype._createIndexBuffer = function () {
  91190. var engine = this._scene.getEngine();
  91191. // Indices
  91192. var indices = [];
  91193. indices.push(0);
  91194. indices.push(1);
  91195. indices.push(2);
  91196. indices.push(0);
  91197. indices.push(2);
  91198. indices.push(3);
  91199. this._indexBuffer = engine.createIndexBuffer(indices);
  91200. };
  91201. Layer.prototype._rebuild = function () {
  91202. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91203. if (vb) {
  91204. vb._rebuild();
  91205. }
  91206. this._createIndexBuffer();
  91207. };
  91208. Layer.prototype.render = function () {
  91209. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  91210. // Check
  91211. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  91212. return;
  91213. var engine = this._scene.getEngine();
  91214. this.onBeforeRenderObservable.notifyObservers(this);
  91215. // Render
  91216. engine.enableEffect(currentEffect);
  91217. engine.setState(false);
  91218. // Texture
  91219. currentEffect.setTexture("textureSampler", this.texture);
  91220. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  91221. // Color
  91222. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  91223. // Scale / offset
  91224. currentEffect.setVector2("offset", this.offset);
  91225. currentEffect.setVector2("scale", this.scale);
  91226. // VBOs
  91227. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91228. // Draw order
  91229. if (!this.alphaTest) {
  91230. engine.setAlphaMode(this.alphaBlendingMode);
  91231. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91232. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91233. }
  91234. else {
  91235. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91236. }
  91237. this.onAfterRenderObservable.notifyObservers(this);
  91238. };
  91239. Layer.prototype.dispose = function () {
  91240. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91241. if (vertexBuffer) {
  91242. vertexBuffer.dispose();
  91243. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91244. }
  91245. if (this._indexBuffer) {
  91246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91247. this._indexBuffer = null;
  91248. }
  91249. if (this.texture) {
  91250. this.texture.dispose();
  91251. this.texture = null;
  91252. }
  91253. // Remove from scene
  91254. var index = this._scene.layers.indexOf(this);
  91255. this._scene.layers.splice(index, 1);
  91256. // Callback
  91257. this.onDisposeObservable.notifyObservers(this);
  91258. this.onDisposeObservable.clear();
  91259. this.onAfterRenderObservable.clear();
  91260. this.onBeforeRenderObservable.clear();
  91261. };
  91262. return Layer;
  91263. }());
  91264. BABYLON.Layer = Layer;
  91265. })(BABYLON || (BABYLON = {}));
  91266. //# sourceMappingURL=babylon.layer.js.map
  91267. "use strict";
  91268. var BABYLON;
  91269. (function (BABYLON) {
  91270. var TextureTools = /** @class */ (function () {
  91271. function TextureTools() {
  91272. }
  91273. /**
  91274. * Uses the GPU to create a copy texture rescaled at a given size
  91275. * @param texture Texture to copy from
  91276. * @param width Desired width
  91277. * @param height Desired height
  91278. * @return Generated texture
  91279. */
  91280. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  91281. if (useBilinearMode === void 0) { useBilinearMode = true; }
  91282. var scene = texture.getScene();
  91283. var engine = scene.getEngine();
  91284. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  91285. rtt.wrapU = texture.wrapU;
  91286. rtt.wrapV = texture.wrapV;
  91287. rtt.uOffset = texture.uOffset;
  91288. rtt.vOffset = texture.vOffset;
  91289. rtt.uScale = texture.uScale;
  91290. rtt.vScale = texture.vScale;
  91291. rtt.uAng = texture.uAng;
  91292. rtt.vAng = texture.vAng;
  91293. rtt.wAng = texture.wAng;
  91294. rtt.coordinatesIndex = texture.coordinatesIndex;
  91295. rtt.level = texture.level;
  91296. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  91297. rtt._texture.isReady = false;
  91298. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91299. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91300. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91301. passPostProcess.getEffect().executeWhenCompiled(function () {
  91302. passPostProcess.onApply = function (effect) {
  91303. effect.setTexture("textureSampler", texture);
  91304. };
  91305. var internalTexture = rtt.getInternalTexture();
  91306. if (internalTexture) {
  91307. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  91308. engine.unBindFramebuffer(internalTexture);
  91309. rtt.disposeFramebufferObjects();
  91310. passPostProcess.dispose();
  91311. internalTexture.isReady = true;
  91312. }
  91313. });
  91314. return rtt;
  91315. };
  91316. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  91317. if (!scene._environmentBRDFTexture) {
  91318. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91319. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91320. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91321. scene._environmentBRDFTexture = texture;
  91322. }
  91323. return scene._environmentBRDFTexture;
  91324. };
  91325. 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=";
  91326. return TextureTools;
  91327. }());
  91328. BABYLON.TextureTools = TextureTools;
  91329. })(BABYLON || (BABYLON = {}));
  91330. //# sourceMappingURL=babylon.textureTools.js.map
  91331. "use strict";
  91332. var BABYLON;
  91333. (function (BABYLON) {
  91334. var FramingBehavior = /** @class */ (function () {
  91335. function FramingBehavior() {
  91336. this._mode = FramingBehavior.FitFrustumSidesMode;
  91337. this._radiusScale = 1.0;
  91338. this._positionScale = 0.5;
  91339. this._defaultElevation = 0.3;
  91340. this._elevationReturnTime = 1500;
  91341. this._elevationReturnWaitTime = 1000;
  91342. this._zoomStopsAnimation = false;
  91343. this._framingTime = 1500;
  91344. this._isPointerDown = false;
  91345. this._lastInteractionTime = -Infinity;
  91346. // Framing control
  91347. this._animatables = new Array();
  91348. this._betaIsAnimating = false;
  91349. }
  91350. Object.defineProperty(FramingBehavior.prototype, "name", {
  91351. get: function () {
  91352. return "Framing";
  91353. },
  91354. enumerable: true,
  91355. configurable: true
  91356. });
  91357. Object.defineProperty(FramingBehavior.prototype, "mode", {
  91358. /**
  91359. * Gets current mode used by the behavior.
  91360. */
  91361. get: function () {
  91362. return this._mode;
  91363. },
  91364. /**
  91365. * Sets the current mode used by the behavior
  91366. */
  91367. set: function (mode) {
  91368. this._mode = mode;
  91369. },
  91370. enumerable: true,
  91371. configurable: true
  91372. });
  91373. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  91374. /**
  91375. * Gets the scale applied to the radius
  91376. */
  91377. get: function () {
  91378. return this._radiusScale;
  91379. },
  91380. /**
  91381. * Sets the scale applied to the radius (1 by default)
  91382. */
  91383. set: function (radius) {
  91384. this._radiusScale = radius;
  91385. },
  91386. enumerable: true,
  91387. configurable: true
  91388. });
  91389. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  91390. /**
  91391. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  91392. */
  91393. get: function () {
  91394. return this._positionScale;
  91395. },
  91396. /**
  91397. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  91398. */
  91399. set: function (scale) {
  91400. this._positionScale = scale;
  91401. },
  91402. enumerable: true,
  91403. configurable: true
  91404. });
  91405. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  91406. /**
  91407. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  91408. * behaviour is triggered, in radians.
  91409. */
  91410. get: function () {
  91411. return this._defaultElevation;
  91412. },
  91413. /**
  91414. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  91415. * behaviour is triggered, in radians.
  91416. */
  91417. set: function (elevation) {
  91418. this._defaultElevation = elevation;
  91419. },
  91420. enumerable: true,
  91421. configurable: true
  91422. });
  91423. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  91424. /**
  91425. * Gets the time (in milliseconds) taken to return to the default beta position.
  91426. * Negative value indicates camera should not return to default.
  91427. */
  91428. get: function () {
  91429. return this._elevationReturnTime;
  91430. },
  91431. /**
  91432. * Sets the time (in milliseconds) taken to return to the default beta position.
  91433. * Negative value indicates camera should not return to default.
  91434. */
  91435. set: function (speed) {
  91436. this._elevationReturnTime = speed;
  91437. },
  91438. enumerable: true,
  91439. configurable: true
  91440. });
  91441. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  91442. /**
  91443. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  91444. */
  91445. get: function () {
  91446. return this._elevationReturnWaitTime;
  91447. },
  91448. /**
  91449. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  91450. */
  91451. set: function (time) {
  91452. this._elevationReturnWaitTime = time;
  91453. },
  91454. enumerable: true,
  91455. configurable: true
  91456. });
  91457. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  91458. /**
  91459. * Gets the flag that indicates if user zooming should stop animation.
  91460. */
  91461. get: function () {
  91462. return this._zoomStopsAnimation;
  91463. },
  91464. /**
  91465. * Sets the flag that indicates if user zooming should stop animation.
  91466. */
  91467. set: function (flag) {
  91468. this._zoomStopsAnimation = flag;
  91469. },
  91470. enumerable: true,
  91471. configurable: true
  91472. });
  91473. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  91474. /**
  91475. * Gets the transition time when framing the mesh, in milliseconds
  91476. */
  91477. get: function () {
  91478. return this._framingTime;
  91479. },
  91480. /**
  91481. * Sets the transition time when framing the mesh, in milliseconds
  91482. */
  91483. set: function (time) {
  91484. this._framingTime = time;
  91485. },
  91486. enumerable: true,
  91487. configurable: true
  91488. });
  91489. FramingBehavior.prototype.init = function () {
  91490. // Do notihng
  91491. };
  91492. FramingBehavior.prototype.attach = function (camera) {
  91493. var _this = this;
  91494. this._attachedCamera = camera;
  91495. var scene = this._attachedCamera.getScene();
  91496. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  91497. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  91498. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  91499. _this._isPointerDown = true;
  91500. return;
  91501. }
  91502. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  91503. _this._isPointerDown = false;
  91504. }
  91505. });
  91506. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  91507. if (mesh) {
  91508. _this.zoomOnMesh(mesh);
  91509. }
  91510. });
  91511. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  91512. // Stop the animation if there is user interaction and the animation should stop for this interaction
  91513. _this._applyUserInteraction();
  91514. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  91515. // back to the default position after a given timeout
  91516. _this._maintainCameraAboveGround();
  91517. });
  91518. };
  91519. FramingBehavior.prototype.detach = function () {
  91520. if (!this._attachedCamera) {
  91521. return;
  91522. }
  91523. var scene = this._attachedCamera.getScene();
  91524. if (this._onPrePointerObservableObserver) {
  91525. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  91526. }
  91527. if (this._onAfterCheckInputsObserver) {
  91528. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  91529. }
  91530. if (this._onMeshTargetChangedObserver) {
  91531. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  91532. }
  91533. this._attachedCamera = null;
  91534. };
  91535. /**
  91536. * Targets the given mesh and updates zoom level accordingly.
  91537. * @param mesh The mesh to target.
  91538. * @param radius Optional. If a cached radius position already exists, overrides default.
  91539. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91540. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91541. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91542. */
  91543. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  91544. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91545. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91546. mesh.computeWorldMatrix(true);
  91547. var boundingBox = mesh.getBoundingInfo().boundingBox;
  91548. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  91549. };
  91550. /**
  91551. * Targets the given mesh with its children and updates zoom level accordingly.
  91552. * @param mesh The mesh to target.
  91553. * @param radius Optional. If a cached radius position already exists, overrides default.
  91554. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91555. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91556. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91557. */
  91558. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  91559. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91560. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91561. mesh.computeWorldMatrix(true);
  91562. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  91563. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  91564. };
  91565. /**
  91566. * Targets the given meshes with their children and updates zoom level accordingly.
  91567. * @param meshes The mesh to target.
  91568. * @param radius Optional. If a cached radius position already exists, overrides default.
  91569. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91570. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91571. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91572. */
  91573. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  91574. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91575. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91576. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  91577. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  91578. for (var i = 0; i < meshes.length; i++) {
  91579. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  91580. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  91581. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  91582. }
  91583. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  91584. };
  91585. /**
  91586. * Targets the given mesh and updates zoom level accordingly.
  91587. * @param mesh The mesh to target.
  91588. * @param radius Optional. If a cached radius position already exists, overrides default.
  91589. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  91590. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  91591. * @param onAnimationEnd Callback triggered at the end of the framing animation
  91592. */
  91593. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  91594. var _this = this;
  91595. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  91596. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  91597. var zoomTarget;
  91598. if (!this._attachedCamera) {
  91599. return;
  91600. }
  91601. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  91602. var bottom = minimumWorld.y;
  91603. var top = maximumWorld.y;
  91604. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  91605. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  91606. if (focusOnOriginXZ) {
  91607. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  91608. }
  91609. else {
  91610. var centerWorld = minimumWorld.add(radiusWorld);
  91611. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  91612. }
  91613. if (!this._vectorTransition) {
  91614. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  91615. }
  91616. this._betaIsAnimating = true;
  91617. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  91618. if (animatable) {
  91619. this._animatables.push(animatable);
  91620. }
  91621. // sets the radius and lower radius bounds
  91622. // Small delta ensures camera is not always at lower zoom limit.
  91623. var radius = 0;
  91624. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  91625. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  91626. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  91627. radius = position;
  91628. }
  91629. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  91630. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  91631. if (this._attachedCamera.lowerRadiusLimit === null) {
  91632. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  91633. }
  91634. }
  91635. // Set sensibilities
  91636. var extend = maximumWorld.subtract(minimumWorld).length();
  91637. this._attachedCamera.panningSensibility = 5000 / extend;
  91638. this._attachedCamera.wheelPrecision = 100 / radius;
  91639. // transition to new radius
  91640. if (!this._radiusTransition) {
  91641. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  91642. }
  91643. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  91644. _this.stopAllAnimations();
  91645. if (onAnimationEnd) {
  91646. onAnimationEnd();
  91647. }
  91648. if (_this._attachedCamera) {
  91649. _this._attachedCamera.storeState();
  91650. }
  91651. });
  91652. if (animatable) {
  91653. this._animatables.push(animatable);
  91654. }
  91655. };
  91656. /**
  91657. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  91658. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  91659. * frustum width.
  91660. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  91661. * to fully enclose the mesh in the viewing frustum.
  91662. */
  91663. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  91664. var size = maximumWorld.subtract(minimumWorld);
  91665. var boxVectorGlobalDiagonal = size.length();
  91666. var frustumSlope = this._getFrustumSlope();
  91667. // Formula for setting distance
  91668. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  91669. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  91670. // Horizon distance
  91671. var radius = radiusWithoutFraming * this._radiusScale;
  91672. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  91673. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  91674. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  91675. var camera = this._attachedCamera;
  91676. if (!camera) {
  91677. return 0;
  91678. }
  91679. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  91680. // Don't exceed the requested limit
  91681. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  91682. }
  91683. // Don't exceed the upper radius limit
  91684. if (camera.upperRadiusLimit) {
  91685. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  91686. }
  91687. return distance;
  91688. };
  91689. /**
  91690. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  91691. * is automatically returned to its default position (expected to be above ground plane).
  91692. */
  91693. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  91694. var _this = this;
  91695. if (this._elevationReturnTime < 0) {
  91696. return;
  91697. }
  91698. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  91699. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  91700. var limitBeta = Math.PI * 0.5;
  91701. // Bring the camera back up if below the ground plane
  91702. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  91703. this._betaIsAnimating = true;
  91704. //Transition to new position
  91705. this.stopAllAnimations();
  91706. if (!this._betaTransition) {
  91707. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  91708. }
  91709. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  91710. _this._clearAnimationLocks();
  91711. _this.stopAllAnimations();
  91712. });
  91713. if (animatabe) {
  91714. this._animatables.push(animatabe);
  91715. }
  91716. }
  91717. };
  91718. /**
  91719. * Returns the frustum slope based on the canvas ratio and camera FOV
  91720. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  91721. */
  91722. FramingBehavior.prototype._getFrustumSlope = function () {
  91723. // Calculate the viewport ratio
  91724. // Aspect Ratio is Height/Width.
  91725. var camera = this._attachedCamera;
  91726. if (!camera) {
  91727. return BABYLON.Vector2.Zero();
  91728. }
  91729. var engine = camera.getScene().getEngine();
  91730. var aspectRatio = engine.getAspectRatio(camera);
  91731. // Camera FOV is the vertical field of view (top-bottom) in radians.
  91732. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  91733. var frustumSlopeY = Math.tan(camera.fov / 2);
  91734. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  91735. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  91736. // along the forward vector.
  91737. var frustumSlopeX = frustumSlopeY * aspectRatio;
  91738. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  91739. };
  91740. /**
  91741. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  91742. */
  91743. FramingBehavior.prototype._clearAnimationLocks = function () {
  91744. this._betaIsAnimating = false;
  91745. };
  91746. /**
  91747. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  91748. */
  91749. FramingBehavior.prototype._applyUserInteraction = function () {
  91750. if (this.isUserIsMoving) {
  91751. this._lastInteractionTime = BABYLON.Tools.Now;
  91752. this.stopAllAnimations();
  91753. this._clearAnimationLocks();
  91754. }
  91755. };
  91756. /**
  91757. * Stops and removes all animations that have been applied to the camera
  91758. */
  91759. FramingBehavior.prototype.stopAllAnimations = function () {
  91760. if (this._attachedCamera) {
  91761. this._attachedCamera.animations = [];
  91762. }
  91763. while (this._animatables.length) {
  91764. if (this._animatables[0]) {
  91765. this._animatables[0].onAnimationEnd = null;
  91766. this._animatables[0].stop();
  91767. }
  91768. this._animatables.shift();
  91769. }
  91770. };
  91771. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  91772. /**
  91773. * Gets a value indicating if the user is moving the camera
  91774. */
  91775. get: function () {
  91776. if (!this._attachedCamera) {
  91777. return false;
  91778. }
  91779. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  91780. this._attachedCamera.inertialBetaOffset !== 0 ||
  91781. this._attachedCamera.inertialRadiusOffset !== 0 ||
  91782. this._attachedCamera.inertialPanningX !== 0 ||
  91783. this._attachedCamera.inertialPanningY !== 0 ||
  91784. this._isPointerDown;
  91785. },
  91786. enumerable: true,
  91787. configurable: true
  91788. });
  91789. /**
  91790. * The easing function used by animations
  91791. */
  91792. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  91793. /**
  91794. * The easing mode used by animations
  91795. */
  91796. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  91797. // Statics
  91798. /**
  91799. * The camera can move all the way towards the mesh.
  91800. */
  91801. FramingBehavior.IgnoreBoundsSizeMode = 0;
  91802. /**
  91803. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  91804. */
  91805. FramingBehavior.FitFrustumSidesMode = 1;
  91806. return FramingBehavior;
  91807. }());
  91808. BABYLON.FramingBehavior = FramingBehavior;
  91809. })(BABYLON || (BABYLON = {}));
  91810. //# sourceMappingURL=babylon.framingBehavior.js.map
  91811. "use strict";
  91812. var BABYLON;
  91813. (function (BABYLON) {
  91814. /**
  91815. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  91816. */
  91817. var BouncingBehavior = /** @class */ (function () {
  91818. function BouncingBehavior() {
  91819. /**
  91820. * The duration of the animation, in milliseconds
  91821. */
  91822. this.transitionDuration = 450;
  91823. /**
  91824. * Length of the distance animated by the transition when lower radius is reached
  91825. */
  91826. this.lowerRadiusTransitionRange = 2;
  91827. /**
  91828. * Length of the distance animated by the transition when upper radius is reached
  91829. */
  91830. this.upperRadiusTransitionRange = -2;
  91831. this._autoTransitionRange = false;
  91832. // Animations
  91833. this._radiusIsAnimating = false;
  91834. this._radiusBounceTransition = null;
  91835. this._animatables = new Array();
  91836. }
  91837. Object.defineProperty(BouncingBehavior.prototype, "name", {
  91838. get: function () {
  91839. return "Bouncing";
  91840. },
  91841. enumerable: true,
  91842. configurable: true
  91843. });
  91844. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  91845. /**
  91846. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  91847. */
  91848. get: function () {
  91849. return this._autoTransitionRange;
  91850. },
  91851. /**
  91852. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  91853. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  91854. */
  91855. set: function (value) {
  91856. var _this = this;
  91857. if (this._autoTransitionRange === value) {
  91858. return;
  91859. }
  91860. this._autoTransitionRange = value;
  91861. var camera = this._attachedCamera;
  91862. if (!camera) {
  91863. return;
  91864. }
  91865. if (value) {
  91866. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  91867. if (!mesh) {
  91868. return;
  91869. }
  91870. mesh.computeWorldMatrix(true);
  91871. var diagonal = mesh.getBoundingInfo().diagonalLength;
  91872. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  91873. _this.upperRadiusTransitionRange = diagonal * 0.05;
  91874. });
  91875. }
  91876. else if (this._onMeshTargetChangedObserver) {
  91877. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  91878. }
  91879. },
  91880. enumerable: true,
  91881. configurable: true
  91882. });
  91883. BouncingBehavior.prototype.init = function () {
  91884. // Do notihng
  91885. };
  91886. BouncingBehavior.prototype.attach = function (camera) {
  91887. var _this = this;
  91888. this._attachedCamera = camera;
  91889. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  91890. if (!_this._attachedCamera) {
  91891. return;
  91892. }
  91893. // Add the bounce animation to the lower radius limit
  91894. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  91895. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  91896. }
  91897. // Add the bounce animation to the upper radius limit
  91898. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  91899. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  91900. }
  91901. });
  91902. };
  91903. BouncingBehavior.prototype.detach = function () {
  91904. if (!this._attachedCamera) {
  91905. return;
  91906. }
  91907. if (this._onAfterCheckInputsObserver) {
  91908. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  91909. }
  91910. if (this._onMeshTargetChangedObserver) {
  91911. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  91912. }
  91913. this._attachedCamera = null;
  91914. };
  91915. /**
  91916. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  91917. * @param radiusLimit The limit to check against.
  91918. * @return Bool to indicate if at limit.
  91919. */
  91920. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  91921. if (!this._attachedCamera) {
  91922. return false;
  91923. }
  91924. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  91925. return true;
  91926. }
  91927. return false;
  91928. };
  91929. /**
  91930. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  91931. * @param radiusDelta The delta by which to animate to. Can be negative.
  91932. */
  91933. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  91934. var _this = this;
  91935. if (!this._attachedCamera) {
  91936. return;
  91937. }
  91938. if (!this._radiusBounceTransition) {
  91939. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  91940. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  91941. }
  91942. // Prevent zoom until bounce has completed
  91943. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  91944. this._attachedCamera.wheelPrecision = Infinity;
  91945. this._attachedCamera.inertialRadiusOffset = 0;
  91946. // Animate to the radius limit
  91947. this.stopAllAnimations();
  91948. this._radiusIsAnimating = true;
  91949. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  91950. if (animatable) {
  91951. this._animatables.push(animatable);
  91952. }
  91953. };
  91954. /**
  91955. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  91956. */
  91957. BouncingBehavior.prototype._clearAnimationLocks = function () {
  91958. this._radiusIsAnimating = false;
  91959. if (this._attachedCamera) {
  91960. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  91961. }
  91962. };
  91963. /**
  91964. * Stops and removes all animations that have been applied to the camera
  91965. */
  91966. BouncingBehavior.prototype.stopAllAnimations = function () {
  91967. if (this._attachedCamera) {
  91968. this._attachedCamera.animations = [];
  91969. }
  91970. while (this._animatables.length) {
  91971. this._animatables[0].onAnimationEnd = null;
  91972. this._animatables[0].stop();
  91973. this._animatables.shift();
  91974. }
  91975. };
  91976. /**
  91977. * The easing function used by animations
  91978. */
  91979. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  91980. /**
  91981. * The easing mode used by animations
  91982. */
  91983. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  91984. return BouncingBehavior;
  91985. }());
  91986. BABYLON.BouncingBehavior = BouncingBehavior;
  91987. })(BABYLON || (BABYLON = {}));
  91988. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  91989. "use strict";
  91990. var BABYLON;
  91991. (function (BABYLON) {
  91992. var AutoRotationBehavior = /** @class */ (function () {
  91993. function AutoRotationBehavior() {
  91994. this._zoomStopsAnimation = false;
  91995. this._idleRotationSpeed = 0.05;
  91996. this._idleRotationWaitTime = 2000;
  91997. this._idleRotationSpinupTime = 2000;
  91998. this._isPointerDown = false;
  91999. this._lastFrameTime = null;
  92000. this._lastInteractionTime = -Infinity;
  92001. this._cameraRotationSpeed = 0;
  92002. this._lastFrameRadius = 0;
  92003. }
  92004. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  92005. get: function () {
  92006. return "AutoRotation";
  92007. },
  92008. enumerable: true,
  92009. configurable: true
  92010. });
  92011. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  92012. /**
  92013. * Gets the flag that indicates if user zooming should stop animation.
  92014. */
  92015. get: function () {
  92016. return this._zoomStopsAnimation;
  92017. },
  92018. /**
  92019. * Sets the flag that indicates if user zooming should stop animation.
  92020. */
  92021. set: function (flag) {
  92022. this._zoomStopsAnimation = flag;
  92023. },
  92024. enumerable: true,
  92025. configurable: true
  92026. });
  92027. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  92028. /**
  92029. * Gets the default speed at which the camera rotates around the model.
  92030. */
  92031. get: function () {
  92032. return this._idleRotationSpeed;
  92033. },
  92034. /**
  92035. * Sets the default speed at which the camera rotates around the model.
  92036. */
  92037. set: function (speed) {
  92038. this._idleRotationSpeed = speed;
  92039. },
  92040. enumerable: true,
  92041. configurable: true
  92042. });
  92043. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  92044. /**
  92045. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  92046. */
  92047. get: function () {
  92048. return this._idleRotationWaitTime;
  92049. },
  92050. /**
  92051. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  92052. */
  92053. set: function (time) {
  92054. this._idleRotationWaitTime = time;
  92055. },
  92056. enumerable: true,
  92057. configurable: true
  92058. });
  92059. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  92060. /**
  92061. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92062. */
  92063. get: function () {
  92064. return this._idleRotationSpinupTime;
  92065. },
  92066. /**
  92067. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92068. */
  92069. set: function (time) {
  92070. this._idleRotationSpinupTime = time;
  92071. },
  92072. enumerable: true,
  92073. configurable: true
  92074. });
  92075. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  92076. /**
  92077. * Gets a value indicating if the camera is currently rotating because of this behavior
  92078. */
  92079. get: function () {
  92080. return Math.abs(this._cameraRotationSpeed) > 0;
  92081. },
  92082. enumerable: true,
  92083. configurable: true
  92084. });
  92085. AutoRotationBehavior.prototype.init = function () {
  92086. // Do notihng
  92087. };
  92088. AutoRotationBehavior.prototype.attach = function (camera) {
  92089. var _this = this;
  92090. this._attachedCamera = camera;
  92091. var scene = this._attachedCamera.getScene();
  92092. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92093. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92094. _this._isPointerDown = true;
  92095. return;
  92096. }
  92097. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92098. _this._isPointerDown = false;
  92099. }
  92100. });
  92101. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92102. var now = BABYLON.Tools.Now;
  92103. var dt = 0;
  92104. if (_this._lastFrameTime != null) {
  92105. dt = now - _this._lastFrameTime;
  92106. }
  92107. _this._lastFrameTime = now;
  92108. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92109. _this._applyUserInteraction();
  92110. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  92111. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  92112. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  92113. // Step camera rotation by rotation speed
  92114. if (_this._attachedCamera) {
  92115. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  92116. }
  92117. });
  92118. };
  92119. AutoRotationBehavior.prototype.detach = function () {
  92120. if (!this._attachedCamera) {
  92121. return;
  92122. }
  92123. var scene = this._attachedCamera.getScene();
  92124. if (this._onPrePointerObservableObserver) {
  92125. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92126. }
  92127. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92128. this._attachedCamera = null;
  92129. };
  92130. /**
  92131. * Returns true if user is scrolling.
  92132. * @return true if user is scrolling.
  92133. */
  92134. AutoRotationBehavior.prototype._userIsZooming = function () {
  92135. if (!this._attachedCamera) {
  92136. return false;
  92137. }
  92138. return this._attachedCamera.inertialRadiusOffset !== 0;
  92139. };
  92140. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  92141. if (!this._attachedCamera) {
  92142. return false;
  92143. }
  92144. var zoomHasHitLimit = false;
  92145. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  92146. zoomHasHitLimit = true;
  92147. }
  92148. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  92149. this._lastFrameRadius = this._attachedCamera.radius;
  92150. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  92151. };
  92152. /**
  92153. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92154. */
  92155. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  92156. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  92157. this._lastInteractionTime = BABYLON.Tools.Now;
  92158. }
  92159. };
  92160. // Tools
  92161. AutoRotationBehavior.prototype._userIsMoving = function () {
  92162. if (!this._attachedCamera) {
  92163. return false;
  92164. }
  92165. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92166. this._attachedCamera.inertialBetaOffset !== 0 ||
  92167. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92168. this._attachedCamera.inertialPanningX !== 0 ||
  92169. this._attachedCamera.inertialPanningY !== 0 ||
  92170. this._isPointerDown;
  92171. };
  92172. return AutoRotationBehavior;
  92173. }());
  92174. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  92175. })(BABYLON || (BABYLON = {}));
  92176. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  92177. "use strict";
  92178. var BABYLON;
  92179. (function (BABYLON) {
  92180. var NullEngineOptions = /** @class */ (function () {
  92181. function NullEngineOptions() {
  92182. this.renderWidth = 512;
  92183. this.renderHeight = 256;
  92184. this.textureSize = 512;
  92185. this.deterministicLockstep = false;
  92186. this.lockstepMaxSteps = 4;
  92187. }
  92188. return NullEngineOptions;
  92189. }());
  92190. BABYLON.NullEngineOptions = NullEngineOptions;
  92191. /**
  92192. * The null engine class provides support for headless version of babylon.js.
  92193. * This can be used in server side scenario or for testing purposes
  92194. */
  92195. var NullEngine = /** @class */ (function (_super) {
  92196. __extends(NullEngine, _super);
  92197. function NullEngine(options) {
  92198. if (options === void 0) { options = new NullEngineOptions(); }
  92199. var _this = _super.call(this, null) || this;
  92200. if (options.deterministicLockstep === undefined) {
  92201. options.deterministicLockstep = false;
  92202. }
  92203. if (options.lockstepMaxSteps === undefined) {
  92204. options.lockstepMaxSteps = 4;
  92205. }
  92206. _this._options = options;
  92207. // Init caps
  92208. // We consider we are on a webgl1 capable device
  92209. _this._caps = new BABYLON.EngineCapabilities();
  92210. _this._caps.maxTexturesImageUnits = 16;
  92211. _this._caps.maxVertexTextureImageUnits = 16;
  92212. _this._caps.maxTextureSize = 512;
  92213. _this._caps.maxCubemapTextureSize = 512;
  92214. _this._caps.maxRenderTextureSize = 512;
  92215. _this._caps.maxVertexAttribs = 16;
  92216. _this._caps.maxVaryingVectors = 16;
  92217. _this._caps.maxFragmentUniformVectors = 16;
  92218. _this._caps.maxVertexUniformVectors = 16;
  92219. // Extensions
  92220. _this._caps.standardDerivatives = false;
  92221. _this._caps.astc = null;
  92222. _this._caps.s3tc = null;
  92223. _this._caps.pvrtc = null;
  92224. _this._caps.etc1 = null;
  92225. _this._caps.etc2 = null;
  92226. _this._caps.textureAnisotropicFilterExtension = null;
  92227. _this._caps.maxAnisotropy = 0;
  92228. _this._caps.uintIndices = false;
  92229. _this._caps.fragmentDepthSupported = false;
  92230. _this._caps.highPrecisionShaderSupported = true;
  92231. _this._caps.colorBufferFloat = false;
  92232. _this._caps.textureFloat = false;
  92233. _this._caps.textureFloatLinearFiltering = false;
  92234. _this._caps.textureFloatRender = false;
  92235. _this._caps.textureHalfFloat = false;
  92236. _this._caps.textureHalfFloatLinearFiltering = false;
  92237. _this._caps.textureHalfFloatRender = false;
  92238. _this._caps.textureLOD = false;
  92239. _this._caps.drawBuffersExtension = false;
  92240. _this._caps.depthTextureExtension = false;
  92241. _this._caps.vertexArrayObject = false;
  92242. _this._caps.instancedArrays = false;
  92243. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  92244. // Wrappers
  92245. if (typeof URL === "undefined") {
  92246. URL = {
  92247. createObjectURL: function () { },
  92248. revokeObjectURL: function () { }
  92249. };
  92250. }
  92251. if (typeof Blob === "undefined") {
  92252. Blob = function () { };
  92253. }
  92254. return _this;
  92255. }
  92256. NullEngine.prototype.isDeterministicLockStep = function () {
  92257. return this._options.deterministicLockstep;
  92258. };
  92259. NullEngine.prototype.getLockstepMaxSteps = function () {
  92260. return this._options.lockstepMaxSteps;
  92261. };
  92262. NullEngine.prototype.getHardwareScalingLevel = function () {
  92263. return 1.0;
  92264. };
  92265. NullEngine.prototype.createVertexBuffer = function (vertices) {
  92266. return {
  92267. capacity: 0,
  92268. references: 1,
  92269. is32Bits: false
  92270. };
  92271. };
  92272. NullEngine.prototype.createIndexBuffer = function (indices) {
  92273. return {
  92274. capacity: 0,
  92275. references: 1,
  92276. is32Bits: false
  92277. };
  92278. };
  92279. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  92280. if (stencil === void 0) { stencil = false; }
  92281. };
  92282. NullEngine.prototype.getRenderWidth = function (useScreen) {
  92283. if (useScreen === void 0) { useScreen = false; }
  92284. if (!useScreen && this._currentRenderTarget) {
  92285. return this._currentRenderTarget.width;
  92286. }
  92287. return this._options.renderWidth;
  92288. };
  92289. NullEngine.prototype.getRenderHeight = function (useScreen) {
  92290. if (useScreen === void 0) { useScreen = false; }
  92291. if (!useScreen && this._currentRenderTarget) {
  92292. return this._currentRenderTarget.height;
  92293. }
  92294. return this._options.renderHeight;
  92295. };
  92296. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  92297. this._cachedViewport = viewport;
  92298. };
  92299. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  92300. return {
  92301. transformFeedback: null,
  92302. __SPECTOR_rebuildProgram: null
  92303. };
  92304. };
  92305. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  92306. return [];
  92307. };
  92308. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  92309. return [];
  92310. };
  92311. NullEngine.prototype.bindSamplers = function (effect) {
  92312. this._currentEffect = null;
  92313. };
  92314. NullEngine.prototype.enableEffect = function (effect) {
  92315. this._currentEffect = effect;
  92316. if (effect.onBind) {
  92317. effect.onBind(effect);
  92318. }
  92319. effect.onBindObservable.notifyObservers(effect);
  92320. };
  92321. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  92322. if (zOffset === void 0) { zOffset = 0; }
  92323. if (reverseSide === void 0) { reverseSide = false; }
  92324. };
  92325. NullEngine.prototype.setIntArray = function (uniform, array) {
  92326. };
  92327. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  92328. };
  92329. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  92330. };
  92331. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  92332. };
  92333. NullEngine.prototype.setFloatArray = function (uniform, array) {
  92334. };
  92335. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  92336. };
  92337. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  92338. };
  92339. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  92340. };
  92341. NullEngine.prototype.setArray = function (uniform, array) {
  92342. };
  92343. NullEngine.prototype.setArray2 = function (uniform, array) {
  92344. };
  92345. NullEngine.prototype.setArray3 = function (uniform, array) {
  92346. };
  92347. NullEngine.prototype.setArray4 = function (uniform, array) {
  92348. };
  92349. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  92350. };
  92351. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  92352. };
  92353. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  92354. };
  92355. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  92356. };
  92357. NullEngine.prototype.setFloat = function (uniform, value) {
  92358. };
  92359. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  92360. };
  92361. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  92362. };
  92363. NullEngine.prototype.setBool = function (uniform, bool) {
  92364. };
  92365. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  92366. };
  92367. NullEngine.prototype.setColor3 = function (uniform, color3) {
  92368. };
  92369. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  92370. };
  92371. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  92372. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  92373. if (this._alphaMode === mode) {
  92374. return;
  92375. }
  92376. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  92377. if (!noDepthWriteChange) {
  92378. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  92379. }
  92380. this._alphaMode = mode;
  92381. };
  92382. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  92383. };
  92384. NullEngine.prototype.wipeCaches = function (bruteForce) {
  92385. if (this.preventCacheWipeBetweenFrames) {
  92386. return;
  92387. }
  92388. this.resetTextureCache();
  92389. this._currentEffect = null;
  92390. if (bruteForce) {
  92391. this._currentProgram = null;
  92392. this._stencilState.reset();
  92393. this._depthCullingState.reset();
  92394. this._alphaState.reset();
  92395. }
  92396. this._cachedVertexBuffers = null;
  92397. this._cachedIndexBuffer = null;
  92398. this._cachedEffectForVertexBuffers = null;
  92399. };
  92400. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  92401. };
  92402. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  92403. };
  92404. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  92405. };
  92406. NullEngine.prototype._createTexture = function () {
  92407. return {};
  92408. };
  92409. NullEngine.prototype._releaseTexture = function (texture) {
  92410. };
  92411. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  92412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92413. if (onLoad === void 0) { onLoad = null; }
  92414. if (onError === void 0) { onError = null; }
  92415. if (buffer === void 0) { buffer = null; }
  92416. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  92417. var url = String(urlArg);
  92418. texture.url = url;
  92419. texture.generateMipMaps = !noMipmap;
  92420. texture.samplingMode = samplingMode;
  92421. texture.invertY = invertY;
  92422. texture.baseWidth = this._options.textureSize;
  92423. texture.baseHeight = this._options.textureSize;
  92424. texture.width = this._options.textureSize;
  92425. texture.height = this._options.textureSize;
  92426. if (format) {
  92427. texture.format = format;
  92428. }
  92429. texture.isReady = true;
  92430. if (onLoad) {
  92431. onLoad();
  92432. }
  92433. return texture;
  92434. };
  92435. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  92436. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  92437. if (options !== undefined && typeof options === "object") {
  92438. fullOptions.generateMipMaps = options.generateMipMaps;
  92439. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  92440. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  92441. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  92442. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  92443. }
  92444. else {
  92445. fullOptions.generateMipMaps = options;
  92446. fullOptions.generateDepthBuffer = true;
  92447. fullOptions.generateStencilBuffer = false;
  92448. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92449. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92450. }
  92451. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  92452. var width = size.width || size;
  92453. var height = size.height || size;
  92454. texture._depthStencilBuffer = {};
  92455. texture._framebuffer = {};
  92456. texture.baseWidth = width;
  92457. texture.baseHeight = height;
  92458. texture.width = width;
  92459. texture.height = height;
  92460. texture.isReady = true;
  92461. texture.samples = 1;
  92462. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  92463. texture.samplingMode = fullOptions.samplingMode;
  92464. texture.type = fullOptions.type;
  92465. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  92466. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  92467. return texture;
  92468. };
  92469. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  92470. texture.samplingMode = samplingMode;
  92471. };
  92472. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  92473. if (this._currentRenderTarget) {
  92474. this.unBindFramebuffer(this._currentRenderTarget);
  92475. }
  92476. this._currentRenderTarget = texture;
  92477. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  92478. if (this._cachedViewport && !forceFullscreenViewport) {
  92479. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  92480. }
  92481. };
  92482. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  92483. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  92484. this._currentRenderTarget = null;
  92485. if (onBeforeUnbind) {
  92486. if (texture._MSAAFramebuffer) {
  92487. this._currentFramebuffer = texture._framebuffer;
  92488. }
  92489. onBeforeUnbind();
  92490. }
  92491. this._currentFramebuffer = null;
  92492. };
  92493. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  92494. var vbo = {
  92495. capacity: 1,
  92496. references: 1,
  92497. is32Bits: false
  92498. };
  92499. return vbo;
  92500. };
  92501. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  92502. if (offset === void 0) { offset = 0; }
  92503. };
  92504. /**
  92505. * Updates a dynamic vertex buffer.
  92506. * @param vertexBuffer the vertex buffer to update
  92507. * @param data the data used to update the vertex buffer
  92508. * @param byteOffset the byte offset of the data (optional)
  92509. * @param byteLength the byte length of the data (optional)
  92510. */
  92511. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  92512. };
  92513. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  92514. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  92515. this._boundTexturesCache[this._activeChannel] = texture;
  92516. }
  92517. };
  92518. NullEngine.prototype._bindTexture = function (channel, texture) {
  92519. if (channel < 0) {
  92520. return;
  92521. }
  92522. this._bindTextureDirectly(0, texture);
  92523. };
  92524. NullEngine.prototype._releaseBuffer = function (buffer) {
  92525. buffer.references--;
  92526. if (buffer.references === 0) {
  92527. return true;
  92528. }
  92529. return false;
  92530. };
  92531. return NullEngine;
  92532. }(BABYLON.Engine));
  92533. BABYLON.NullEngine = NullEngine;
  92534. })(BABYLON || (BABYLON = {}));
  92535. //# sourceMappingURL=babylon.nullEngine.js.map
  92536. "use strict";
  92537. var BABYLON;
  92538. (function (BABYLON) {
  92539. /**
  92540. * This class can be used to get instrumentation data from a Babylon engine
  92541. */
  92542. var EngineInstrumentation = /** @class */ (function () {
  92543. function EngineInstrumentation(engine) {
  92544. this.engine = engine;
  92545. this._captureGPUFrameTime = false;
  92546. this._gpuFrameTime = new BABYLON.PerfCounter();
  92547. this._captureShaderCompilationTime = false;
  92548. this._shaderCompilationTime = new BABYLON.PerfCounter();
  92549. // Observers
  92550. this._onBeginFrameObserver = null;
  92551. this._onEndFrameObserver = null;
  92552. this._onBeforeShaderCompilationObserver = null;
  92553. this._onAfterShaderCompilationObserver = null;
  92554. }
  92555. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  92556. // Properties
  92557. /**
  92558. * Gets the perf counter used for GPU frame time
  92559. */
  92560. get: function () {
  92561. return this._gpuFrameTime;
  92562. },
  92563. enumerable: true,
  92564. configurable: true
  92565. });
  92566. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  92567. /**
  92568. * Gets the GPU frame time capture status
  92569. */
  92570. get: function () {
  92571. return this._captureGPUFrameTime;
  92572. },
  92573. /**
  92574. * Enable or disable the GPU frame time capture
  92575. */
  92576. set: function (value) {
  92577. var _this = this;
  92578. if (value === this._captureGPUFrameTime) {
  92579. return;
  92580. }
  92581. this._captureGPUFrameTime = value;
  92582. if (value) {
  92583. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  92584. if (!_this._gpuFrameTimeToken) {
  92585. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  92586. }
  92587. });
  92588. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  92589. if (!_this._gpuFrameTimeToken) {
  92590. return;
  92591. }
  92592. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  92593. if (time > -1) {
  92594. _this._gpuFrameTimeToken = null;
  92595. _this._gpuFrameTime.fetchNewFrame();
  92596. _this._gpuFrameTime.addCount(time, true);
  92597. }
  92598. });
  92599. }
  92600. else {
  92601. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  92602. this._onBeginFrameObserver = null;
  92603. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  92604. this._onEndFrameObserver = null;
  92605. }
  92606. },
  92607. enumerable: true,
  92608. configurable: true
  92609. });
  92610. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  92611. /**
  92612. * Gets the perf counter used for shader compilation time
  92613. */
  92614. get: function () {
  92615. return this._shaderCompilationTime;
  92616. },
  92617. enumerable: true,
  92618. configurable: true
  92619. });
  92620. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  92621. /**
  92622. * Gets the shader compilation time capture status
  92623. */
  92624. get: function () {
  92625. return this._captureShaderCompilationTime;
  92626. },
  92627. /**
  92628. * Enable or disable the shader compilation time capture
  92629. */
  92630. set: function (value) {
  92631. var _this = this;
  92632. if (value === this._captureShaderCompilationTime) {
  92633. return;
  92634. }
  92635. this._captureShaderCompilationTime = value;
  92636. if (value) {
  92637. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  92638. _this._shaderCompilationTime.fetchNewFrame();
  92639. _this._shaderCompilationTime.beginMonitoring();
  92640. });
  92641. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  92642. _this._shaderCompilationTime.endMonitoring();
  92643. });
  92644. }
  92645. else {
  92646. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  92647. this._onBeforeShaderCompilationObserver = null;
  92648. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  92649. this._onAfterShaderCompilationObserver = null;
  92650. }
  92651. },
  92652. enumerable: true,
  92653. configurable: true
  92654. });
  92655. EngineInstrumentation.prototype.dispose = function () {
  92656. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  92657. this._onBeginFrameObserver = null;
  92658. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  92659. this._onEndFrameObserver = null;
  92660. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  92661. this._onBeforeShaderCompilationObserver = null;
  92662. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  92663. this._onAfterShaderCompilationObserver = null;
  92664. this.engine = null;
  92665. };
  92666. return EngineInstrumentation;
  92667. }());
  92668. BABYLON.EngineInstrumentation = EngineInstrumentation;
  92669. })(BABYLON || (BABYLON = {}));
  92670. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  92671. "use strict";
  92672. var BABYLON;
  92673. (function (BABYLON) {
  92674. /**
  92675. * This class can be used to get instrumentation data from a Babylon engine
  92676. */
  92677. var SceneInstrumentation = /** @class */ (function () {
  92678. function SceneInstrumentation(scene) {
  92679. var _this = this;
  92680. this.scene = scene;
  92681. this._captureActiveMeshesEvaluationTime = false;
  92682. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  92683. this._captureRenderTargetsRenderTime = false;
  92684. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  92685. this._captureFrameTime = false;
  92686. this._frameTime = new BABYLON.PerfCounter();
  92687. this._captureRenderTime = false;
  92688. this._renderTime = new BABYLON.PerfCounter();
  92689. this._captureInterFrameTime = false;
  92690. this._interFrameTime = new BABYLON.PerfCounter();
  92691. this._captureParticlesRenderTime = false;
  92692. this._particlesRenderTime = new BABYLON.PerfCounter();
  92693. this._captureSpritesRenderTime = false;
  92694. this._spritesRenderTime = new BABYLON.PerfCounter();
  92695. this._capturePhysicsTime = false;
  92696. this._physicsTime = new BABYLON.PerfCounter();
  92697. this._captureAnimationsTime = false;
  92698. this._animationsTime = new BABYLON.PerfCounter();
  92699. // Observers
  92700. this._onBeforeActiveMeshesEvaluationObserver = null;
  92701. this._onAfterActiveMeshesEvaluationObserver = null;
  92702. this._onBeforeRenderTargetsRenderObserver = null;
  92703. this._onAfterRenderTargetsRenderObserver = null;
  92704. this._onAfterRenderObserver = null;
  92705. this._onBeforeDrawPhaseObserver = null;
  92706. this._onAfterDrawPhaseObserver = null;
  92707. this._onBeforeAnimationsObserver = null;
  92708. this._onBeforeParticlesRenderingObserver = null;
  92709. this._onAfterParticlesRenderingObserver = null;
  92710. this._onBeforeSpritesRenderingObserver = null;
  92711. this._onAfterSpritesRenderingObserver = null;
  92712. this._onBeforePhysicsObserver = null;
  92713. this._onAfterPhysicsObserver = null;
  92714. this._onAfterAnimationsObserver = null;
  92715. // Before render
  92716. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  92717. if (_this._captureActiveMeshesEvaluationTime) {
  92718. _this._activeMeshesEvaluationTime.fetchNewFrame();
  92719. }
  92720. if (_this._captureRenderTargetsRenderTime) {
  92721. _this._renderTargetsRenderTime.fetchNewFrame();
  92722. }
  92723. if (_this._captureFrameTime) {
  92724. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  92725. _this._frameTime.beginMonitoring();
  92726. }
  92727. if (_this._captureInterFrameTime) {
  92728. _this._interFrameTime.endMonitoring();
  92729. }
  92730. if (_this._captureParticlesRenderTime) {
  92731. _this._particlesRenderTime.fetchNewFrame();
  92732. }
  92733. if (_this._captureSpritesRenderTime) {
  92734. _this._spritesRenderTime.fetchNewFrame();
  92735. }
  92736. if (_this._captureAnimationsTime) {
  92737. _this._animationsTime.beginMonitoring();
  92738. }
  92739. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  92740. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  92741. });
  92742. // After render
  92743. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  92744. if (_this._captureFrameTime) {
  92745. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  92746. _this._frameTime.endMonitoring();
  92747. }
  92748. if (_this._captureRenderTime) {
  92749. _this._renderTime.endMonitoring(false);
  92750. }
  92751. if (_this._captureInterFrameTime) {
  92752. _this._interFrameTime.beginMonitoring();
  92753. }
  92754. });
  92755. }
  92756. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  92757. // Properties
  92758. /**
  92759. * Gets the perf counter used for active meshes evaluation time
  92760. */
  92761. get: function () {
  92762. return this._activeMeshesEvaluationTime;
  92763. },
  92764. enumerable: true,
  92765. configurable: true
  92766. });
  92767. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  92768. /**
  92769. * Gets the active meshes evaluation time capture status
  92770. */
  92771. get: function () {
  92772. return this._captureActiveMeshesEvaluationTime;
  92773. },
  92774. /**
  92775. * Enable or disable the active meshes evaluation time capture
  92776. */
  92777. set: function (value) {
  92778. var _this = this;
  92779. if (value === this._captureActiveMeshesEvaluationTime) {
  92780. return;
  92781. }
  92782. this._captureActiveMeshesEvaluationTime = value;
  92783. if (value) {
  92784. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  92785. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  92786. _this._activeMeshesEvaluationTime.beginMonitoring();
  92787. });
  92788. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  92789. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  92790. _this._activeMeshesEvaluationTime.endMonitoring();
  92791. });
  92792. }
  92793. else {
  92794. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  92795. this._onBeforeActiveMeshesEvaluationObserver = null;
  92796. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  92797. this._onAfterActiveMeshesEvaluationObserver = null;
  92798. }
  92799. },
  92800. enumerable: true,
  92801. configurable: true
  92802. });
  92803. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  92804. /**
  92805. * Gets the perf counter used for render targets render time
  92806. */
  92807. get: function () {
  92808. return this._renderTargetsRenderTime;
  92809. },
  92810. enumerable: true,
  92811. configurable: true
  92812. });
  92813. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  92814. /**
  92815. * Gets the render targets render time capture status
  92816. */
  92817. get: function () {
  92818. return this._captureRenderTargetsRenderTime;
  92819. },
  92820. /**
  92821. * Enable or disable the render targets render time capture
  92822. */
  92823. set: function (value) {
  92824. var _this = this;
  92825. if (value === this._captureRenderTargetsRenderTime) {
  92826. return;
  92827. }
  92828. this._captureRenderTargetsRenderTime = value;
  92829. if (value) {
  92830. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  92831. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  92832. _this._renderTargetsRenderTime.beginMonitoring();
  92833. });
  92834. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  92835. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  92836. _this._renderTargetsRenderTime.endMonitoring(false);
  92837. });
  92838. }
  92839. else {
  92840. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  92841. this._onBeforeRenderTargetsRenderObserver = null;
  92842. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  92843. this._onAfterRenderTargetsRenderObserver = null;
  92844. }
  92845. },
  92846. enumerable: true,
  92847. configurable: true
  92848. });
  92849. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  92850. /**
  92851. * Gets the perf counter used for particles render time
  92852. */
  92853. get: function () {
  92854. return this._particlesRenderTime;
  92855. },
  92856. enumerable: true,
  92857. configurable: true
  92858. });
  92859. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  92860. /**
  92861. * Gets the particles render time capture status
  92862. */
  92863. get: function () {
  92864. return this._captureParticlesRenderTime;
  92865. },
  92866. /**
  92867. * Enable or disable the particles render time capture
  92868. */
  92869. set: function (value) {
  92870. var _this = this;
  92871. if (value === this._captureParticlesRenderTime) {
  92872. return;
  92873. }
  92874. this._captureParticlesRenderTime = value;
  92875. if (value) {
  92876. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  92877. BABYLON.Tools.StartPerformanceCounter("Particles");
  92878. _this._particlesRenderTime.beginMonitoring();
  92879. });
  92880. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  92881. BABYLON.Tools.EndPerformanceCounter("Particles");
  92882. _this._particlesRenderTime.endMonitoring(false);
  92883. });
  92884. }
  92885. else {
  92886. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  92887. this._onBeforeParticlesRenderingObserver = null;
  92888. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  92889. this._onAfterParticlesRenderingObserver = null;
  92890. }
  92891. },
  92892. enumerable: true,
  92893. configurable: true
  92894. });
  92895. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  92896. /**
  92897. * Gets the perf counter used for sprites render time
  92898. */
  92899. get: function () {
  92900. return this._spritesRenderTime;
  92901. },
  92902. enumerable: true,
  92903. configurable: true
  92904. });
  92905. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  92906. /**
  92907. * Gets the sprites render time capture status
  92908. */
  92909. get: function () {
  92910. return this._captureSpritesRenderTime;
  92911. },
  92912. /**
  92913. * Enable or disable the sprites render time capture
  92914. */
  92915. set: function (value) {
  92916. var _this = this;
  92917. if (value === this._captureSpritesRenderTime) {
  92918. return;
  92919. }
  92920. this._captureSpritesRenderTime = value;
  92921. if (value) {
  92922. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  92923. BABYLON.Tools.StartPerformanceCounter("Sprites");
  92924. _this._spritesRenderTime.beginMonitoring();
  92925. });
  92926. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  92927. BABYLON.Tools.EndPerformanceCounter("Sprites");
  92928. _this._spritesRenderTime.endMonitoring(false);
  92929. });
  92930. }
  92931. else {
  92932. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  92933. this._onBeforeSpritesRenderingObserver = null;
  92934. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  92935. this._onAfterSpritesRenderingObserver = null;
  92936. }
  92937. },
  92938. enumerable: true,
  92939. configurable: true
  92940. });
  92941. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  92942. /**
  92943. * Gets the perf counter used for physics time
  92944. */
  92945. get: function () {
  92946. return this._physicsTime;
  92947. },
  92948. enumerable: true,
  92949. configurable: true
  92950. });
  92951. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  92952. /**
  92953. * Gets the physics time capture status
  92954. */
  92955. get: function () {
  92956. return this._capturePhysicsTime;
  92957. },
  92958. /**
  92959. * Enable or disable the physics time capture
  92960. */
  92961. set: function (value) {
  92962. var _this = this;
  92963. if (value === this._capturePhysicsTime) {
  92964. return;
  92965. }
  92966. this._capturePhysicsTime = value;
  92967. if (value) {
  92968. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  92969. BABYLON.Tools.StartPerformanceCounter("Physics");
  92970. _this._physicsTime.beginMonitoring();
  92971. });
  92972. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  92973. BABYLON.Tools.EndPerformanceCounter("Physics");
  92974. _this._physicsTime.endMonitoring();
  92975. });
  92976. }
  92977. else {
  92978. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  92979. this._onBeforePhysicsObserver = null;
  92980. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  92981. this._onAfterPhysicsObserver = null;
  92982. }
  92983. },
  92984. enumerable: true,
  92985. configurable: true
  92986. });
  92987. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  92988. /**
  92989. * Gets the perf counter used for animations time
  92990. */
  92991. get: function () {
  92992. return this._animationsTime;
  92993. },
  92994. enumerable: true,
  92995. configurable: true
  92996. });
  92997. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  92998. /**
  92999. * Gets the animations time capture status
  93000. */
  93001. get: function () {
  93002. return this._captureAnimationsTime;
  93003. },
  93004. /**
  93005. * Enable or disable the animations time capture
  93006. */
  93007. set: function (value) {
  93008. var _this = this;
  93009. if (value === this._captureAnimationsTime) {
  93010. return;
  93011. }
  93012. this._captureAnimationsTime = value;
  93013. if (value) {
  93014. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  93015. _this._animationsTime.endMonitoring();
  93016. });
  93017. }
  93018. else {
  93019. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93020. this._onAfterAnimationsObserver = null;
  93021. }
  93022. },
  93023. enumerable: true,
  93024. configurable: true
  93025. });
  93026. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  93027. /**
  93028. * Gets the perf counter used for frame time capture
  93029. */
  93030. get: function () {
  93031. return this._frameTime;
  93032. },
  93033. enumerable: true,
  93034. configurable: true
  93035. });
  93036. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  93037. /**
  93038. * Gets the frame time capture status
  93039. */
  93040. get: function () {
  93041. return this._captureFrameTime;
  93042. },
  93043. /**
  93044. * Enable or disable the frame time capture
  93045. */
  93046. set: function (value) {
  93047. this._captureFrameTime = value;
  93048. },
  93049. enumerable: true,
  93050. configurable: true
  93051. });
  93052. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  93053. /**
  93054. * Gets the perf counter used for inter-frames time capture
  93055. */
  93056. get: function () {
  93057. return this._interFrameTime;
  93058. },
  93059. enumerable: true,
  93060. configurable: true
  93061. });
  93062. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  93063. /**
  93064. * Gets the inter-frames time capture status
  93065. */
  93066. get: function () {
  93067. return this._captureInterFrameTime;
  93068. },
  93069. /**
  93070. * Enable or disable the inter-frames time capture
  93071. */
  93072. set: function (value) {
  93073. this._captureInterFrameTime = value;
  93074. },
  93075. enumerable: true,
  93076. configurable: true
  93077. });
  93078. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  93079. /**
  93080. * Gets the perf counter used for render time capture
  93081. */
  93082. get: function () {
  93083. return this._renderTime;
  93084. },
  93085. enumerable: true,
  93086. configurable: true
  93087. });
  93088. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  93089. /**
  93090. * Gets the render time capture status
  93091. */
  93092. get: function () {
  93093. return this._captureRenderTime;
  93094. },
  93095. /**
  93096. * Enable or disable the render time capture
  93097. */
  93098. set: function (value) {
  93099. var _this = this;
  93100. if (value === this._captureRenderTime) {
  93101. return;
  93102. }
  93103. this._captureRenderTime = value;
  93104. if (value) {
  93105. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  93106. _this._renderTime.beginMonitoring();
  93107. BABYLON.Tools.StartPerformanceCounter("Main render");
  93108. });
  93109. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  93110. _this._renderTime.endMonitoring(false);
  93111. BABYLON.Tools.EndPerformanceCounter("Main render");
  93112. });
  93113. }
  93114. else {
  93115. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93116. this._onBeforeDrawPhaseObserver = null;
  93117. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93118. this._onAfterDrawPhaseObserver = null;
  93119. }
  93120. },
  93121. enumerable: true,
  93122. configurable: true
  93123. });
  93124. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  93125. /**
  93126. * Gets the perf counter used for draw calls
  93127. */
  93128. get: function () {
  93129. return this.scene.getEngine()._drawCalls;
  93130. },
  93131. enumerable: true,
  93132. configurable: true
  93133. });
  93134. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  93135. /**
  93136. * Gets the perf counter used for texture collisions
  93137. */
  93138. get: function () {
  93139. return this.scene.getEngine()._textureCollisions;
  93140. },
  93141. enumerable: true,
  93142. configurable: true
  93143. });
  93144. SceneInstrumentation.prototype.dispose = function () {
  93145. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93146. this._onAfterRenderObserver = null;
  93147. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93148. this._onBeforeActiveMeshesEvaluationObserver = null;
  93149. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93150. this._onAfterActiveMeshesEvaluationObserver = null;
  93151. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93152. this._onBeforeRenderTargetsRenderObserver = null;
  93153. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93154. this._onAfterRenderTargetsRenderObserver = null;
  93155. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  93156. this._onBeforeAnimationsObserver = null;
  93157. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  93158. this._onBeforeParticlesRenderingObserver = null;
  93159. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  93160. this._onAfterParticlesRenderingObserver = null;
  93161. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93162. this._onBeforeSpritesRenderingObserver = null;
  93163. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93164. this._onAfterSpritesRenderingObserver = null;
  93165. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93166. this._onBeforeDrawPhaseObserver = null;
  93167. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93168. this._onAfterDrawPhaseObserver = null;
  93169. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93170. this._onBeforePhysicsObserver = null;
  93171. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93172. this._onAfterPhysicsObserver = null;
  93173. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93174. this._onAfterAnimationsObserver = null;
  93175. this.scene = null;
  93176. };
  93177. return SceneInstrumentation;
  93178. }());
  93179. BABYLON.SceneInstrumentation = SceneInstrumentation;
  93180. })(BABYLON || (BABYLON = {}));
  93181. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  93182. "use strict";
  93183. var BABYLON;
  93184. (function (BABYLON) {
  93185. var _TimeToken = /** @class */ (function () {
  93186. function _TimeToken() {
  93187. this._timeElapsedQueryEnded = false;
  93188. }
  93189. return _TimeToken;
  93190. }());
  93191. BABYLON._TimeToken = _TimeToken;
  93192. })(BABYLON || (BABYLON = {}));
  93193. //# sourceMappingURL=babylon.timeToken.js.map
  93194. "use strict";
  93195. var BABYLON;
  93196. (function (BABYLON) {
  93197. /**
  93198. * Background material defines definition.
  93199. * @ignore Mainly internal Use
  93200. */
  93201. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  93202. __extends(BackgroundMaterialDefines, _super);
  93203. /**
  93204. * Constructor of the defines.
  93205. */
  93206. function BackgroundMaterialDefines() {
  93207. var _this = _super.call(this) || this;
  93208. /**
  93209. * True if the diffuse texture is in use.
  93210. */
  93211. _this.DIFFUSE = false;
  93212. /**
  93213. * The direct UV channel to use.
  93214. */
  93215. _this.DIFFUSEDIRECTUV = 0;
  93216. /**
  93217. * True if the diffuse texture is in gamma space.
  93218. */
  93219. _this.GAMMADIFFUSE = false;
  93220. /**
  93221. * True if the diffuse texture has opacity in the alpha channel.
  93222. */
  93223. _this.DIFFUSEHASALPHA = false;
  93224. /**
  93225. * True if you want the material to fade to transparent at grazing angle.
  93226. */
  93227. _this.OPACITYFRESNEL = false;
  93228. /**
  93229. * True if an extra blur needs to be added in the reflection.
  93230. */
  93231. _this.REFLECTIONBLUR = false;
  93232. /**
  93233. * True if you want the material to fade to reflection at grazing angle.
  93234. */
  93235. _this.REFLECTIONFRESNEL = false;
  93236. /**
  93237. * True if you want the material to falloff as far as you move away from the scene center.
  93238. */
  93239. _this.REFLECTIONFALLOFF = false;
  93240. /**
  93241. * False if the current Webgl implementation does not support the texture lod extension.
  93242. */
  93243. _this.TEXTURELODSUPPORT = false;
  93244. /**
  93245. * True to ensure the data are premultiplied.
  93246. */
  93247. _this.PREMULTIPLYALPHA = false;
  93248. /**
  93249. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  93250. */
  93251. _this.USERGBCOLOR = false;
  93252. /**
  93253. * True to add noise in order to reduce the banding effect.
  93254. */
  93255. _this.NOISE = false;
  93256. /**
  93257. * is the reflection texture in BGR color scheme?
  93258. * Mainly used to solve a bug in ios10 video tag
  93259. */
  93260. _this.REFLECTIONBGR = false;
  93261. _this.IMAGEPROCESSING = false;
  93262. _this.VIGNETTE = false;
  93263. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  93264. _this.VIGNETTEBLENDMODEOPAQUE = false;
  93265. _this.TONEMAPPING = false;
  93266. _this.CONTRAST = false;
  93267. _this.COLORCURVES = false;
  93268. _this.COLORGRADING = false;
  93269. _this.COLORGRADING3D = false;
  93270. _this.SAMPLER3DGREENDEPTH = false;
  93271. _this.SAMPLER3DBGRMAP = false;
  93272. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  93273. _this.EXPOSURE = false;
  93274. // Reflection.
  93275. _this.REFLECTION = false;
  93276. _this.REFLECTIONMAP_3D = false;
  93277. _this.REFLECTIONMAP_SPHERICAL = false;
  93278. _this.REFLECTIONMAP_PLANAR = false;
  93279. _this.REFLECTIONMAP_CUBIC = false;
  93280. _this.REFLECTIONMAP_PROJECTION = false;
  93281. _this.REFLECTIONMAP_SKYBOX = false;
  93282. _this.REFLECTIONMAP_EXPLICIT = false;
  93283. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  93284. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  93285. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  93286. _this.INVERTCUBICMAP = false;
  93287. _this.REFLECTIONMAP_OPPOSITEZ = false;
  93288. _this.LODINREFLECTIONALPHA = false;
  93289. _this.GAMMAREFLECTION = false;
  93290. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  93291. // Default BJS.
  93292. _this.MAINUV1 = false;
  93293. _this.MAINUV2 = false;
  93294. _this.UV1 = false;
  93295. _this.UV2 = false;
  93296. _this.CLIPPLANE = false;
  93297. _this.POINTSIZE = false;
  93298. _this.FOG = false;
  93299. _this.NORMAL = false;
  93300. _this.NUM_BONE_INFLUENCERS = 0;
  93301. _this.BonesPerMesh = 0;
  93302. _this.INSTANCES = false;
  93303. _this.SHADOWFLOAT = false;
  93304. _this.rebuild();
  93305. return _this;
  93306. }
  93307. return BackgroundMaterialDefines;
  93308. }(BABYLON.MaterialDefines));
  93309. /**
  93310. * Background material used to create an efficient environement around your scene.
  93311. */
  93312. var BackgroundMaterial = /** @class */ (function (_super) {
  93313. __extends(BackgroundMaterial, _super);
  93314. /**
  93315. * Instantiates a Background Material in the given scene
  93316. * @param name The friendly name of the material
  93317. * @param scene The scene to add the material to
  93318. */
  93319. function BackgroundMaterial(name, scene) {
  93320. var _this = _super.call(this, name, scene) || this;
  93321. /**
  93322. * Key light Color (multiply against the R channel of the environement texture)
  93323. */
  93324. _this.primaryColor = BABYLON.Color3.White();
  93325. /**
  93326. * Key light Level (allowing HDR output of the background)
  93327. */
  93328. _this.primaryLevel = 1;
  93329. /**
  93330. * Secondary light Color (multiply against the G channel of the environement texture)
  93331. */
  93332. _this.secondaryColor = BABYLON.Color3.Gray();
  93333. /**
  93334. * Secondary light Level (allowing HDR output of the background)
  93335. */
  93336. _this.secondaryLevel = 1;
  93337. /**
  93338. * Tertiary light Color (multiply against the B channel of the environement texture)
  93339. */
  93340. _this.tertiaryColor = BABYLON.Color3.Black();
  93341. /**
  93342. * Tertiary light Level (allowing HDR output of the background)
  93343. */
  93344. _this.tertiaryLevel = 1;
  93345. /**
  93346. * Reflection Texture used in the material.
  93347. * Should be author in a specific way for the best result (refer to the documentation).
  93348. */
  93349. _this.reflectionTexture = null;
  93350. /**
  93351. * Reflection Texture level of blur.
  93352. *
  93353. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  93354. * texture twice.
  93355. */
  93356. _this.reflectionBlur = 0;
  93357. /**
  93358. * Diffuse Texture used in the material.
  93359. * Should be author in a specific way for the best result (refer to the documentation).
  93360. */
  93361. _this.diffuseTexture = null;
  93362. _this._shadowLights = null;
  93363. /**
  93364. * Specify the list of lights casting shadow on the material.
  93365. * All scene shadow lights will be included if null.
  93366. */
  93367. _this.shadowLights = null;
  93368. /**
  93369. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  93370. * soft lighting on the background.
  93371. */
  93372. _this.shadowBlurScale = 1;
  93373. /**
  93374. * Helps adjusting the shadow to a softer level if required.
  93375. * 0 means black shadows and 1 means no shadows.
  93376. */
  93377. _this.shadowLevel = 0;
  93378. /**
  93379. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  93380. * It is usually zero but might be interesting to modify according to your setup.
  93381. */
  93382. _this.sceneCenter = BABYLON.Vector3.Zero();
  93383. /**
  93384. * This helps specifying that the material is falling off to the sky box at grazing angle.
  93385. * This helps ensuring a nice transition when the camera goes under the ground.
  93386. */
  93387. _this.opacityFresnel = true;
  93388. /**
  93389. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  93390. * This helps adding a mirror texture on the ground.
  93391. */
  93392. _this.reflectionFresnel = false;
  93393. /**
  93394. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  93395. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  93396. */
  93397. _this.reflectionFalloffDistance = 0.0;
  93398. /**
  93399. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  93400. */
  93401. _this.reflectionAmount = 1.0;
  93402. /**
  93403. * This specifies the weight of the reflection at grazing angle.
  93404. */
  93405. _this.reflectionReflectance0 = 0.05;
  93406. /**
  93407. * This specifies the weight of the reflection at a perpendicular point of view.
  93408. */
  93409. _this.reflectionReflectance90 = 0.5;
  93410. /**
  93411. * Helps to directly use the maps channels instead of their level.
  93412. */
  93413. _this.useRGBColor = true;
  93414. /**
  93415. * This helps reducing the banding effect that could occur on the background.
  93416. */
  93417. _this.enableNoise = false;
  93418. _this._fovMultiplier = 1.0;
  93419. /**
  93420. * Enable the FOV adjustment feature controlled by fovMultiplier.
  93421. */
  93422. _this.useEquirectangularFOV = false;
  93423. _this._maxSimultaneousLights = 4;
  93424. /**
  93425. * Number of Simultaneous lights allowed on the material.
  93426. */
  93427. _this.maxSimultaneousLights = 4;
  93428. /**
  93429. * Keep track of the image processing observer to allow dispose and replace.
  93430. */
  93431. _this._imageProcessingObserver = null;
  93432. /**
  93433. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  93434. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  93435. */
  93436. _this.switchToBGR = false;
  93437. // Temp values kept as cache in the material.
  93438. _this._renderTargets = new BABYLON.SmartArray(16);
  93439. _this._reflectionControls = BABYLON.Vector4.Zero();
  93440. // Setup the default processing configuration to the scene.
  93441. _this._attachImageProcessingConfiguration(null);
  93442. _this.getRenderTargetTextures = function () {
  93443. _this._renderTargets.reset();
  93444. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  93445. _this._renderTargets.push(_this._diffuseTexture);
  93446. }
  93447. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  93448. _this._renderTargets.push(_this._reflectionTexture);
  93449. }
  93450. return _this._renderTargets;
  93451. };
  93452. return _this;
  93453. }
  93454. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  93455. /**
  93456. * Sets the reflection reflectance fresnel values according to the default standard
  93457. * empirically know to work well :-)
  93458. */
  93459. set: function (value) {
  93460. var reflectionWeight = value;
  93461. if (reflectionWeight < 0.5) {
  93462. reflectionWeight = reflectionWeight * 2.0;
  93463. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  93464. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  93465. }
  93466. else {
  93467. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  93468. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  93469. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  93470. }
  93471. },
  93472. enumerable: true,
  93473. configurable: true
  93474. });
  93475. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  93476. /**
  93477. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  93478. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  93479. * Recommended to be keep at 1.0 except for special cases.
  93480. */
  93481. get: function () {
  93482. return this._fovMultiplier;
  93483. },
  93484. set: function (value) {
  93485. if (isNaN(value)) {
  93486. value = 1.0;
  93487. }
  93488. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  93489. },
  93490. enumerable: true,
  93491. configurable: true
  93492. });
  93493. /**
  93494. * Attaches a new image processing configuration to the PBR Material.
  93495. * @param configuration (if null the scene configuration will be use)
  93496. */
  93497. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  93498. var _this = this;
  93499. if (configuration === this._imageProcessingConfiguration) {
  93500. return;
  93501. }
  93502. // Detaches observer.
  93503. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  93504. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  93505. }
  93506. // Pick the scene configuration if needed.
  93507. if (!configuration) {
  93508. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  93509. }
  93510. else {
  93511. this._imageProcessingConfiguration = configuration;
  93512. }
  93513. // Attaches observer.
  93514. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  93515. _this._markAllSubMeshesAsImageProcessingDirty();
  93516. });
  93517. };
  93518. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  93519. /**
  93520. * Gets the image processing configuration used either in this material.
  93521. */
  93522. get: function () {
  93523. return this._imageProcessingConfiguration;
  93524. },
  93525. /**
  93526. * Sets the Default image processing configuration used either in the this material.
  93527. *
  93528. * If sets to null, the scene one is in use.
  93529. */
  93530. set: function (value) {
  93531. this._attachImageProcessingConfiguration(value);
  93532. // Ensure the effect will be rebuilt.
  93533. this._markAllSubMeshesAsTexturesDirty();
  93534. },
  93535. enumerable: true,
  93536. configurable: true
  93537. });
  93538. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  93539. /**
  93540. * Gets wether the color curves effect is enabled.
  93541. */
  93542. get: function () {
  93543. return this.imageProcessingConfiguration.colorCurvesEnabled;
  93544. },
  93545. /**
  93546. * Sets wether the color curves effect is enabled.
  93547. */
  93548. set: function (value) {
  93549. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  93550. },
  93551. enumerable: true,
  93552. configurable: true
  93553. });
  93554. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  93555. /**
  93556. * Gets wether the color grading effect is enabled.
  93557. */
  93558. get: function () {
  93559. return this.imageProcessingConfiguration.colorGradingEnabled;
  93560. },
  93561. /**
  93562. * Gets wether the color grading effect is enabled.
  93563. */
  93564. set: function (value) {
  93565. this.imageProcessingConfiguration.colorGradingEnabled = value;
  93566. },
  93567. enumerable: true,
  93568. configurable: true
  93569. });
  93570. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  93571. /**
  93572. * Gets wether tonemapping is enabled or not.
  93573. */
  93574. get: function () {
  93575. return this._imageProcessingConfiguration.toneMappingEnabled;
  93576. },
  93577. /**
  93578. * Sets wether tonemapping is enabled or not
  93579. */
  93580. set: function (value) {
  93581. this._imageProcessingConfiguration.toneMappingEnabled = value;
  93582. },
  93583. enumerable: true,
  93584. configurable: true
  93585. });
  93586. ;
  93587. ;
  93588. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  93589. /**
  93590. * The camera exposure used on this material.
  93591. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  93592. * This corresponds to a photographic exposure.
  93593. */
  93594. get: function () {
  93595. return this._imageProcessingConfiguration.exposure;
  93596. },
  93597. /**
  93598. * The camera exposure used on this material.
  93599. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  93600. * This corresponds to a photographic exposure.
  93601. */
  93602. set: function (value) {
  93603. this._imageProcessingConfiguration.exposure = value;
  93604. },
  93605. enumerable: true,
  93606. configurable: true
  93607. });
  93608. ;
  93609. ;
  93610. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  93611. /**
  93612. * Gets The camera contrast used on this material.
  93613. */
  93614. get: function () {
  93615. return this._imageProcessingConfiguration.contrast;
  93616. },
  93617. /**
  93618. * Sets The camera contrast used on this material.
  93619. */
  93620. set: function (value) {
  93621. this._imageProcessingConfiguration.contrast = value;
  93622. },
  93623. enumerable: true,
  93624. configurable: true
  93625. });
  93626. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  93627. /**
  93628. * Gets the Color Grading 2D Lookup Texture.
  93629. */
  93630. get: function () {
  93631. return this._imageProcessingConfiguration.colorGradingTexture;
  93632. },
  93633. /**
  93634. * Sets the Color Grading 2D Lookup Texture.
  93635. */
  93636. set: function (value) {
  93637. this.imageProcessingConfiguration.colorGradingTexture = value;
  93638. },
  93639. enumerable: true,
  93640. configurable: true
  93641. });
  93642. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  93643. /**
  93644. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  93645. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  93646. * 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;
  93647. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  93648. */
  93649. get: function () {
  93650. return this.imageProcessingConfiguration.colorCurves;
  93651. },
  93652. /**
  93653. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  93654. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  93655. * 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;
  93656. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  93657. */
  93658. set: function (value) {
  93659. this.imageProcessingConfiguration.colorCurves = value;
  93660. },
  93661. enumerable: true,
  93662. configurable: true
  93663. });
  93664. /**
  93665. * The entire material has been created in order to prevent overdraw.
  93666. * @returns false
  93667. */
  93668. BackgroundMaterial.prototype.needAlphaTesting = function () {
  93669. return true;
  93670. };
  93671. /**
  93672. * The entire material has been created in order to prevent overdraw.
  93673. * @returns true if blending is enable
  93674. */
  93675. BackgroundMaterial.prototype.needAlphaBlending = function () {
  93676. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  93677. };
  93678. /**
  93679. * Checks wether the material is ready to be rendered for a given mesh.
  93680. * @param mesh The mesh to render
  93681. * @param subMesh The submesh to check against
  93682. * @param useInstances Specify wether or not the material is used with instances
  93683. * @returns true if all the dependencies are ready (Textures, Effects...)
  93684. */
  93685. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  93686. var _this = this;
  93687. if (useInstances === void 0) { useInstances = false; }
  93688. if (subMesh.effect && this.isFrozen) {
  93689. if (this._wasPreviouslyReady) {
  93690. return true;
  93691. }
  93692. }
  93693. if (!subMesh._materialDefines) {
  93694. subMesh._materialDefines = new BackgroundMaterialDefines();
  93695. }
  93696. var scene = this.getScene();
  93697. var defines = subMesh._materialDefines;
  93698. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  93699. if (defines._renderId === scene.getRenderId()) {
  93700. return true;
  93701. }
  93702. }
  93703. var engine = scene.getEngine();
  93704. // Lights
  93705. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  93706. defines._needNormals = true;
  93707. // Textures
  93708. if (defines._areTexturesDirty) {
  93709. defines._needUVs = false;
  93710. if (scene.texturesEnabled) {
  93711. if (scene.getEngine().getCaps().textureLOD) {
  93712. defines.TEXTURELODSUPPORT = true;
  93713. }
  93714. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  93715. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  93716. return false;
  93717. }
  93718. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  93719. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  93720. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  93721. defines.OPACITYFRESNEL = this._opacityFresnel;
  93722. }
  93723. else {
  93724. defines.DIFFUSE = false;
  93725. defines.DIFFUSEHASALPHA = false;
  93726. defines.GAMMADIFFUSE = false;
  93727. defines.OPACITYFRESNEL = false;
  93728. }
  93729. var reflectionTexture = this._reflectionTexture;
  93730. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  93731. if (!reflectionTexture.isReadyOrNotBlocking()) {
  93732. return false;
  93733. }
  93734. defines.REFLECTION = true;
  93735. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  93736. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  93737. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  93738. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  93739. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  93740. defines.REFLECTIONBGR = this.switchToBGR;
  93741. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  93742. defines.INVERTCUBICMAP = true;
  93743. }
  93744. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  93745. switch (reflectionTexture.coordinatesMode) {
  93746. case BABYLON.Texture.CUBIC_MODE:
  93747. case BABYLON.Texture.INVCUBIC_MODE:
  93748. defines.REFLECTIONMAP_CUBIC = true;
  93749. break;
  93750. case BABYLON.Texture.EXPLICIT_MODE:
  93751. defines.REFLECTIONMAP_EXPLICIT = true;
  93752. break;
  93753. case BABYLON.Texture.PLANAR_MODE:
  93754. defines.REFLECTIONMAP_PLANAR = true;
  93755. break;
  93756. case BABYLON.Texture.PROJECTION_MODE:
  93757. defines.REFLECTIONMAP_PROJECTION = true;
  93758. break;
  93759. case BABYLON.Texture.SKYBOX_MODE:
  93760. defines.REFLECTIONMAP_SKYBOX = true;
  93761. break;
  93762. case BABYLON.Texture.SPHERICAL_MODE:
  93763. defines.REFLECTIONMAP_SPHERICAL = true;
  93764. break;
  93765. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  93766. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  93767. break;
  93768. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  93769. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  93770. break;
  93771. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  93772. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  93773. break;
  93774. }
  93775. if (this.reflectionFresnel) {
  93776. defines.REFLECTIONFRESNEL = true;
  93777. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  93778. this._reflectionControls.x = this.reflectionAmount;
  93779. this._reflectionControls.y = this.reflectionReflectance0;
  93780. this._reflectionControls.z = this.reflectionReflectance90;
  93781. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  93782. }
  93783. else {
  93784. defines.REFLECTIONFRESNEL = false;
  93785. defines.REFLECTIONFALLOFF = false;
  93786. }
  93787. }
  93788. else {
  93789. defines.REFLECTION = false;
  93790. defines.REFLECTIONFALLOFF = false;
  93791. defines.REFLECTIONBLUR = false;
  93792. defines.REFLECTIONMAP_3D = false;
  93793. defines.REFLECTIONMAP_SPHERICAL = false;
  93794. defines.REFLECTIONMAP_PLANAR = false;
  93795. defines.REFLECTIONMAP_CUBIC = false;
  93796. defines.REFLECTIONMAP_PROJECTION = false;
  93797. defines.REFLECTIONMAP_SKYBOX = false;
  93798. defines.REFLECTIONMAP_EXPLICIT = false;
  93799. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  93800. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  93801. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  93802. defines.INVERTCUBICMAP = false;
  93803. defines.REFLECTIONMAP_OPPOSITEZ = false;
  93804. defines.LODINREFLECTIONALPHA = false;
  93805. defines.GAMMAREFLECTION = false;
  93806. }
  93807. }
  93808. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  93809. defines.USERGBCOLOR = this._useRGBColor;
  93810. defines.NOISE = this._enableNoise;
  93811. }
  93812. if (defines._areImageProcessingDirty) {
  93813. if (!this._imageProcessingConfiguration.isReady()) {
  93814. return false;
  93815. }
  93816. this._imageProcessingConfiguration.prepareDefines(defines);
  93817. }
  93818. // Misc.
  93819. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  93820. // Values that need to be evaluated on every frame
  93821. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  93822. // Attribs
  93823. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  93824. if (mesh) {
  93825. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93826. mesh.createNormals(true);
  93827. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  93828. }
  93829. }
  93830. }
  93831. // Get correct effect
  93832. if (defines.isDirty) {
  93833. defines.markAsProcessed();
  93834. scene.resetCachedMaterial();
  93835. // Fallbacks
  93836. var fallbacks = new BABYLON.EffectFallbacks();
  93837. if (defines.FOG) {
  93838. fallbacks.addFallback(0, "FOG");
  93839. }
  93840. if (defines.POINTSIZE) {
  93841. fallbacks.addFallback(1, "POINTSIZE");
  93842. }
  93843. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  93844. if (defines.NUM_BONE_INFLUENCERS > 0) {
  93845. fallbacks.addCPUSkinningFallback(0, mesh);
  93846. }
  93847. //Attributes
  93848. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93849. if (defines.NORMAL) {
  93850. attribs.push(BABYLON.VertexBuffer.NormalKind);
  93851. }
  93852. if (defines.UV1) {
  93853. attribs.push(BABYLON.VertexBuffer.UVKind);
  93854. }
  93855. if (defines.UV2) {
  93856. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93857. }
  93858. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  93859. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  93860. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  93861. "vFogInfos", "vFogColor", "pointSize",
  93862. "vClipPlane", "mBones",
  93863. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  93864. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  93865. "shadowLevel", "alpha",
  93866. "vBackgroundCenter", "vReflectionControl",
  93867. "vDiffuseInfos", "diffuseMatrix",
  93868. ];
  93869. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  93870. var uniformBuffers = ["Material", "Scene"];
  93871. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  93872. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  93873. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  93874. uniformsNames: uniforms,
  93875. uniformBuffersNames: uniformBuffers,
  93876. samplers: samplers,
  93877. defines: defines,
  93878. maxSimultaneousLights: this._maxSimultaneousLights
  93879. });
  93880. var onCompiled = function (effect) {
  93881. if (_this.onCompiled) {
  93882. _this.onCompiled(effect);
  93883. }
  93884. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  93885. };
  93886. var join = defines.toString();
  93887. subMesh.setEffect(scene.getEngine().createEffect("background", {
  93888. attributes: attribs,
  93889. uniformsNames: uniforms,
  93890. uniformBuffersNames: uniformBuffers,
  93891. samplers: samplers,
  93892. defines: join,
  93893. fallbacks: fallbacks,
  93894. onCompiled: onCompiled,
  93895. onError: this.onError,
  93896. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  93897. }, engine), defines);
  93898. this.buildUniformLayout();
  93899. }
  93900. if (!subMesh.effect || !subMesh.effect.isReady()) {
  93901. return false;
  93902. }
  93903. defines._renderId = scene.getRenderId();
  93904. this._wasPreviouslyReady = true;
  93905. return true;
  93906. };
  93907. /**
  93908. * Build the uniform buffer used in the material.
  93909. */
  93910. BackgroundMaterial.prototype.buildUniformLayout = function () {
  93911. // Order is important !
  93912. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  93913. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  93914. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  93915. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  93916. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  93917. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  93918. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  93919. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  93920. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  93921. this._uniformBuffer.addUniform("pointSize", 1);
  93922. this._uniformBuffer.addUniform("shadowLevel", 1);
  93923. this._uniformBuffer.addUniform("alpha", 1);
  93924. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  93925. this._uniformBuffer.addUniform("vReflectionControl", 4);
  93926. this._uniformBuffer.create();
  93927. };
  93928. /**
  93929. * Unbind the material.
  93930. */
  93931. BackgroundMaterial.prototype.unbind = function () {
  93932. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  93933. this._uniformBuffer.setTexture("diffuseSampler", null);
  93934. }
  93935. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  93936. this._uniformBuffer.setTexture("reflectionSampler", null);
  93937. }
  93938. _super.prototype.unbind.call(this);
  93939. };
  93940. /**
  93941. * Bind only the world matrix to the material.
  93942. * @param world The world matrix to bind.
  93943. */
  93944. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  93945. this._activeEffect.setMatrix("world", world);
  93946. };
  93947. /**
  93948. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  93949. * @param world The world matrix to bind.
  93950. * @param subMesh The submesh to bind for.
  93951. */
  93952. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  93953. var scene = this.getScene();
  93954. var defines = subMesh._materialDefines;
  93955. if (!defines) {
  93956. return;
  93957. }
  93958. var effect = subMesh.effect;
  93959. if (!effect) {
  93960. return;
  93961. }
  93962. this._activeEffect = effect;
  93963. // Matrices
  93964. this.bindOnlyWorldMatrix(world);
  93965. // Bones
  93966. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  93967. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  93968. if (mustRebind) {
  93969. this._uniformBuffer.bindToEffect(effect, "Material");
  93970. this.bindViewProjection(effect);
  93971. var reflectionTexture = this._reflectionTexture;
  93972. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  93973. // Texture uniforms
  93974. if (scene.texturesEnabled) {
  93975. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  93976. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  93977. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  93978. }
  93979. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  93980. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  93981. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  93982. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  93983. }
  93984. }
  93985. if (this.shadowLevel > 0) {
  93986. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  93987. }
  93988. this._uniformBuffer.updateFloat("alpha", this.alpha);
  93989. // Point size
  93990. if (this.pointsCloud) {
  93991. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  93992. }
  93993. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  93994. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  93995. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  93996. }
  93997. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  93998. // Textures
  93999. if (scene.texturesEnabled) {
  94000. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94001. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  94002. }
  94003. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94004. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  94005. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94006. }
  94007. else if (!defines.REFLECTIONBLUR) {
  94008. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94009. }
  94010. else {
  94011. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  94012. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  94013. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  94014. }
  94015. if (defines.REFLECTIONFRESNEL) {
  94016. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  94017. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  94018. }
  94019. }
  94020. }
  94021. // Clip plane
  94022. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  94023. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  94024. }
  94025. if (mustRebind || !this.isFrozen) {
  94026. if (scene.lightsEnabled) {
  94027. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  94028. }
  94029. // View
  94030. this.bindView(effect);
  94031. // Fog
  94032. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  94033. // image processing
  94034. this._imageProcessingConfiguration.bind(this._activeEffect);
  94035. }
  94036. this._uniformBuffer.update();
  94037. this._afterBind(mesh);
  94038. };
  94039. /**
  94040. * Dispose the material.
  94041. * @param forceDisposeEffect Force disposal of the associated effect.
  94042. * @param forceDisposeTextures Force disposal of the associated textures.
  94043. */
  94044. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  94045. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  94046. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  94047. if (forceDisposeTextures) {
  94048. if (this.diffuseTexture) {
  94049. this.diffuseTexture.dispose();
  94050. }
  94051. if (this.reflectionTexture) {
  94052. this.reflectionTexture.dispose();
  94053. }
  94054. }
  94055. this._renderTargets.dispose();
  94056. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94057. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94058. }
  94059. _super.prototype.dispose.call(this, forceDisposeEffect);
  94060. };
  94061. /**
  94062. * Clones the material.
  94063. * @param name The cloned name.
  94064. * @returns The cloned material.
  94065. */
  94066. BackgroundMaterial.prototype.clone = function (name) {
  94067. var _this = this;
  94068. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  94069. };
  94070. /**
  94071. * Serializes the current material to its JSON representation.
  94072. * @returns The JSON representation.
  94073. */
  94074. BackgroundMaterial.prototype.serialize = function () {
  94075. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94076. serializationObject.customType = "BABYLON.BackgroundMaterial";
  94077. return serializationObject;
  94078. };
  94079. /**
  94080. * Gets the class name of the material
  94081. * @returns "BackgroundMaterial"
  94082. */
  94083. BackgroundMaterial.prototype.getClassName = function () {
  94084. return "BackgroundMaterial";
  94085. };
  94086. /**
  94087. * Parse a JSON input to create back a background material.
  94088. * @param source The JSON data to parse
  94089. * @param scene The scene to create the parsed material in
  94090. * @param rootUrl The root url of the assets the material depends upon
  94091. * @returns the instantiated BackgroundMaterial.
  94092. */
  94093. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  94094. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  94095. };
  94096. /**
  94097. * Standard reflectance value at parallel view angle.
  94098. */
  94099. BackgroundMaterial.StandardReflectance0 = 0.05;
  94100. /**
  94101. * Standard reflectance value at grazing angle.
  94102. */
  94103. BackgroundMaterial.StandardReflectance90 = 0.5;
  94104. __decorate([
  94105. BABYLON.serializeAsColor3()
  94106. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  94107. __decorate([
  94108. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94109. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  94110. __decorate([
  94111. BABYLON.serialize()
  94112. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  94113. __decorate([
  94114. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94115. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  94116. __decorate([
  94117. BABYLON.serializeAsColor3()
  94118. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  94119. __decorate([
  94120. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94121. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  94122. __decorate([
  94123. BABYLON.serialize()
  94124. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  94125. __decorate([
  94126. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94127. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  94128. __decorate([
  94129. BABYLON.serializeAsColor3()
  94130. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  94131. __decorate([
  94132. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94133. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  94134. __decorate([
  94135. BABYLON.serialize()
  94136. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  94137. __decorate([
  94138. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94139. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  94140. __decorate([
  94141. BABYLON.serializeAsTexture()
  94142. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  94143. __decorate([
  94144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94145. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  94146. __decorate([
  94147. BABYLON.serialize()
  94148. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  94149. __decorate([
  94150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94151. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  94152. __decorate([
  94153. BABYLON.serializeAsTexture()
  94154. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  94155. __decorate([
  94156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94157. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  94158. __decorate([
  94159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94160. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  94161. __decorate([
  94162. BABYLON.serialize()
  94163. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  94164. __decorate([
  94165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94166. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  94167. __decorate([
  94168. BABYLON.serialize()
  94169. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  94170. __decorate([
  94171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94172. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  94173. __decorate([
  94174. BABYLON.serializeAsVector3()
  94175. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  94176. __decorate([
  94177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94178. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  94179. __decorate([
  94180. BABYLON.serialize()
  94181. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  94182. __decorate([
  94183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94184. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  94185. __decorate([
  94186. BABYLON.serialize()
  94187. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  94188. __decorate([
  94189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94190. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  94191. __decorate([
  94192. BABYLON.serialize()
  94193. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  94194. __decorate([
  94195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94196. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  94197. __decorate([
  94198. BABYLON.serialize()
  94199. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  94200. __decorate([
  94201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94202. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  94203. __decorate([
  94204. BABYLON.serialize()
  94205. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  94206. __decorate([
  94207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94208. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  94209. __decorate([
  94210. BABYLON.serialize()
  94211. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  94212. __decorate([
  94213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94214. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  94215. __decorate([
  94216. BABYLON.serialize()
  94217. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  94218. __decorate([
  94219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94220. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  94221. __decorate([
  94222. BABYLON.serialize()
  94223. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  94224. __decorate([
  94225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94226. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  94227. __decorate([
  94228. BABYLON.serialize()
  94229. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  94230. __decorate([
  94231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94232. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  94233. __decorate([
  94234. BABYLON.serializeAsImageProcessingConfiguration()
  94235. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  94236. return BackgroundMaterial;
  94237. }(BABYLON.PushMaterial));
  94238. BABYLON.BackgroundMaterial = BackgroundMaterial;
  94239. })(BABYLON || (BABYLON = {}));
  94240. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  94241. "use strict";
  94242. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94243. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94244. s = arguments[i];
  94245. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94246. t[p] = s[p];
  94247. }
  94248. return t;
  94249. };
  94250. var BABYLON;
  94251. (function (BABYLON) {
  94252. /**
  94253. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  94254. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  94255. * It also helps with the default setup of your imageProcessing configuration.
  94256. */
  94257. var EnvironmentHelper = /** @class */ (function () {
  94258. /**
  94259. * constructor
  94260. * @param options
  94261. * @param scene The scene to add the material to
  94262. */
  94263. function EnvironmentHelper(options, scene) {
  94264. var _this = this;
  94265. this._errorHandler = function (message, exception) {
  94266. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  94267. };
  94268. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  94269. this._scene = scene;
  94270. this.onErrorObservable = new BABYLON.Observable();
  94271. this._setupBackground();
  94272. this._setupImageProcessing();
  94273. }
  94274. /**
  94275. * Creates the default options for the helper.
  94276. */
  94277. EnvironmentHelper._getDefaultOptions = function () {
  94278. return {
  94279. createGround: true,
  94280. groundSize: 15,
  94281. groundTexture: this._groundTextureCDNUrl,
  94282. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94283. groundOpacity: 0.9,
  94284. enableGroundShadow: true,
  94285. groundShadowLevel: 0.5,
  94286. enableGroundMirror: false,
  94287. groundMirrorSizeRatio: 0.3,
  94288. groundMirrorBlurKernel: 64,
  94289. groundMirrorAmount: 1,
  94290. groundMirrorFresnelWeight: 1,
  94291. groundMirrorFallOffDistance: 0,
  94292. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  94293. groundYBias: 0.00001,
  94294. createSkybox: true,
  94295. skyboxSize: 20,
  94296. skyboxTexture: this._skyboxTextureCDNUrl,
  94297. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94298. backgroundYRotation: 0,
  94299. sizeAuto: true,
  94300. rootPosition: BABYLON.Vector3.Zero(),
  94301. setupImageProcessing: true,
  94302. environmentTexture: this._environmentTextureCDNUrl,
  94303. cameraExposure: 0.8,
  94304. cameraContrast: 1.2,
  94305. toneMappingEnabled: true,
  94306. };
  94307. };
  94308. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  94309. /**
  94310. * Gets the root mesh created by the helper.
  94311. */
  94312. get: function () {
  94313. return this._rootMesh;
  94314. },
  94315. enumerable: true,
  94316. configurable: true
  94317. });
  94318. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  94319. /**
  94320. * Gets the skybox created by the helper.
  94321. */
  94322. get: function () {
  94323. return this._skybox;
  94324. },
  94325. enumerable: true,
  94326. configurable: true
  94327. });
  94328. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  94329. /**
  94330. * Gets the skybox texture created by the helper.
  94331. */
  94332. get: function () {
  94333. return this._skyboxTexture;
  94334. },
  94335. enumerable: true,
  94336. configurable: true
  94337. });
  94338. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  94339. /**
  94340. * Gets the skybox material created by the helper.
  94341. */
  94342. get: function () {
  94343. return this._skyboxMaterial;
  94344. },
  94345. enumerable: true,
  94346. configurable: true
  94347. });
  94348. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  94349. /**
  94350. * Gets the ground mesh created by the helper.
  94351. */
  94352. get: function () {
  94353. return this._ground;
  94354. },
  94355. enumerable: true,
  94356. configurable: true
  94357. });
  94358. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  94359. /**
  94360. * Gets the ground texture created by the helper.
  94361. */
  94362. get: function () {
  94363. return this._groundTexture;
  94364. },
  94365. enumerable: true,
  94366. configurable: true
  94367. });
  94368. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  94369. /**
  94370. * Gets the ground mirror created by the helper.
  94371. */
  94372. get: function () {
  94373. return this._groundMirror;
  94374. },
  94375. enumerable: true,
  94376. configurable: true
  94377. });
  94378. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  94379. /**
  94380. * Gets the ground mirror render list to helps pushing the meshes
  94381. * you wish in the ground reflection.
  94382. */
  94383. get: function () {
  94384. if (this._groundMirror) {
  94385. return this._groundMirror.renderList;
  94386. }
  94387. return null;
  94388. },
  94389. enumerable: true,
  94390. configurable: true
  94391. });
  94392. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  94393. /**
  94394. * Gets the ground material created by the helper.
  94395. */
  94396. get: function () {
  94397. return this._groundMaterial;
  94398. },
  94399. enumerable: true,
  94400. configurable: true
  94401. });
  94402. /**
  94403. * Updates the background according to the new options
  94404. * @param options
  94405. */
  94406. EnvironmentHelper.prototype.updateOptions = function (options) {
  94407. var newOptions = __assign({}, this._options, options);
  94408. if (this._ground && !newOptions.createGround) {
  94409. this._ground.dispose();
  94410. this._ground = null;
  94411. }
  94412. if (this._groundMaterial && !newOptions.createGround) {
  94413. this._groundMaterial.dispose();
  94414. this._groundMaterial = null;
  94415. }
  94416. if (this._groundTexture) {
  94417. if (this._options.groundTexture != newOptions.groundTexture) {
  94418. this._groundTexture.dispose();
  94419. this._groundTexture = null;
  94420. }
  94421. }
  94422. if (this._skybox && !newOptions.createSkybox) {
  94423. this._skybox.dispose();
  94424. this._skybox = null;
  94425. }
  94426. if (this._skyboxMaterial && !newOptions.createSkybox) {
  94427. this._skyboxMaterial.dispose();
  94428. this._skyboxMaterial = null;
  94429. }
  94430. if (this._skyboxTexture) {
  94431. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  94432. this._skyboxTexture.dispose();
  94433. this._skyboxTexture = null;
  94434. }
  94435. }
  94436. if (this._groundMirror && !newOptions.enableGroundMirror) {
  94437. this._groundMirror.dispose();
  94438. this._groundMirror = null;
  94439. }
  94440. if (this._scene.environmentTexture) {
  94441. if (this._options.environmentTexture != newOptions.environmentTexture) {
  94442. this._scene.environmentTexture.dispose();
  94443. }
  94444. }
  94445. this._options = newOptions;
  94446. this._setupBackground();
  94447. this._setupImageProcessing();
  94448. };
  94449. /**
  94450. * Sets the primary color of all the available elements.
  94451. * @param color
  94452. */
  94453. EnvironmentHelper.prototype.setMainColor = function (color) {
  94454. if (this.groundMaterial) {
  94455. this.groundMaterial.primaryColor = color;
  94456. }
  94457. if (this.skyboxMaterial) {
  94458. this.skyboxMaterial.primaryColor = color;
  94459. }
  94460. if (this.groundMirror) {
  94461. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  94462. }
  94463. };
  94464. /**
  94465. * Setup the image processing according to the specified options.
  94466. */
  94467. EnvironmentHelper.prototype._setupImageProcessing = function () {
  94468. if (this._options.setupImageProcessing) {
  94469. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  94470. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  94471. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  94472. this._setupEnvironmentTexture();
  94473. }
  94474. };
  94475. /**
  94476. * Setup the environment texture according to the specified options.
  94477. */
  94478. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  94479. if (this._scene.environmentTexture) {
  94480. return;
  94481. }
  94482. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  94483. this._scene.environmentTexture = this._options.environmentTexture;
  94484. return;
  94485. }
  94486. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  94487. this._scene.environmentTexture = environmentTexture;
  94488. };
  94489. /**
  94490. * Setup the background according to the specified options.
  94491. */
  94492. EnvironmentHelper.prototype._setupBackground = function () {
  94493. if (!this._rootMesh) {
  94494. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  94495. }
  94496. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  94497. var sceneSize = this._getSceneSize();
  94498. if (this._options.createGround) {
  94499. this._setupGround(sceneSize);
  94500. this._setupGroundMaterial();
  94501. this._setupGroundDiffuseTexture();
  94502. if (this._options.enableGroundMirror) {
  94503. this._setupGroundMirrorTexture(sceneSize);
  94504. }
  94505. this._setupMirrorInGroundMaterial();
  94506. }
  94507. if (this._options.createSkybox) {
  94508. this._setupSkybox(sceneSize);
  94509. this._setupSkyboxMaterial();
  94510. this._setupSkyboxReflectionTexture();
  94511. }
  94512. this._rootMesh.position.x = sceneSize.rootPosition.x;
  94513. this._rootMesh.position.z = sceneSize.rootPosition.z;
  94514. this._rootMesh.position.y = sceneSize.rootPosition.y;
  94515. };
  94516. /**
  94517. * Get the scene sizes according to the setup.
  94518. */
  94519. EnvironmentHelper.prototype._getSceneSize = function () {
  94520. var _this = this;
  94521. var groundSize = this._options.groundSize;
  94522. var skyboxSize = this._options.skyboxSize;
  94523. var rootPosition = this._options.rootPosition;
  94524. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  94525. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  94526. }
  94527. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  94528. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  94529. });
  94530. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  94531. if (this._options.sizeAuto) {
  94532. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  94533. this._scene.activeCamera.upperRadiusLimit) {
  94534. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  94535. skyboxSize = groundSize;
  94536. }
  94537. var sceneDiagonalLenght = sceneDiagonal.length();
  94538. if (sceneDiagonalLenght > groundSize) {
  94539. groundSize = sceneDiagonalLenght * 2;
  94540. skyboxSize = groundSize;
  94541. }
  94542. // 10 % bigger.
  94543. groundSize *= 1.1;
  94544. skyboxSize *= 1.5;
  94545. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  94546. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  94547. }
  94548. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  94549. };
  94550. /**
  94551. * Setup the ground according to the specified options.
  94552. */
  94553. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  94554. var _this = this;
  94555. if (!this._ground) {
  94556. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  94557. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  94558. this._ground.parent = this._rootMesh;
  94559. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  94560. }
  94561. this._ground.receiveShadows = this._options.enableGroundShadow;
  94562. };
  94563. /**
  94564. * Setup the ground material according to the specified options.
  94565. */
  94566. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  94567. if (!this._groundMaterial) {
  94568. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  94569. }
  94570. this._groundMaterial.alpha = this._options.groundOpacity;
  94571. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  94572. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  94573. this._groundMaterial.primaryLevel = 1;
  94574. this._groundMaterial.primaryColor = this._options.groundColor;
  94575. this._groundMaterial.secondaryLevel = 0;
  94576. this._groundMaterial.tertiaryLevel = 0;
  94577. this._groundMaterial.useRGBColor = false;
  94578. this._groundMaterial.enableNoise = true;
  94579. if (this._ground) {
  94580. this._ground.material = this._groundMaterial;
  94581. }
  94582. };
  94583. /**
  94584. * Setup the ground diffuse texture according to the specified options.
  94585. */
  94586. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  94587. if (!this._groundMaterial) {
  94588. return;
  94589. }
  94590. if (this._groundTexture) {
  94591. return;
  94592. }
  94593. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  94594. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  94595. return;
  94596. }
  94597. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  94598. diffuseTexture.gammaSpace = false;
  94599. diffuseTexture.hasAlpha = true;
  94600. this._groundMaterial.diffuseTexture = diffuseTexture;
  94601. };
  94602. /**
  94603. * Setup the ground mirror texture according to the specified options.
  94604. */
  94605. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  94606. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94607. if (!this._groundMirror) {
  94608. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  94609. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  94610. this._groundMirror.anisotropicFilteringLevel = 1;
  94611. this._groundMirror.wrapU = wrapping;
  94612. this._groundMirror.wrapV = wrapping;
  94613. this._groundMirror.gammaSpace = false;
  94614. if (this._groundMirror.renderList) {
  94615. for (var i = 0; i < this._scene.meshes.length; i++) {
  94616. var mesh = this._scene.meshes[i];
  94617. if (mesh !== this._ground &&
  94618. mesh !== this._skybox &&
  94619. mesh !== this._rootMesh) {
  94620. this._groundMirror.renderList.push(mesh);
  94621. }
  94622. }
  94623. }
  94624. }
  94625. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  94626. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  94627. };
  94628. /**
  94629. * Setup the ground to receive the mirror texture.
  94630. */
  94631. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  94632. if (this._groundMaterial) {
  94633. this._groundMaterial.reflectionTexture = this._groundMirror;
  94634. this._groundMaterial.reflectionFresnel = true;
  94635. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  94636. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  94637. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  94638. }
  94639. };
  94640. /**
  94641. * Setup the skybox according to the specified options.
  94642. */
  94643. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  94644. var _this = this;
  94645. if (!this._skybox) {
  94646. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  94647. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  94648. }
  94649. this._skybox.parent = this._rootMesh;
  94650. };
  94651. /**
  94652. * Setup the skybox material according to the specified options.
  94653. */
  94654. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  94655. if (!this._skybox) {
  94656. return;
  94657. }
  94658. if (!this._skyboxMaterial) {
  94659. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  94660. }
  94661. this._skyboxMaterial.useRGBColor = false;
  94662. this._skyboxMaterial.primaryLevel = 1;
  94663. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  94664. this._skyboxMaterial.secondaryLevel = 0;
  94665. this._skyboxMaterial.tertiaryLevel = 0;
  94666. this._skyboxMaterial.enableNoise = true;
  94667. this._skybox.material = this._skyboxMaterial;
  94668. };
  94669. /**
  94670. * Setup the skybox reflection texture according to the specified options.
  94671. */
  94672. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  94673. if (!this._skyboxMaterial) {
  94674. return;
  94675. }
  94676. if (this._skyboxTexture) {
  94677. return;
  94678. }
  94679. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  94680. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  94681. return;
  94682. }
  94683. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  94684. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  94685. this._skyboxTexture.gammaSpace = false;
  94686. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  94687. };
  94688. /**
  94689. * Dispose all the elements created by the Helper.
  94690. */
  94691. EnvironmentHelper.prototype.dispose = function () {
  94692. if (this._groundMaterial) {
  94693. this._groundMaterial.dispose(true, true);
  94694. }
  94695. if (this._skyboxMaterial) {
  94696. this._skyboxMaterial.dispose(true, true);
  94697. }
  94698. this._rootMesh.dispose(false);
  94699. };
  94700. /**
  94701. * Default ground texture URL.
  94702. */
  94703. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  94704. /**
  94705. * Default skybox texture URL.
  94706. */
  94707. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  94708. /**
  94709. * Default environment texture URL.
  94710. */
  94711. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  94712. return EnvironmentHelper;
  94713. }());
  94714. BABYLON.EnvironmentHelper = EnvironmentHelper;
  94715. })(BABYLON || (BABYLON = {}));
  94716. //# sourceMappingURL=babylon.environmentHelper.js.map
  94717. "use strict";
  94718. var BABYLON;
  94719. (function (BABYLON) {
  94720. /**
  94721. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  94722. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  94723. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  94724. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  94725. */
  94726. var VideoDome = /** @class */ (function (_super) {
  94727. __extends(VideoDome, _super);
  94728. /**
  94729. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  94730. * @param name Element's name, child elements will append suffixes for their own names.
  94731. * @param urlsOrVideo
  94732. * @param options An object containing optional or exposed sub element properties:
  94733. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  94734. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  94735. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  94736. * @param options **loop=true** Automatically loop video on end.
  94737. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  94738. */
  94739. function VideoDome(name, urlsOrVideo, options, scene) {
  94740. var _this = _super.call(this, name, scene) || this;
  94741. // set defaults and manage values
  94742. name = name || "videoDome";
  94743. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  94744. options.clickToPlay = Boolean(options.clickToPlay);
  94745. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  94746. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  94747. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  94748. // create
  94749. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  94750. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  94751. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  94752. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  94753. flat: false,
  94754. radius: options.size,
  94755. subdivisions: options.resolution,
  94756. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  94757. }, scene);
  94758. // configure material
  94759. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  94760. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  94761. material.reflectionTexture = _this._videoTexture;
  94762. material.useEquirectangularFOV = true;
  94763. material.fovMultiplier = 1.0;
  94764. // configure mesh
  94765. _this._mesh.material = material;
  94766. _this._mesh.parent = _this;
  94767. // optional configuration
  94768. if (options.clickToPlay) {
  94769. scene.onPointerUp = function () {
  94770. _this._videoTexture.video.play();
  94771. };
  94772. }
  94773. return _this;
  94774. }
  94775. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  94776. /**
  94777. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94778. * Also see the options.resolution property.
  94779. */
  94780. get: function () {
  94781. return this._material.fovMultiplier;
  94782. },
  94783. set: function (value) {
  94784. this._material.fovMultiplier = value;
  94785. },
  94786. enumerable: true,
  94787. configurable: true
  94788. });
  94789. /**
  94790. * Releases resources associated with this node.
  94791. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  94792. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  94793. */
  94794. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  94795. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  94796. this._videoTexture.dispose();
  94797. this._mesh.dispose();
  94798. this._material.dispose();
  94799. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  94800. };
  94801. return VideoDome;
  94802. }(BABYLON.Node));
  94803. BABYLON.VideoDome = VideoDome;
  94804. })(BABYLON || (BABYLON = {}));
  94805. //# sourceMappingURL=babylon.videoDome.js.map
  94806. 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) || defined(GEOMETRYAA)\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#ifdef GEOMETRYAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\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#ifdef GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\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}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \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{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\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\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{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\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;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,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"};
  94807. 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,geometricRoughnessFactor,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,geometricRoughnessFactor,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,geometricRoughnessFactor,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,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\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,float geometricRoughnessFactor,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,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \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\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\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);
  94808. globalObject["BABYLON"] = BABYLON;
  94809. 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 serializeAsCameraReference = BABYLON.serializeAsCameraReference;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 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 Debug = BABYLON.Debug ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  94810. 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,serializeAsCameraReference,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,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 ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };